branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>Crekan/qrcode_enter<file_sep>/qrcode_enter/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MessagingToolkit.QRCode.Codec;
using MessagingToolkit.QRCode.Codec.Data;
namespace qrcode_enter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Height = 366; //высота формы
pictureBox1.Visible = !pictureBox1.Visible; //смена отображения pictureBox'a
this.button1.Visible = false; //скрываем button1
}
private void button2_Click(object sender, EventArgs e)
{
Random rand = new Random(); //создаём новый генератор рандомных чисел
int i = rand.Next(100000, 999999); // в переменную i заносим рандомное число в пределах от 100000 до 999999 (все шестизначные числа)
string qrimage = Convert.ToString(i); //конвеорируем i в string и записываем его значение в переменную qrimage
QRCodeEncoder encoder = new QRCodeEncoder(); // создаём новое кодирование qr-кода
Bitmap qrcode = encoder.Encode(qrimage); // получаем закодированное изображение в классе работы с изображением bitmap.
pictureBox1.Image = qrcode as Image; // выводит полученное изображение как рисунок в pictureBox1.
}
private void button3_Click(object sender, EventArgs e)
{
QRCodeDecoder decoder = new QRCodeDecoder(); // создаём новое раскодирование qr-кода
string s = decoder.decode(new QRCodeBitmapImage(pictureBox1.Image as Bitmap)); //добавляем в стринговскую переменную s результат раскодирования изображения из pictureBox1
if (textBox1.Text == s) //если строка, которую введёт пользователь, равна раскодированной с pictureBox1 строке.
{
this.Height = 101; //уменьшаем высоту окна формы до изначальной
pictureBox1.Visible = !pictureBox1.Visible; //скрываем pictureBox1
label2.Visible = !label2.Visible; //показываем текст "Вы успешно авторизировались".
}
else //иначе
{
MessageBox.Show("Вы ввели неверное число. Авторизируйтесь заново."); //появится MessageBox с данным сообщением
this.Height = 101; //уменьшаем высоту окна формы до изначальной
pictureBox1.Visible = !pictureBox1.Visible; //скрываем pictureBox1
button1.Visible = !button1.Visible; //отображаем кнопку "Авторизироваться", чтобы начать авторизацию заново, пользователю снова придётся её нажать, и снова сработает код из button1_Click
Random rand = new Random(); //снова создаём генератор рандомных чисел и переводим это число в изображение qr-кода
int i = rand.Next(100000, 999999);
string qrimage = Convert.ToString(i);
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap qrcode = encoder.Encode(qrimage);
pictureBox1.Image = qrcode as Image;
textBox1.Text = ""; //стираем прошлое значение, которое заносил в textBox пользователь.
}
}
}
}
|
e0b8b3bcebda4c7e11622e3f03e4b11fbb91ff15
|
[
"C#"
] | 1 |
C#
|
Crekan/qrcode_enter
|
2cc61a407edf17476d9d89c75f99495dc88d0ab6
|
bd778cceb017ba6b330edaeecde60a3f6d539d4c
|
refs/heads/master
|
<repo_name>lenoncorrea/curso-flask-alura<file_sep>/README.md
# curso-flask-alura
<file_sep>/jogoteca.py
#!/home/lenon/Nextcloud/projetos/Alura\ Cursos/Flask\ parte\ 1/venv/bin/python
from flask import Flask
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = MySQL(app)
from views import *
if __name__== '__main__':
app.run(debug=True)<file_sep>/config.py
import os
SECRET_KEY = 'jogoteca'
MYSQL_HOST = "0.0.0.0"
MYSQL_USER = "jogoteca"
MYSQL_PASSWORD = "<PASSWORD>"
MYSQL_DB = "jogoteca"
MYSQL_PORT = 3306
UPLOAD_PATH = os.path.dirname(os.path.abspath(__file__)) + '/uploads'<file_sep>/models.py
class Jogo:
def __init__(self,nome,categoria,console,id=None):
self.id = id
self.nome = nome
self.categoria = categoria
self.console = console
class Usuario:
def __init__(self,id,nome,senha):
self.id = id
self.nome = nome
self.senha = senha
|
664feefafe854e116575177512a2555e96199b95
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
lenoncorrea/curso-flask-alura
|
0771bff3674918b4559a3dd323e3e82401a44d9a
|
cb667635c3db11b5172e33c431c1990d67fd7731
|
refs/heads/main
|
<repo_name>jerryzhou3/Algorithm_And_Data_Structures<file_sep>/TestCase.h
//
// Created by jerryzhou3 on 1/4/2021.
//
#ifndef DATASTRUCTURES_TESTCASE_H
#define DATASTRUCTURES_TESTCASE_H
#include "BinarySearchTree.h"
#include "AVLTree.h"
#include "MinHeap.h"
#include "QuickSort.h"
class TestCase {
static void doTestBinarySearchTree();
static void doTestAVLTree();
static void doTestMinHeap();
static void doTestQuickSort();
public:
static void testBinarySearchTree();
static void testAVLTree();
static void testMinHeap();
static void testQuickSort();
};
#endif //DATASTRUCTURES_TESTCASE_H
<file_sep>/BinarySearchTree.cpp
//
// Created by jerryzhou3 on 1/4/2021.
//
#include "BinarySearchTree.h"
void BinarySearchTree::insert(int x) {
TreeNode* temp = this->root;
TreeNode* prev = nullptr;
while (temp) {
prev = temp;
if (temp->val == x) return;
else if (temp->val < x) temp = temp->right;
else temp = temp->left;
}
auto* node = new TreeNode(x);
if (!prev) this->root = node;
else {
if (prev->val > x) prev->left = node;
else prev->right = node;
}
}
bool BinarySearchTree::contains(int x) {
TreeNode* temp = this->root;
while (temp) {
if (temp->val == x) return true;
else if (temp->val < x) temp = temp->right;
else temp = temp->left;
}
return false;
}
int BinarySearchTree::getMin() {
if (!this->root) return 0;
TreeNode* temp = this->root;
while (temp->left) {
temp = temp->left;
}
return temp->val;
}
int BinarySearchTree::getMax() {
if (!this->root) return 0;
TreeNode* temp = this->root;
while (temp->right) {
temp = temp->right;
}
return temp->val;
}
int BinarySearchTree::getHeight() {
struct recursion {
static int getHeight_rec(TreeNode* root) {
if (!root) return 0;
else return 1 + std::max(getHeight_rec(root->left), getHeight_rec(root->right));
}
};
return recursion::getHeight_rec(this->root);
}
void BinarySearchTree::remove(int x) {
TreeNode* temp = this->root;
TreeNode* prev = nullptr;
while (temp && temp->val != x) {
prev = temp;
if (temp->val < x) temp = temp->right;
else temp = temp->left;
}
if (!temp) return;
if (!prev) {
delete this->root;
this->root = nullptr;
return;
}
if (prev->val < temp->val) {
if (temp->left && temp->right) {
prev->right = temp->left;
temp->left->right = temp->right;
}
else if (temp->left) prev->right = temp->left;
else if (temp->right) prev->right = temp->right;
else prev->right = nullptr;
}
else {
if (temp->left && temp->right) {
prev->left = temp->right;
temp->right->left = temp->left;
}
else if (temp->left) prev->left = temp->left;
else if (temp->right) prev->left = temp->right;
else prev->left = nullptr;
}
delete temp;
}
bool BinarySearchTree::isFull() {
struct recursion{
static bool isFull_rec(TreeNode* root) {
if (!root) return true;
if (!root->left == !root->right) return isFull_rec(root->left) && isFull_rec(root->right);
else return false;
}
};
return recursion::isFull_rec(this->root);
}
bool BinarySearchTree::isBalanced() {
struct recursion {
static int getHeight_rec(TreeNode* root) {
if (!root) return 0;
else return 1 + std::max(getHeight_rec(root->left), getHeight_rec(root->right));
}
static bool isBalanced(TreeNode* root) {
if (!root) return true;
else return std::abs(getHeight_rec(root->left) - getHeight_rec(root->right)) <= 1;
}
};
return recursion::isBalanced(this->root);
}
void BinarySearchTree::printTree() {
if (!this->root) std::cout << "Empty Tree" << std::endl;
std::cout << "Print Tree: " << std::endl;
std::queue<TreeNode*> q;
q.push(this->root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
if (i < size - 1) {
if (!node) std::cout << "null ";
else std::cout << node->val << " ";
}
else {
if (!node) std::cout << "null" << std::endl;
else std::cout << node->val << std::endl;
}
if (node) {
q.push(node->left);
q.push(node->right);
}
}
}
}<file_sep>/TestCase.cpp
//
// Created by jerryzhou3 on 1/4/2021.
//
#include "TestCase.h"
void TestCase::doTestBinarySearchTree() {
auto* BST = new BinarySearchTree();
std::cout << "insert 5" << std::endl;
BST->insert(5);
std::cout << "insert 3" << std::endl;
BST->insert(3);
std::cout << "insert 10" << std::endl;
BST->insert(10);
std::cout << "insert 7" << std::endl;
BST->insert(7);
std::cout << "insert 4" << std::endl;
BST->insert(4);
std::cout << std::endl;
std::cout << "height: " << BST->getHeight() << std::endl;
std::cout << "max: " << BST->getMax() << std::endl;
std::cout << "min: " << BST->getMin() << std::endl;
std::cout << "contains 7: " << std::boolalpha << BST->contains(7) << std::endl;
std::cout << "contains 6: " << std::boolalpha << BST->contains(6) << std::endl;
std::cout << "is full: " << std::boolalpha << BST->isFull() << std::endl;
std::cout << "is balanced: " << std::boolalpha << BST->isBalanced() << std::endl;
BST->printTree();
std::cout << std::endl;
std::cout << "remove 3" << std::endl;
BST->remove(3);
BST->printTree();
std::cout << std::endl;
std::cout << "insert 3" << std::endl;
BST->insert(3);
BST->printTree();
std::cout << std::endl;
std::cout << "remove 3" << std::endl;
BST->remove(3);
std::cout << "remove 7" << std::endl;
BST->remove(7);
std::cout << "is full: " << std::boolalpha << BST->isFull() << std::endl;
BST->printTree();
std::cout << std::endl;
std::cout << "insert 3" << std::endl;
BST->insert(3);
std::cout << "insert 2" << std::endl;
BST->insert(2);
std::cout << "insert 1" << std::endl;
BST->insert(1);
BST->printTree();
std::cout << std::endl;
std::cout << "is balanced: " << std::boolalpha << BST->isBalanced() << std::endl;
delete BST;
}
void TestCase::doTestAVLTree() {
auto* AVL = new AVLTree();
std::cout << "insert 1" << std::endl;
AVL->insert(1);
std::cout << "insert 2" << std::endl;
AVL->insert(2);
std::cout << "insert 3" << std::endl;
AVL->insert(3);
std::cout << "insert 7" << std::endl;
AVL->insert(7);
std::cout << "insert 10" << std::endl;
AVL->insert(10);
std::cout << "insert 4" << std::endl;
AVL->insert(4);
std::cout << "remove 1" << std::endl;
AVL->remove(1);
std::cout << "remove 2" << std::endl;
AVL->remove(2);
std::cout << std::endl;
std::cout << "height: " << AVL->getHeight() << std::endl;
std::cout << "max: " << AVL->getMax() << std::endl;
std::cout << "min: " << AVL->getMin() << std::endl;
std::cout << "contains 7: " << std::boolalpha << AVL->contains(7) << std::endl;
std::cout << "contains 6: " << std::boolalpha << AVL->contains(6) << std::endl;
std::cout << "is full: " << std::boolalpha << AVL->isFull() << std::endl;
AVL->printTree();
std::cout << std::endl;
delete AVL;
}
void TestCase::testBinarySearchTree() {
std::cout << std::endl << "<TEST BinarySearchTree>" << std::endl << std::endl;
doTestBinarySearchTree();
}
void TestCase::testAVLTree() {
std::cout << std::endl << "<TEST AVLTree>" << std::endl << std::endl;
doTestAVLTree();
}
void TestCase::testMinHeap() {
std::cout << std::endl << "<TEST MinHeap>" << std::endl << std::endl;
doTestMinHeap();
}
void TestCase::doTestMinHeap() {
auto* HEAP = new MinHeap(20);
std::cout << "INSERT: 10, 5, 7, 1, 3, 20" << std::endl;
HEAP->insert(10);
HEAP->insert(5);
HEAP->insert(7);
HEAP->insert(1);
HEAP->insert(3);
HEAP->insert(20);
std::cout << "EXTRACT MIN:" << std::endl;
std::cout << HEAP->extractMin() << std::endl;
std::cout << HEAP->extractMin() << std::endl;
std::cout << HEAP->extractMin() << std::endl;
std::cout << HEAP->extractMin() << std::endl;
std::cout << HEAP->extractMin() << std::endl;
std::cout << HEAP->extractMin() << std::endl;
std::cout << HEAP->extractMin() << std::endl;
delete HEAP;
}
void TestCase::doTestQuickSort() {
std::vector<int> array;
array.push_back(5);
array.push_back(3);
array.push_back(2);
array.push_back(6);
array.push_back(10);
array.push_back(-1);
array.push_back(300);
array.push_back(1);
QuickSort::quickSort(array);
for (auto i : array) {
std::cout << i << std::endl;
}
}
void TestCase::testQuickSort() {
std::cout << std::endl << "<TEST QuickSort>" << std::endl << std::endl;
doTestQuickSort();
}
<file_sep>/MinHeap.h
//
// Created by jerryzhou3 on 2/2/2021.
//
#ifndef DATASTRUCTURES_MINHEAP_H
#define DATASTRUCTURES_MINHEAP_H
#include <iostream>
#include <limits.h>
class MinHeap {
int* array;
int capacity;
int size;
public:
MinHeap(int capacity);
~MinHeap();
int getParent(int i);
int getLeft(int i);
int getRight(int i);
int extractMin();
void insert(int k);
void MinHeapfy(int i);
};
#endif //DATASTRUCTURES_MINHEAP_H
<file_sep>/MinHeap.cpp
//
// Created by jerryzhou3 on 2/2/2021.
//
#include "MinHeap.h"
MinHeap::MinHeap(int capacity) {
this->capacity = capacity;
this->size = 0;
this->array = new int[capacity];
}
MinHeap::~MinHeap() {
delete[] this->array;
}
int MinHeap::getParent(int i) {
return (i - 1) / 2;
}
int MinHeap::getLeft(int i) {
return i * 2 + 1;
}
int MinHeap::getRight(int i) {
return i * 2 + 2;
}
int MinHeap::extractMin() {
if (this->size <= 0) return INT_MAX;
if (this->size == 1) {
--this->size;
return this->array[0];
}
int res = this->array[0];
this->array[0] = this->array[this->size-1];
--this->size;
MinHeapfy(0);
return res;
}
void MinHeap::MinHeapfy(int i) {
int left = getLeft(i);
int right = getRight(i);
int smallest = i;
if (left < this->size && this->array[left] < this->array[smallest]) smallest = left;
if (right < this->size && this->array[right] < this->array[smallest]) smallest = right;
if (smallest != i) {
int temp = this->array[smallest];
this->array[smallest] = this->array[i];
this->array[i] = temp;
MinHeapfy(smallest);
}
}
void MinHeap::insert(int k) {
if (this->size >= this->capacity) {
std::cout << "Heap full, cannot insert!" << std::endl;
return;
}
++this->size;
int idx = this->size - 1;
this->array[idx] = k;
while (idx > 0 && this->array[getParent(idx)] > k) {
this->array[idx] = this->array[getParent(idx)];
this->array[getParent(idx)] = k;
idx = getParent(idx);
}
}
<file_sep>/main.cpp
#include "TestCase.h"
int main() {
TestCase::testBinarySearchTree();
TestCase::testAVLTree();
TestCase::testMinHeap();
return 0;
}
<file_sep>/README.md
### C++ implementation of important data structures and LeetCode excercises
#### Binary Search Tree
<pre>
<a href="BinarySearchTree.h">BinarySearchTree.h</a>
<a href="BinarySearchTree.cpp">BinarySearchTree.cpp</a>
</pre>
#### AVL Tree
<pre>
<a href="AVLTree.h">AVLTree.h</a>
<a href="AVLTree.cpp">AVLTree.cpp</a>
<a href="https://www.geeksforgeeks.org/avl-tree-set-1-insertion/">AVL tree rotation explained</a>
<a href="https://www.cs.usfca.edu/~galles/visualization/AVLtree.html">AVL tree visualization</a>
</pre>
#### Min Heap
<pre>
<a href="MinHeap.h">MinHeap.h</a>
<a href="MinHeap.cpp">MinHeap.cpp</a>
<a href="https://www.geeksforgeeks.org/binary-heap/">Min Heap explained</a>
</pre><file_sep>/SegmentTree.h
//
// Created by jerryzhou3 on 2021/7/24.
//
#ifndef CODING_AND_DATA_STRUCTURES_SEGMENTTREE_H
#define CODING_AND_DATA_STRUCTURES_SEGMENTTREE_H
#include <vector>
#include <algorithm>
class SegmentTree {
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(): val(0), left(nullptr), right(nullptr) {}
TreeNode(int val): val(val), left(nullptr), right(nullptr) {}
TreeNode(int val, TreeNode* left, TreeNode* right): val(val), left(left), right(right) {}
};
TreeNode* root;
std::vector<int> array;
public:
SegmentTree(std::vector<int> array): root(nullptr) {
sort(array.begin(), array.end());
this->array = array;
}
SegmentTree(): root(nullptr), array(std::vector<int>()) {}
void insert(int val);
private:
void construct_tree_from_array();
TreeNode* construct_tree_rec(std::vector<int>& array, int left, int right);
void insert_and_sort_array(int val);
};
#endif //CODING_AND_DATA_STRUCTURES_SEGMENTTREE_H
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(DataStructures)
set(CMAKE_CXX_STANDARD 11)
add_executable(DataStructures main.cpp BinarySearchTree.cpp BinarySearchTree.h TestCase.cpp TestCase.h AVLTree.cpp AVLTree.h MinHeap.cpp MinHeap.h QuickSort.cpp QuickSort.h SegmentTree.cpp SegmentTree.h)<file_sep>/SegmentTree.cpp
//
// Created by jerryzhou3 on 2021/7/24.
//
#include "SegmentTree.h"
void SegmentTree::insert(int val) {
this->insert_and_sort_array(val);
}
void SegmentTree::construct_tree_from_array() {
this->root = this->construct_tree_rec(this->array, 0, this->array.size() - 1);
}
SegmentTree::TreeNode* SegmentTree::construct_tree_rec(std::vector<int> &arr, int left, int right) {
int mid = (left + right) / 2;
if (left == right) {
TreeNode* newNode = new TreeNode(arr[mid]);
return newNode;
}
else {
TreeNode* newNode = new TreeNode();
TreeNode* leftNode = this->construct_tree_rec(arr, left, mid);
TreeNode* rightNode = this->construct_tree_rec(arr, mid + 1, right);
newNode->val = leftNode->val + rightNode->val;
newNode->left = leftNode;
newNode->right = rightNode;
return newNode;
}
}
void SegmentTree::insert_and_sort_array(int val) {
if (this->array.empty()) {
this->array.push_back(val);
}
else {
auto it = this->array.begin();
while (it != this->array.end() && *it <= val) ++it;
this->array.insert(it, val);
}
}<file_sep>/QuickSort.h
//
// Created by jerryzhou3 on 2/3/2021.
//
#ifndef DATASTRUCTURES_QUICKSORT_H
#define DATASTRUCTURES_QUICKSORT_H
#include<vector>
class QuickSort {
static int partition(std::vector<int>& array, int left, int right);
static void quickSort(std::vector<int>& array, int left, int right);
public:
static void quickSort(std::vector<int>& array);
};
#endif //DATASTRUCTURES_QUICKSORT_H
<file_sep>/test.cpp
#include <iostream>
#include <unordered_map>
#include <stack>
int main() {
std::unordered_map<int, std::stack<int>> stacks;
int cnt = 0;
for (auto m: stacks) ++cnt;
std::cout << cnt << std::endl;
return 0;
}
<file_sep>/BinarySearchTree.h
//
// Created by jerryzhou3 on 1/4/2021.
//
#ifndef DATASTRUCTURES_BINARYSEARCHTREE_H
#define DATASTRUCTURES_BINARYSEARCHTREE_H
#include <cstdlib>
#include <iostream>
#include <queue>
class BinarySearchTree {
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
explicit TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {}
};
TreeNode* root;
public:
BinarySearchTree(): root(nullptr) {};
void insert(int x);
bool contains(int x);
int getMin();
int getMax();
int getHeight();
void remove(int x);
bool isFull();
bool isBalanced();
void printTree();
};
#endif //DATASTRUCTURES_BINARYSEARCHTREE_H
<file_sep>/AVLTree.cpp
//
// Created by jerryzhou3 on 1/4/2021.
//
#include "AVLTree.h"
AVLTree::TreeNode* AVLTree::leftRotate(TreeNode* root) {
TreeNode* temp = root->right;
root->right = root->right->left;
temp->left = root;
return temp;
}
AVLTree::TreeNode* AVLTree::rightRotate(TreeNode* root) {
TreeNode* temp = root->left;
root->left = root->left->right;
temp->right = root;
return temp;
}
AVLTree::TreeNode* AVLTree::leftRightRotate(TreeNode* root) {
TreeNode* leftRoot = leftRotate(root->left);
root->left = leftRoot;
return rightRotate(root);
}
AVLTree::TreeNode* AVLTree::rightLeftRotate(TreeNode* root) {
TreeNode* rightRoot = rightRotate(root->right);
root->right = rightRoot;
return leftRotate(root);
}
int AVLTree::getBalance(TreeNode* root) {
if (!root) return 0;
else {
int leftHeight = 0;
int rightHeight = 0;
if (root->left) leftHeight = root->left->height;
if (root->right) rightHeight = root->right->height;
return rightHeight - leftHeight;
}
}
void AVLTree::balanceTree(int target) {
TreeNode* temp = this->root;
TreeNode* prev = nullptr;
TreeNode* unbalanced = nullptr;
TreeNode* unbalancedPrev = nullptr;
int balance = 0;
while (temp && temp->val != target) {
int cur_balance = getBalance(temp);
if (cur_balance > 1 || cur_balance < -1) {
unbalanced = temp;
unbalancedPrev = prev;
balance = cur_balance;
}
prev = temp;
if (temp->val > target) temp = temp->left;
else temp = temp->right;
}
if (unbalanced) {
std::cout << "balance tree" << std::endl;
TreeNode* balancedRoot;
if (balance > 1) {
int subBalance = getBalance(unbalanced->right);
if (subBalance >= 0) {
balancedRoot = leftRotate(unbalanced);
}
else {
balancedRoot = rightLeftRotate(unbalanced);
}
}
else {
int subBalance = getBalance(unbalanced->left);
if (subBalance <= 0) {
balancedRoot = rightRotate(unbalanced);
}
else {
balancedRoot = leftRightRotate(unbalanced);
}
}
if (!unbalancedPrev) this->root = balancedRoot;
else {
if (balancedRoot->val < unbalancedPrev->val) unbalancedPrev->left = balancedRoot;
else unbalancedPrev->right = balancedRoot;
}
}
}
void AVLTree::updateHeight() {
struct recursion {
static void updateHeight_rec(TreeNode* root) {
if (!root) return;
else {
updateHeight_rec(root->left);
updateHeight_rec(root->right);
int leftHeight = 0;
int rightHeight = 0;
if (root->left) leftHeight = root->left->height;
if (root->right) rightHeight = root->right->height;
root->height = 1 + std::max(leftHeight, rightHeight);
return;
}
}
};
recursion::updateHeight_rec(this->root);
}
void AVLTree::insert(int x) {
TreeNode* temp = this->root;
TreeNode* prev = nullptr;
while (temp) {
prev = temp;
if (temp->val == x) return;
else if (temp->val < x) temp = temp->right;
else temp = temp->left;
}
auto* node = new TreeNode(x);
if (!prev) this->root = node;
else {
if (prev->val > x) prev->left = node;
else prev->right = node;
}
updateHeight();
balanceTree(x);
updateHeight();
}
bool AVLTree::contains(int x) {
TreeNode* temp = this->root;
while (temp) {
if (temp->val == x) return true;
else if (temp->val < x) temp = temp->right;
else temp = temp->left;
}
return false;
}
int AVLTree::getMin() {
if (!this->root) return 0;
TreeNode* temp = this->root;
while (temp->left) {
temp = temp->left;
}
return temp->val;
}
int AVLTree::getMax() {
if (!this->root) return 0;
TreeNode* temp = this->root;
while (temp->right) {
temp = temp->right;
}
return temp->val;
}
int AVLTree::getHeight() {
if (!this->root) return 0;
else return this->root->height;
}
void AVLTree::remove(int x) {
TreeNode* temp = this->root;
TreeNode* prev = nullptr;
while (temp && temp->val != x) {
prev = temp;
if (temp->val < x) temp = temp->right;
else temp = temp->left;
}
if (!temp) return;
if (!prev) {
delete this->root;
this->root = nullptr;
return;
}
if (prev->val < temp->val) {
if (temp->left && temp->right) {
prev->right = temp->left;
temp->left->right = temp->right;
}
else if (temp->left) prev->right = temp->left;
else if (temp->right) prev->right = temp->right;
else prev->right = nullptr;
}
else {
if (temp->left && temp->right) {
prev->left = temp->right;
temp->right->left = temp->left;
}
else if (temp->left) prev->left = temp->left;
else if (temp->right) prev->left = temp->right;
else prev->left = nullptr;
}
delete temp;
updateHeight();
balanceTree(x);
updateHeight();
}
bool AVLTree::isFull() {
struct recursion{
static bool isFull_rec(TreeNode* root) {
if (!root) return true;
if (!root->left == !root->right) return isFull_rec(root->left) && isFull_rec(root->right);
else return false;
}
};
return recursion::isFull_rec(this->root);
}
void AVLTree::printTree() {
if (!this->root) std::cout << "Empty Tree" << std::endl;
std::cout << "Print Tree: " << std::endl;
std::queue<TreeNode*> q;
q.push(this->root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
if (i < size - 1) {
if (!node) std::cout << "null ";
else std::cout << node->val << " ";
}
else {
if (!node) std::cout << "null" << std::endl;
else std::cout << node->val << std::endl;
}
if (node) {
q.push(node->left);
q.push(node->right);
}
}
}
}<file_sep>/AVLTree.h
//
// Created by jerryzhou3 on 1/4/2021.
//
#ifndef DATASTRUCTURES_AVLTREE_H
#define DATASTRUCTURES_AVLTREE_H
#include <cstdlib>
#include <iostream>
#include <queue>
class AVLTree {
struct TreeNode {
int val;
int height;
TreeNode* left;
TreeNode* right;
explicit TreeNode(int x): val(x), height(0), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right): val(x), height(0), left(left), right(right) {}
};
TreeNode* root;
static TreeNode* leftRotate(TreeNode* root);
static TreeNode* rightRotate(TreeNode* root);
static TreeNode* leftRightRotate(TreeNode* root);
static TreeNode* rightLeftRotate(TreeNode* root);
static int getBalance(TreeNode* root);
void balanceTree(int target);
void updateHeight();
public:
void insert(int x);
bool contains(int x);
int getMin();
int getMax();
int getHeight();
void remove(int x);
bool isFull();
void printTree();
};
#endif //DATASTRUCTURES_AVLTREE_H
<file_sep>/QuickSort.cpp
//
// Created by jerryzhou3 on 2/3/2021.
//
#include "QuickSort.h"
void QuickSort::quickSort(std::vector<int> &array) {
int size = array.size();
quickSort(array, 0, size - 1);
}
int QuickSort::partition(std::vector<int> &array, int left, int right) {
int pivot_val = array[right];
int pivot = left - 1;
for (int i = left; i <= right - 1; i++) {
if (array[i] <= pivot_val) {
++pivot;
array[pivot] ^= array[i];
array[i] ^= array[pivot];
array[pivot] ^= array[i];
}
}
array[pivot + 1] ^= array[right];
array[right] ^= array[pivot + 1];
array[pivot + 1] ^= array[right];
return pivot + 1;
}
void QuickSort::quickSort(std::vector<int> &array, int left, int right) {
if (left >= right) return;
int pivot = partition(array, left, right);
quickSort(array, left, pivot - 1);
quickSort(array, pivot + 1, right);
}
|
f5889883259bf909e5c60c4123558cc71765f633
|
[
"Markdown",
"CMake",
"C++"
] | 16 |
C++
|
jerryzhou3/Algorithm_And_Data_Structures
|
a789d638552e326214e45371d25be94a0886ca84
|
922f51bb24cafb9d03ba820628a13250f3c99f71
|
refs/heads/master
|
<repo_name>kyozen-lib/decrypt_password<file_sep>/lib/decrypt_password.bash.inc
## ----------------------------------------------------------
## decrypt_password - basic decryption
## WARNING: changing $PASSWD_SALT in ~/etc/init.conf also changes decryption behavior
## ----------------------------------------------------------
decrypt_password()
{
local encrypted_password="$1"
local retval=$INVALID
retval='ERROR: $PASSWD_SALT undefined'
if [[ "$PASSWD_SALT" != "" ]] && retval=$(echo "$encrypted_password"|$BASE64_BIN -D 2>/dev/null|$OPENSSL_BIN des3 -d -k "$PASSWD_SALT")
echo "$retval"
} ## END: decrypt_password()
<file_sep>/readme.txt
## ----------------------------------------------------------
## decrypt_password - basic decryption
## WARNING: changing $PASSWORD_SALT in ~/etc/init.conf also changes decryption behavior
## ----------------------------------------------------------
|
390da72d409864db331c8805ef01c3a98b092077
|
[
"Text",
"PHP"
] | 2 |
PHP
|
kyozen-lib/decrypt_password
|
41fb77b768d0197be26bde04148e28d72509817f
|
5489215e2578dcf51c9559bfa79d686701054485
|
refs/heads/master
|
<file_sep>/*
* This sketch serves as a 12 volt trigger to switch a NAD-D3020 audio amplifier on and off.
* The on and off state are controlled over a http call. The current status can also be probed.
*
* The sketch is designed to run on a Wemos D1 mini that has pin 15 connected to a NPN transistor.
* Although it is designed for the 12V trigger input, the output voltage can be toggled
* between 0 and 5 volt. This is enough to trigget the amplifier.
*
* Valid HTTP calls are
* http://nad-d3020.local/on
* http://nad-d3020.local/off
* http://nad-d3020.local/status this returns on or off
* http://nad-d3020.local/version
* http://nad-d3020.local/reset
* http://nad-d3020.local/ this returns an identifier
*
* (C) 2017 <NAME>
*
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include "secret.h"
#define PINOUT 14 // this corresponds to D5 on the Wemos D1 mini
// These are defined in secret.h
// const char* ssid = "xxxx";
// const char* password = "<PASSWORD>";
const char* version = __DATE__ " / " __TIME__;
ESP8266WebServer server(80);
void handleRoot() {
Serial.println("/");
server.send(200, "text/plain", "NAD-D3020");
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
long checkpoint = millis();
void setup(void) {
pinMode(PINOUT, OUTPUT);
digitalWrite(PINOUT, LOW);
Serial.begin(115200);
while (!Serial) {
;
}
Serial.print("\n[esp8266_12v_trigger / ");
Serial.print(version);
Serial.println("]");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
int count = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if (count++>10) {
Serial.println("reset");
ESP.reset();
}
else
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("NAD-D3020")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/on", []() {
Serial.println("/on");
digitalWrite(PINOUT, HIGH);
server.send(200, "text/plain", "on");
});
server.on("/off", []() {
Serial.println("/off");
digitalWrite(PINOUT, LOW);
server.send(200, "text/plain", "off");
});
server.on("/status", []() {
Serial.println("/status");
if (digitalRead(PINOUT))
server.send(200, "text/plain", "on");
else
server.send(200, "text/plain", "off");
});
server.on("/version", []() {
Serial.println("/version");
server.send(200, "text/plain", version);
});
server.on("/reset", []() {
Serial.println("/reset");
server.send(200, "text/plain", "reset");
ESP.reset();
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
} // setup
void loop(void) {
// check the connection status every 10 seconds
if ((millis()-checkpoint) > 10000) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("reset");
ESP.reset();
}
else
checkpoint = millis();
}
// process incoming http requests
server.handleClient();
} // loop
|
4a05695d5fbdd612f9a6806a0637b4e32b5a657d
|
[
"C++"
] | 1 |
C++
|
dasomaso/arduino
|
ff790e5ba4c6a1c5d92f05dca963c043221a54a9
|
996d2461e23b1f4ee80dd5efa79b3d57eb425a95
|
refs/heads/master
|
<repo_name>suqun/webapi<file_sep>/demo/src/main/java/com/wises/demo/api/UserController.java
///*
// * Copyright 2016 Wicrenet, Inc. All rights reserved.
// */
//package com.wises.demo.api;
//
//import com.wises.common.component.redis.RedisCache;
//import com.wises.common.model.response.WisesResponseEntity;
//import com.wises.demo.model.User;
//import com.wises.demo.service.UserService;
//import com.wises.demo.service.base.BaseService;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//import tk.mybatis.mapper.entity.Example;
//
///**
// * HomeController
// * Created by larry on 2016/12/27.
// */
//@RestController
//public class UserController implements UserApi{
// private static final Logger logger = LoggerFactory.getLogger(UserController.class);
//
// @Autowired
// UserService userService;
//
// @Autowired
// BaseService baseService;
//
// @Autowired
// RedisCache redisCache;
//
////
//// [POST] http://localhost:8080/users // 新增
//// [GET] http://localhost:8080/users/1 // 查询
//// [PUT] http://localhost:8080/users/1 // 更新
//// [DELETE] http://localhost:8080/users/1 // 删除
//
// /**
// * 添加
// *
// * @param user
// * @return
// */
// public WisesResponseEntity save(@RequestBody User user) {
// return new WisesResponseEntity<>(baseService.insert(user), "200", "ok");
// }
//
// /**
// * 查询
// *
// * @param name
// * @return
// */
// public WisesResponseEntity query(@PathVariable String name) {
// Example example = new Example(User.class);
// example.createCriteria().andLike("name",name);
// return new WisesResponseEntity<>(baseService.selectByExample(example), "0", "ok");
// }
//
// /**
// * 修改
// *
// * @param name
// * @return
// */
// public WisesResponseEntity update(@PathVariable String name, @PathVariable String password) {
// Example example = new Example(User.class);
// example.createCriteria().andLike("name",name);
// User user = new User();
// user.setPassword(<PASSWORD>);
// return new WisesResponseEntity<>(baseService.updateByExample(user, example), "0", "ok");
// }
//}
<file_sep>/business/src/main/java/com/wises/business/goods/service/impl/GoodsEvaluationServiceImpl.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.business.goods.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wises.business.goods.mapper.GoodsEvaluationMapper;
import com.wises.business.goods.model.GoodsEvaluation;
import com.wises.business.goods.service.GoodsEvaluationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
/**
* 商品评价信息服务
* Created by larry.su on 2017/2/2.
*/
@Slf4j
@Service
public class GoodsEvaluationServiceImpl implements GoodsEvaluationService {
@Autowired
GoodsEvaluationMapper goodsEvaluationMapper;
@Override
public PageInfo<GoodsEvaluation> findByPageNumSize(String goodsId) {
Example example = new Example(GoodsEvaluation.class);
example.createCriteria().andEqualTo("goodsId",goodsId);
PageInfo<GoodsEvaluation> page = PageHelper.startPage(1, 10)
.doSelectPageInfo(() -> goodsEvaluationMapper.selectByExample(example));
return page;
}
@Override
public Page<GoodsEvaluation> findByPageNumSize2(String goodsId) {
return null;
}
}
<file_sep>/business/src/test/java/com/wises/business/goods/service/GoodsConsultServiceTest.java
package com.wises.business.goods.service;
import com.wises.business.component.dbunit.DbUnitTestCase;
import com.wises.business.goods.model.Consult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import java.util.List;
/**
* GoodsConsultServiceTest
* Created by larry.su on 2017/1/31.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:dbunit.xml"})
public class GoodsConsultServiceTest extends DbUnitTestCase{
@Autowired
GoodsConsultService goodsConsultService;
@Test
public void getConsultByGoodsId() throws Exception {
List<Consult> list = goodsConsultService.findConsultByGoodsId("g0001");
Assert.isTrue(list.size()==1);
}
}<file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/evaluatons/EvaluationParam.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.gateway.api.goods.evaluatons;
import com.wises.gateway.common.CommonParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import org.hibernate.validator.constraints.NotEmpty;
/**
* GoodsParam
* Created by larry.su on 2017/2/4.
*/
@Data
@ToString
@ApiModel(value = "EvaluationParam", description = "商品评价参数对象")
public class EvaluationParam extends CommonParam{
@ApiModelProperty(value = "商品ID", required = true)
@NotEmpty(message = "不能为空")
private String goodsId;
}<file_sep>/api-server/src/main/java/com/wises/gateway/component/image/config/AuthType.java
package com.wises.gateway.component.image.config;
public enum AuthType {
OP,//运营
MA,//商家
ME //会员
}
<file_sep>/common/src/main/java/com/wises/common/utils/SerializeUtil.java
/*
* Copyright 2015 Wicresoft, Inc. All rights reserved.
*/
package com.wises.common.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Description of SerializeUtil
*
* @author evans.zhangs
* @created on 2015-7-3
*
* @version $Id: SerializeUtil.java 16 2016-03-22 10:26:26Z steven $
*/
public class SerializeUtil {
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
List<Map<String, String>> list=new ArrayList<Map<String, String>>();
Map<String, String> map=new HashMap<String, String>();
map.put("aa", "aaa");
list.add(map);
System.out.println(SerializeUtil.serialize(list).length);
}
}
<file_sep>/business/src/main/java/com/wises/business/goods/model/GoodsEvaluation.java
package com.wises.business.goods.model;
import java.util.Date;
import javax.persistence.*;
@Table(name = "GOODS_EVALUATION")
public class GoodsEvaluation {
/**
* 主键ID
*/
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
/**
* 评价人ID
*/
@Column(name = "MEMBER_ID")
private String memberId;
/**
* 商品表ID
*/
@Column(name = "GOODS_ID")
private String goodsId;
/**
* 订单ID
*/
@Column(name = "ORDER_ID")
private String orderId;
/**
* 订单编号
*/
@Column(name = "ORDER_NO")
private String orderNo;
/**
* 店铺ID
*/
@Column(name = "MERCHANT_ID")
private String merchantId;
/**
* 商品名称
*/
@Column(name = "GOODS_NAME")
private String goodsName;
/**
* 商品价格
*/
@Column(name = "GOODS_PRICE")
private Long goodsPrice;
/**
* 1-5分
*/
@Column(name = "SCORES")
private Short scores;
/**
* 信誉评价内容
*/
@Column(name = "CONTENT")
private String content;
/**
* 0表示不是 1表示是匿名评价
*/
@Column(name = "ANONYMOUS")
private Short anonymous;
/**
* 评价时间
*/
@Column(name = "EVAL_TIME")
private Date evalTime;
/**
* 评价信息的状态 0为正常 1为禁止显示
*/
@Column(name = "STATE")
private Short state;
/**
* 管理员对评价的处理备注
*/
@Column(name = "REMARK")
private String remark;
/**
* 解释内容
*/
@Column(name = "EXPLAINS")
private String explains;
/**
* 晒单图片
*/
@Column(name = "SHOW_IMAGE")
private String showImage;
/**
* 获取主键ID
*
* @return ID - 主键ID
*/
public String getId() {
return id;
}
/**
* 设置主键ID
*
* @param id 主键ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取评价人ID
*
* @return MEMBER_ID - 评价人ID
*/
public String getMemberId() {
return memberId;
}
/**
* 设置评价人ID
*
* @param memberId 评价人ID
*/
public void setMemberId(String memberId) {
this.memberId = memberId;
}
/**
* 获取商品表ID
*
* @return GOODS_ID - 商品表ID
*/
public String getGoodsId() {
return goodsId;
}
/**
* 设置商品表ID
*
* @param goodsId 商品表ID
*/
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
/**
* 获取订单ID
*
* @return ORDER_ID - 订单ID
*/
public String getOrderId() {
return orderId;
}
/**
* 设置订单ID
*
* @param orderId 订单ID
*/
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/**
* 获取订单编号
*
* @return ORDER_NO - 订单编号
*/
public String getOrderNo() {
return orderNo;
}
/**
* 设置订单编号
*
* @param orderNo 订单编号
*/
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
/**
* 获取店铺ID
*
* @return MERCHANT_ID - 店铺ID
*/
public String getMerchantId() {
return merchantId;
}
/**
* 设置店铺ID
*
* @param merchantId 店铺ID
*/
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
/**
* 获取商品名称
*
* @return GOODS_NAME - 商品名称
*/
public String getGoodsName() {
return goodsName;
}
/**
* 设置商品名称
*
* @param goodsName 商品名称
*/
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
/**
* 获取商品价格
*
* @return GOODS_PRICE - 商品价格
*/
public Long getGoodsPrice() {
return goodsPrice;
}
/**
* 设置商品价格
*
* @param goodsPrice 商品价格
*/
public void setGoodsPrice(Long goodsPrice) {
this.goodsPrice = goodsPrice;
}
/**
* 获取1-5分
*
* @return SCORES - 1-5分
*/
public Short getScores() {
return scores;
}
/**
* 设置1-5分
*
* @param scores 1-5分
*/
public void setScores(Short scores) {
this.scores = scores;
}
/**
* 获取信誉评价内容
*
* @return CONTENT - 信誉评价内容
*/
public String getContent() {
return content;
}
/**
* 设置信誉评价内容
*
* @param content 信誉评价内容
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取0表示不是 1表示是匿名评价
*
* @return ANONYMOUS - 0表示不是 1表示是匿名评价
*/
public Short getAnonymous() {
return anonymous;
}
/**
* 设置0表示不是 1表示是匿名评价
*
* @param anonymous 0表示不是 1表示是匿名评价
*/
public void setAnonymous(Short anonymous) {
this.anonymous = anonymous;
}
/**
* 获取评价时间
*
* @return EVAL_TIME - 评价时间
*/
public Date getEvalTime() {
return evalTime;
}
/**
* 设置评价时间
*
* @param evalTime 评价时间
*/
public void setEvalTime(Date evalTime) {
this.evalTime = evalTime;
}
/**
* 获取评价信息的状态 0为正常 1为禁止显示
*
* @return STATE - 评价信息的状态 0为正常 1为禁止显示
*/
public Short getState() {
return state;
}
/**
* 设置评价信息的状态 0为正常 1为禁止显示
*
* @param state 评价信息的状态 0为正常 1为禁止显示
*/
public void setState(Short state) {
this.state = state;
}
/**
* 获取管理员对评价的处理备注
*
* @return REMARK - 管理员对评价的处理备注
*/
public String getRemark() {
return remark;
}
/**
* 设置管理员对评价的处理备注
*
* @param remark 管理员对评价的处理备注
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 获取解释内容
*
* @return EXPLAIN - 解释内容
*/
public String getExplains() {
return explains;
}
/**
* 设置解释内容
*
* @param explains 解释内容
*/
public void setExplains(String explains) {
this.explains = explains;
}
/**
* 获取晒单图片
*
* @return SHOW_IMAGE - 晒单图片
*/
public String getShowImage() {
return showImage;
}
/**
* 设置晒单图片
*
* @param showImage 晒单图片
*/
public void setShowImage(String showImage) {
this.showImage = showImage;
}
}<file_sep>/demo/src/main/java/com/wises/demo/service/UserService.java
/*
* Copyright 2016 Wicrenet, Inc. All rights reserved.
*/
package com.wises.demo.service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.wises.demo.model.User;
import java.util.List;
/**
* UserService
* Created by larry on 2016/12/28.
*/
public interface UserService {
/**
* 自定义方法
* @return
*/
List<User> findUser();
/**
* 分页,返回分页详细信息
* @return
*/
PageInfo<User> findUserByPageNumSize();
/**
* 分页,返回分页详细信息
* @return
*/
Page<User> findUserByPageNumSize2();
}
<file_sep>/api-server/src/main/java/com/wises/gateway/common/CommonParam.java
package com.wises.gateway.common;
import com.alibaba.fastjson.JSONObject;
import com.wises.gateway.exception.ApiException;
import com.wises.gateway.exception.ApiIllegalArgumentException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import javax.validation.constraints.Pattern;
/**
* 接口通用参数
*/
@Slf4j
@Data
@ToString
@ApiModel(value = "CommonParam", description = "公共参数")
public class CommonParam {
@ApiModelProperty(value = "客户端", required = true)
@Pattern(regexp = "^(h5)|(ios)|(android)$", message = "h5,ios,android三选一必填")
private String client;
@ApiModelProperty(value = "版本号", required = true)
@NotEmpty(message = "version不能为空")
private String version;
@ApiModelProperty(value = "token")
private String token;
@ApiModelProperty(value = "页数")
private int pageNum = 0;
@ApiModelProperty(value = "每页显示数")
private int pageSize = 10;
/**
* 组装校验错误信息
* @param result
* @throws ApiException
*/
public void validResult(BindingResult result) throws ApiException {
if (result.hasErrors()) {
log.debug("参数格式错误");
JSONObject jsonObject = new JSONObject();
for (FieldError fieldError : result.getFieldErrors()) {
jsonObject.put(fieldError.getField(), fieldError.getDefaultMessage());
}
log.debug(jsonObject.toJSONString());
throw new ApiIllegalArgumentException(1, jsonObject.toJSONString());
}
}
}
<file_sep>/common/src/main/java/com/wises/common/component/redis/RedisCacheTransfer.java
/*
* Copyright 2016 Wicrenet, Inc. All rights reserved.
*/
package com.wises.common.component.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
/**
* 静态注入中间类
* Created by larry on 2016/12/29.
*/
public class RedisCacheTransfer {
@Autowired
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
MybatisRedisCache.setJedisConnectionFactory(jedisConnectionFactory);
// SessionConfig.setJedisConnectionFactory(jedisConnectionFactory);
}
}
<file_sep>/api-server/src/main/java/com/wises/gateway/common/constants/SystemSettingConstants.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.gateway.common.constants;
/**
* 系统配置参数名称枚举
* Created by larry.su on 2017/1/22.
*/
public enum SystemSettingConstants {
HOT_WORDS ("hot_search","热词搜索");
SystemSettingConstants(String code, String desc) {
this.code = code;
this.desc = desc;
}
private String code;
private String desc;
public String code() {
return code;
}
public String desc() {
return desc;
}
}
<file_sep>/business/src/main/java/com/wises/business/goods/service/impl/GoodsInfoServiceImpl.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.business.goods.service.impl;
import com.wises.business.goods.service.GoodsInfoService;
/**
* GoodsInfoServiceImpl
* 商品信息服务
* Created by larry.su on 2017/1/17.
*/
public class GoodsInfoServiceImpl implements GoodsInfoService {
}
<file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/category/GoodsCategoriesApi.java
package com.wises.gateway.api.goods.category;
import com.wises.gateway.common.CommonParam;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
@Api(value = "goodsCategories", description = "the goodsCategories API")
public interface GoodsCategoriesApi {
@ApiOperation(value = "商品分类查询", notes = "查询商品分类", response = GoodsCategoryResult.class, tags = {"商品",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = GoodsCategoryResult.class)})
@RequestMapping(value = "/goodsCategories",
produces = {"application/json"},
method = RequestMethod.GET)
GoodsCategoryResult goodsCategoriesGet(@Valid @ModelAttribute CommonParam commonParam, BindingResult result);
}
<file_sep>/api-server/src/main/java/com/wises/gateway/component/image/web/GetAuthController.java
package com.wises.gateway.component.image.web;//package com.wicresoft.imageclient.web;
//
//import java.io.IOException;
//import java.util.Map;
//
//import javax.servlet.http.HttpServletResponse;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.ResponseBody;
//
//import com.wicresoft.imageclient.config.AuthType;
//import com.wicresoft.imageclient.utils.GetAuthUtils;
//
//@Controller
//@RequestMapping("/auth")
//public class GetAuthController {
//
// @Autowired
// private GetAuthUtils getAuthUtils;
//
// @RequestMapping(value = "/getAuth.json", method = { RequestMethod.GET, RequestMethod.POST })
// @ResponseBody
// public Object getAuthQiNiu(HttpServletResponse response)
// throws IOException {
// //模块名称 用户id
// Map<String, Object> auth = getAuthUtils.getAuth(AuthType.OP, "123456789");
// return auth;
// }
//
//}
<file_sep>/business/src/test/java/com/wises/business/templates/service/UserServiceTest.java
//package com.wises.business.templates.service;
//
//import com.github.pagehelper.Page;
//import com.github.pagehelper.PageInfo;
//import com.wises.business.component.dbunit.DbUnitTestCase;
//import com.wises.business.templates.model.User;
//import com.wises.common.component.redis.RedisCache;
//import org.junit.Assert;
//import org.junit.Before;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.test.context.ContextConfiguration;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//import tk.mybatis.mapper.entity.Example;
//
//import java.util.List;
//
///**
// * UserServiceTest
// * Created by larry on 2016/12/30.
// */
//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath:dbunit.xml"})
//public class UserServiceTest extends DbUnitTestCase {
//
// @Autowired
// UserService userService;
//
// @Autowired
// RedisCache redisCache;
//
// @Before
// public void setUp() throws Exception {
// // 必须调用父类setUp(),此处会初始化数据,数据存放于与此类同名的Xml中
// // 每次case开始前会将Xml中的数据刷新到数据库中
// super.setUp();
// }
//
// @Test
// public void findUser() throws Exception {
// List<User> userList = userService.findUser();
// Assert.assertTrue(userList.size()==1);
// }
//
// @Test
// public void findUserByPageNumSize() throws Exception {
// PageInfo<User> page = userService.findUserByPageNumSize();
// System.out.println(page);
// }
//
// @Test
// public void findUserByPageNumSize2() throws Exception {
// Page<User> page = userService.findUserByPageNumSize2();
// System.out.println(page);
// }
//
//}<file_sep>/business/src/main/java/com/wises/business/system/service/impl/SystemSettingServiceImpl.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.business.system.service.impl;
import com.wises.business.system.mapper.SystemSettingMapper;
import com.wises.business.system.model.SystemSetting;
import com.wises.business.system.service.SystemSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* SystemSettingServiceImpl
* Created by larry.su on 2017/1/22.
*/
@Service
@Transactional
public class SystemSettingServiceImpl implements SystemSettingService{
@Autowired
private SystemSettingMapper systemSettingMapper;
@Override
public String getSettingValueByName(String name) {
Example example = new Example(SystemSetting.class);
example.createCriteria().andEqualTo("paramName",name);
List<SystemSetting> list = systemSettingMapper.selectByExample(example);
if (null == list || list.size() ==0) {
return "";
}
return list.get(0).getParamValue();
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wises</groupId>
<artifactId>wises-parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<!--<module>demo</module>-->
<module>common</module>
<module>business</module>
<module>api-server</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 依赖版本 -->
<springframework.version>4.3.4.RELEASE</springframework.version>
<mysql.version>5.1.39</mysql.version>
<mybatis.version>3.4.1</mybatis.version>
<mybatis.spring.version>1.3.0</mybatis.spring.version>
<mapper.version>3.3.9</mapper.version>
<druid.version>1.0.27</druid.version>
<spring.security.version>4.2.1.RELEASE</spring.security.version>
<elasticsearch.version>5.1.1</elasticsearch.version>
<gson.version>2.8.0</gson.version>
<lombok.version>1.16.12</lombok.version>
</properties>
<dependencyManagement>
<dependencies>
<!--test compile -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
</dependency>
<!--compile-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${mapper.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.0.Final</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.8</version>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<!-- spring-redis实现 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.5.RELEASE</version>
</dependency>
<!-- redis客户端jar -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.23</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<!--权限控制-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!--image-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.2.3</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<!--elasticsearch-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.4.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
<profile>
<id>dev</id>
<properties>
<profiles.activation>dev</profiles.activation>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.activation>test</profiles.activation>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profiles.activation>prod</profiles.activation>
</properties>
</profile>
</profiles>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<directory>target</directory>
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 资源根目录排除各环境的配置,防止在生成目录中多余其它目录 -->
<excludes>
<exclude>resource-test/*</exclude>
<exclude>resource-prod/*</exclude>
<exclude>resource-dev/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/resource-${profiles.activation}</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/java/</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.xls</include>
</includes>
</testResource>
<testResource>
<directory>src/test/resource/</directory>
<includes>
<include>**/*.xml</include>
</includes>
</testResource>
</testResources>
<pluginManagement>
<plugins>
<!--编译的时候使用JDK8和UTF8编码-->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<configuration>
<aggregate>true</aggregate>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<phase>deploy</phase>
<goals>
<goal>javadoc</goal>
</goals>
<configuration> <!-- add this to disable checking -->
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.19</version>
</dependency>
</dependencies>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project><file_sep>/api-server/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>wises-parent</artifactId>
<groupId>com.wises</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>api-server</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.wises</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.wises</groupId>
<artifactId>business</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--compile-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
</dependency>
</dependencies>
</project><file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/category/GoodsCategoryResult.java
package com.wises.gateway.api.goods.category;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.wises.gateway.model.goods.GoodsCategoryModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* GoodsCategoryResult
*/
public class GoodsCategoryResult {
@JsonProperty("data")
private List<GoodsCategoryModel> data = new ArrayList<GoodsCategoryModel>();
@JsonProperty("code")
private Integer code = 0;
@JsonProperty("message")
private String message = null;
public GoodsCategoryResult data(List<GoodsCategoryModel> data) {
this.data = data;
return this;
}
public GoodsCategoryResult addDataItem(GoodsCategoryModel dataItem) {
this.data.add(dataItem);
return this;
}
/**
* 返回的具体数据
*
* @return data
**/
@ApiModelProperty(value = "返回的具体数据")
public List<GoodsCategoryModel> getData() {
return data;
}
public void setData(List<GoodsCategoryModel> data) {
this.data = data;
}
public GoodsCategoryResult code(Integer code) {
this.code = code;
return this;
}
/**
* 返回码
*
* @return code
**/
@ApiModelProperty(value = "返回码",required = true)
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public GoodsCategoryResult message(String message) {
this.message = message;
return this;
}
/**
* 返回信息
*
* @return message
**/
@ApiModelProperty(value = "返回信息")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GoodsCategoryResult goodsCategoryResult = (GoodsCategoryResult) o;
return Objects.equals(this.data, goodsCategoryResult.data) &&
Objects.equals(this.code, goodsCategoryResult.code) &&
Objects.equals(this.message, goodsCategoryResult.message);
}
@Override
public int hashCode() {
return Objects.hash(data, code, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GoodsCategoryResult {\n");
sb.append(" data: ").append(toIndentedString(data)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep>/business/README.md
## 框架介绍
### 配置文件
项目包含的所有配置文件都在`src/main/resource`下。
- 使用maven作为项目管理工具,在parent模块中定义了多个profile,目前定义的有**dev**,**test**,**prod**,**默认profile为dev**。开发,测试,生产各环境使用的不同配置的properties分别放在对应的
`resource-${profiles.activation}`里。
- 更改profile
+ 通过maven命令
```
mvn -Ptest clean install //更改profile为test
```
+ intellij idea的maven框里直接勾选
### SpringMVC
- web.xml配置DispatcherServlet
- mvc配置文件:spring-mvc-config.xml
### 数据库连接池druid
数据库连接池使用阿里的druid,dataSource的配置在spring-druid.xml文件中。web.xml中配置的数据库连接池的web监控页面功能。
监控页面地址:http://localhost:8080/druid/index.html
### Mybatis
数据库持久层框架用的mybatis,通过mvn插件可以自动生成model,mapper等。
#### mybatis-generator-maven-plugin的配置及使用
generator生成代码的配置文件`db/generator/generatorConfig.xml`。修改tablename,即可生成对应表的代码,可以添加多个table。
```xml
<table tableName="user">
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
```
默认生成代码的路径配置在pom文件的properties属性里。
```xml
<properties>
<!-- MyBatis Generator -->
<targetJavaProject>${basedir}/src/main/java</targetJavaProject>
<targetMapperPackage>com.wises.business.templates.mapper</targetMapperPackage>
<targetModelPackage>com.wises.model</targetModelPackage>
<targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
<targetXMLPackage>mybatis_mapper</targetXMLPackage>
</properties>
```
使用起来比较简单,双击下面的就可以。

maven控制台输出以下内容:
```
[INFO] Generating Example class for table user
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Saving file UserMapper.xml
[INFO] Saving file UserExample.java
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.789 s
[INFO] Finished at: 2017-01-03T22:04:17+08:00
[INFO] Final Memory: 13M/309M
[INFO] ------------------------------------------------------------------------
```
#### Mapper
通过自动生成的Mapper代码里包含了,数据库表操作的增删改查等基本操作,例如:
```java
@Component
public interface UserMapper {
int countByExample(UserExample example);//根据example条件count
int deleteByExample(UserExample example);//根据example条件删除,物理删除
int deleteByPrimaryKey(Integer id);//根据主键删除
int insert(User record);
int insertSelective(User record);
List<User> selectByExample(UserExample example);
User selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
int updateByExample(@Param("record") User record, @Param("example") UserExample example);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
```
每个方法在UserMapper.xml中都有对应的sql,具体的可以自行查看下使用方法。
在UserMapper中添加方法,在UserMapper.xml中添加相同方法名的sql。
**注意:UserMapper类一定要添加@Component注解**
### 数据库二级缓存
使用redis作为数据库的二级缓存,通过代码添加修改数据都可以自动更新缓存内容。
#### RedisCache类
该类提供redis操作的基本方法
#### MybatisRedisCache类
该类通过实现org.apache.ibatis.cache.Cache接口,以便使用redis作为mysql的二级缓存。
#### 配置
mybatis-config.xml
```xml
<configuration>
<settings>
<!--开启缓存(二级缓存)-->
<setting name="cacheEnabled" value="true" />
<!--全局启用或禁用延迟加载。当禁用时, 所有关联对象都会即时加载。-->
<setting name="lazyLoadingEnabled" value="true" />
<!--开启按需加载-->
<setting name="aggressiveLazyLoading" value="false" />
<!--设置超时时间-->
<setting name="defaultStatementTimeout" value="100" />
<!--Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn-->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
```
相应表的xml中添加cache,例如:UserMapper.xml中
```xml
<mapper namespace="com.wises.business.templates.mapper.UserMapper">
<cache type="com.wises.common.component.redis.MybatisRedisCache" />
</mapper>
```
model也要实现序列化接口
例如User.java类
```java
public class User implements Serializable{}
```
### 数据库集成测试dbunit
数据库集成测试框架仍然使用的dbunit
#### 配置
配置文件:`src/test/resource/dbunit.xml`,该配置文件其实和spring-config.xml内容一致,只是将具体的参数写死了。同时添加了bean: dbUnitSetting。开发的时候请自行修改参数内容
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<!-- 读取配置文件 -->
<context:property-placeholder
location="classpath:**/*.properties"/>
<!-- 扫描注解,除去web层注解,web层注解在mvc配置中扫描 -->
<context:component-scan
base-package="com.wises.business.component,com.wises.business.templates.mapper,com.wises.business.templates.service">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.RestController"/>
</context:component-scan>
<!-- druid连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/wise_s_demo"/>
<property name="username" value="root"/>
<property name="password" value="<PASSWORD>"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="5"/>
<property name="minIdle" value="5"/>
<property name="maxActive" value="20"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="validationQuery" value="SELECT 1"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize"
value="20"/>
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat,wall,logFilter"/>
</bean>
<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
<property name="statementExecutableSqlLogEnable" value="false" />
</bean>
<!-- mybatis -->
<import resource="spring-mybatis.xml"/>
<!-- redis -->
<!-- 连接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大连接数 -->
<property name="maxTotal" value="100"/>
<!-- 最大空闲连接数 -->
<property name="maxIdle" value="10"/>
<!-- 每次释放连接的最大数目 -->
<property name="numTestsPerEvictionRun" value="1024"/>
<!-- 释放连接的扫描间隔(毫秒) -->
<property name="timeBetweenEvictionRunsMillis" value="30000"/>
<!-- 连接最小空闲时间 -->
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
<property name="softMinEvictableIdleTimeMillis" value="10000"/>
<!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
<property name="maxWaitMillis" value="50000"/>
<!-- 在获取连接的时候检查有效性, 默认false -->
<property name="testOnBorrow" value="true"/>
<!-- 在空闲时检查有效性, 默认false -->
<property name="testWhileIdle" value="true"/>
<!-- 在进行returnObject对返回的connection进行validateObject校验 -->
<property name="testOnReturn" value="true"/>
<!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
<property name="blockWhenExhausted" value="false"/>
</bean>
<!-- Spring-redis连接池管理工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="127.0.0.1" p:port="6379" p:password="" p:pool-config-ref="jedisPoolConfig"/>
<bean id="dbUnitSetting" class="com.wises.business.component.dbunit.DbUnitSetting">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/wise_s_demo" />
<property name="user" value="root" />
<property name="password" value="<PASSWORD>" />
<property name="dataTypeFactory" value="org.dbunit.ext.mysql.MySqlDataTypeFactory" />
<property name="exportFolder" value="/Users/larry/work/dbunit/" />
<property name="schema" value="wise_s_demo" />
</bean>
<!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 -->
<!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
```
dbunit的配置文件在测试类中需要通过@ContextConfiguration引用
#### DbUnitTool
将数据表中的数据导出到xml中
```java
public static void main(String[] args) throws SQLException {
DbUnitSetting dbUnitSetting = new DbUnitSetting();
dbUnitSetting.setDriverClass("com.mysql.jdbc.Driver");
dbUnitSetting.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/wise_s_demo?useUnicode=yes&characterEncoding=UTF-8");
dbUnitSetting.setUser("root");
dbUnitSetting.setPassword("<PASSWORD>");
dbUnitSetting.setExportFolder("/Users/larry/work/dbunit/");//导出xml地址
args = new String[]{"user"};//导出数据的表
if (args != null && args.length > 0) {
List<String> tablesList = new ArrayList<String>();
for (String table : args) {
tablesList.add(table);
}
new DbUnitTool(dbUnitSetting).exportTables(tablesList);
}
}
```
生成的xml为
```xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<user id="1" name="larrys" password="<PASSWORD>"/>
<user id="2" name="test_user" password="<PASSWORD>"/>
</dataset>
```
#### 单元测试
以UserService的findUserByExample方法为例:
- UserServiceTest.java 测试类
- UserServiceTest.xml dataset xml中的内容,xml名称必须和测试类名称一致
```java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:dbunit.xml"})
public class UserServiceTest extends DbUnitTestCase {//继承DbUnitTestCase
@Autowired
UserService userService;
@Before
public void setUp() throws Exception {
// 必须调用父类setUp(),此处会初始化数据,数据存放于与此类同名的Xml中
// 每次case开始前会将Xml中的数据刷新到数据库中
super.setUp();
}
@Test
public void findUserByExample() throws Exception {
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
criteria.andNameLike("larrys");
List<User> userList = userService.findUserByExample(example);
Assert.assertTrue(userList.size()==1);
}
}
```
### 日志logback
#### 配置
日志框架使用的logback。配置文件logback.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 应用名称 -->
<property name="APP_NAME" value="logtest" />
<!--日志文件的保存路径,首先查找系统属性-Dlog.dir,如果存在就使用其;否则,在当前目录下创建名为logs目录做日志存放的目录 -->
<!--<property name="LOG_HOME" value="${log.dir:-logs}/${APP_NAME}" />-->
<property name="LOG_HOME" value="/Users/larry/work/logs/${APP_NAME}" />
<!-- 日志输出格式 -->
<property name="ENCODER_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n" />
<contextName>${APP_NAME}</contextName>
<!-- 控制台日志:输出全部日志到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>${ENCODER_PATTERN}</Pattern>
</encoder>
</appender>
<!-- 文件日志:输出全部日志到文件 -->
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/output.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${ENCODER_PATTERN}</pattern>
</encoder>
</appender>
<!-- 错误日志:用于将错误日志输出到独立文件 -->
<appender name="ERROR_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${ENCODER_PATTERN}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
</appender>
<!-- 独立输出的同步日志 -->
<appender name="SYNC_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/sync.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${ENCODER_PATTERN}</pattern>
</encoder>
</appender>
<logger name="log.sync" level="DEBUG" addtivity="true">
<appender-ref ref="SYNC_FILE" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</configuration>
```
#### 使用方式
```java
private static final Logger logger = LoggerFactory.getLogger(****.class);
```
### RESTFul接口
[RESTful 架构风格概述](http://blog.igevin.info/posts/restful-architecture-in-general/)
提供给H5,或者APP的接口使用http协议,格式为json。希望使用RESTful风格。
REST概念分离了API结构和逻辑资源,通过Http方法GET, DELETE, POST 和 PUT等操作资源。
```java
[POST] http://localhost:8080/users // 新增
[GET] http://localhost:8080/users/1 // 查询
[PATCH] http://localhost:8080/users/1 // 更新
[PUT] http://localhost:8080/users/1 // 覆盖,全部更新
[DELETE] http://localhost:8080/users/1 // 删除
```
[RESTFul良好设计最佳实践](http://www.jdon.com/soa/10-best-practices-for-better-restful-api.html)
### 其他
#### Spring Security
暂未完成
#### RESTFul API接口文档,服务端代码,客户端代码自动生成,API认证
swagger,OAuth2.0
<file_sep>/business/src/main/java/com/wises/business/website/service/FloorService.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.business.website.service;
import com.wises.business.website.model.JblFloor;
import java.util.List;
/**
* FloorService
* 网站首页楼层服务接口
* Created by larry.su on 2017/1/17.
*/
public interface FloorService{
/**
* 查询楼层详细信息
* @return
*/
List<JblFloor> getFloorDetailData();
}
<file_sep>/business/src/test/java/com/wises/business/system/service/SystemSettingServiceTest.java
package com.wises.business.system.service;
import com.wises.business.component.dbunit.DbUnitTestCase;
import com.wises.business.website.service.FloorService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import static org.junit.Assert.*;
/**
* SystemSettingServiceTest
* Created by larry.su on 2017/1/22.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:dbunit.xml"})
public class SystemSettingServiceTest extends DbUnitTestCase {
@Autowired
private SystemSettingService systemSettingService;
@Before
public void setUp() throws Exception {
// 必须调用父类setUp(),此处会初始化数据,数据存放于与此类同名的Xml中
// 每次case开始前会将Xml中的数据刷新到数据库中
super.setUp();
}
@Test
public void getSettingValueByName() throws Exception {
String hotwords = systemSettingService.getSettingValueByName("hot_search");
System.out.println(hotwords);
Assert.isTrue(hotwords!=null);
}
}<file_sep>/business/src/main/java/com/wises/business/promotion/model/PromoDiscount.java
package com.wises.business.promotion.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
@Table(name = "PROMO_DISCOUNT")
public class PromoDiscount implements Serializable {
/**
* 主键ID
*/
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
/**
* 商家名称
*/
@Column(name = "MERCHANT_ID")
private String merchantId;
/**
* 促销套餐认购ID
*/
@Column(name = "SUBSCRIPTION_ID")
private String subscriptionId;
/**
* 活动名称
*/
@Column(name = "NAME")
private String name;
/**
* 活动标题
*/
@Column(name = "TITLE")
private String title;
/**
* 活动说明
*/
@Column(name = "DESCRIPTION")
private String description;
/**
* 活动开始时间
*/
@Column(name = "START_TIME")
private Date startTime;
/**
* 活动结束时间
*/
@Column(name = "END_TIME")
private Date endTime;
/**
* 购买上限,0为不限制
*/
@Column(name = "LIMITATION")
private Short limitation;
/**
* 状态,0默认,1-正常 2 已结束 3-管理员已关闭
*/
@Column(name = "STATE")
private Short state;
/**
* 获取主键ID
*
* @return ID - 主键ID
*/
public String getId() {
return id;
}
/**
* 设置主键ID
*
* @param id 主键ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取商家名称
*
* @return MERCHANT_ID - 商家名称
*/
public String getMerchantId() {
return merchantId;
}
/**
* 设置商家名称
*
* @param merchantId 商家名称
*/
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
/**
* 获取促销套餐认购ID
*
* @return SUBSCRIPTION_ID - 促销套餐认购ID
*/
public String getSubscriptionId() {
return subscriptionId;
}
/**
* 设置促销套餐认购ID
*
* @param subscriptionId 促销套餐认购ID
*/
public void setSubscriptionId(String subscriptionId) {
this.subscriptionId = subscriptionId;
}
/**
* 获取活动名称
*
* @return NAME - 活动名称
*/
public String getName() {
return name;
}
/**
* 设置活动名称
*
* @param name 活动名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取活动标题
*
* @return TITLE - 活动标题
*/
public String getTitle() {
return title;
}
/**
* 设置活动标题
*
* @param title 活动标题
*/
public void setTitle(String title) {
this.title = title;
}
/**
* 获取活动说明
*
* @return DESCRIPTION - 活动说明
*/
public String getDescription() {
return description;
}
/**
* 设置活动说明
*
* @param description 活动说明
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 获取活动开始时间
*
* @return START_TIME - 活动开始时间
*/
public Date getStartTime() {
return startTime;
}
/**
* 设置活动开始时间
*
* @param startTime 活动开始时间
*/
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
/**
* 获取活动结束时间
*
* @return END_TIME - 活动结束时间
*/
public Date getEndTime() {
return endTime;
}
/**
* 设置活动结束时间
*
* @param endTime 活动结束时间
*/
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
/**
* 获取购买上限,0为不限制
*
* @return LIMITATION - 购买上限,0为不限制
*/
public Short getLimitation() {
return limitation;
}
/**
* 设置购买上限,0为不限制
*
* @param limitation 购买上限,0为不限制
*/
public void setLimitation(Short limitation) {
this.limitation = limitation;
}
/**
* 获取状态,0默认,1-正常 2 已结束 3-管理员已关闭
*
* @return STATE - 状态,0默认,1-正常 2 已结束 3-管理员已关闭
*/
public Short getState() {
return state;
}
/**
* 设置状态,0默认,1-正常 2 已结束 3-管理员已关闭
*
* @param state 状态,0默认,1-正常 2 已结束 3-管理员已关闭
*/
public void setState(Short state) {
this.state = state;
}
}<file_sep>/business/src/test/java/com/wises/business/goods/service/GoodsEvaluationServiceTest.java
package com.wises.business.goods.service;
import com.github.pagehelper.PageInfo;
import com.wises.business.component.dbunit.DbUnitTestCase;
import com.wises.business.goods.model.GoodsEvaluation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
/**
* GoodsEvaluationServiceTest
* Created by larry.su on 2017/2/2.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:dbunit.xml"})
public class GoodsEvaluationServiceTest extends DbUnitTestCase{
@Autowired
GoodsEvaluationService goodsEvaluationService;
@Test
public void findByPageNumSize() throws Exception {
PageInfo<GoodsEvaluation> list = goodsEvaluationService.findByPageNumSize("1");
Assert.isTrue(list.getList().size() == 1 );
}
@Test
public void findByPageNumSize2() throws Exception {
}
}<file_sep>/api-server/src/main/java/com/wises/gateway/model/goods/GoodsInfo.java
package com.wises.gateway.model.goods;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
/**
* 商品信息
*/
public class GoodsInfo {
@JsonProperty("name")
private String name = null;
@JsonProperty("price")
private Long price = null;
@JsonProperty("imageUrl")
private String imageUrl = null;
public GoodsInfo imageUrl(String imageUrl) {
this.imageUrl = imageUrl;
return this;
}
/**
* 图片URL,如第三方图片URL
*
* @return imageUrl
**/
@ApiModelProperty(value = "图片URL,如第三方图片URL")
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public GoodsInfo name(String name) {
this.name = name;
return this;
}
/**
* 商品名称
*
* @return name
**/
@ApiModelProperty(value = "商品名称")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GoodsInfo price(Long price) {
this.price = price;
return this;
}
/**
* 售价,单位分
*
* @return price
**/
@ApiModelProperty(value = "售价,单位分")
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GoodsInfo goodsInfo = (GoodsInfo) o;
return Objects.equals(this.name, goodsInfo.name) &&
Objects.equals(this.price, goodsInfo.price);
}
@Override
public int hashCode() {
return Objects.hash(name, price);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GoodsInfo {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" price: ").append(toIndentedString(price)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep>/common/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>wises-parent</artifactId>
<groupId>com.wises</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<!-- MyBatis Generator -->
<targetJavaProject>${basedir}/src/main/java</targetJavaProject>
<targetMapperPackage>com.wises.gateway.mapper</targetMapperPackage>
<targetModelPackage>com.wises.gateway.model</targetModelPackage>
<targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
<targetXMLPackage>mybatis_mapper</targetXMLPackage>
</properties>
<dependencies>
<!--compile-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!--image-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!--search-->
<!--<dependency>-->
<!--<groupId>io.searchbox</groupId>-->
<!--<artifactId>jest</artifactId>-->
<!--<version>0.1.6</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.elasticsearch</groupId>-->
<!--<artifactId>elasticsearch</artifactId>-->
<!--<version>1.6.0</version>-->
<!--</dependency>-->
</dependencies>
</project><file_sep>/api-server/src/main/java/com/wises/gateway/component/image/config/ImageAuthConfig.java
/*
* Copyright 2015 Wicresoft, Inc. All rights reserved.
*/
package com.wises.gateway.component.image.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Description of ImageConfig
*
* @author dalongn
*/
@Component
public class ImageAuthConfig {
@Value("${wises.imageConfig.accessKey}")
private String accessKey;
@Value("${wises.imageConfig.secretKey}")
private String secretKey;
@Value("${wises.imageConfig.bucketName}")
private String bucketName;
@Value("${wises.imageConfig.host}")
private String host;
@Value("${wises.imageConfig.domain}")
private String domain;
@Value("${wises.imageConfig.imageType}")
private String imageType;// jpg,png,jpeg,gif
@Value("${wises.imageConfig.maxSize}")
private Integer maxSize;// kb 2048
@Value("${wises.imageConfig.fileNameLength}")
private Integer fileNameLength;// character 100
@Value("${wises.imageConfig.expire}")
private Integer expire;// seconds 3600
public Integer getMaxSize() {
return maxSize;
}
public void setMaxSize(Integer maxSize) {
this.maxSize = maxSize;
}
public String getImageType() {
return imageType;
}
public void setImageType(String imageType) {
this.imageType = imageType;
}
public Integer getFileNameLength() {
return fileNameLength;
}
public void setFileNameLength(Integer fileNameLength) {
this.fileNameLength = fileNameLength;
}
public Integer getExpire() {
return expire;
}
public void setExpire(Integer expire) {
this.expire = expire;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
<file_sep>/api-server/src/main/java/com/wises/gateway/model/goods/ConsultModel.java
package com.wises.gateway.model.goods;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
/**
* 商品咨询
*/
public class ConsultModel {
@JsonProperty("memberName")
private String memberName = null;
@JsonProperty("content")
private String content = null;
@JsonProperty("reply")
private String reply = null;
@JsonProperty("consultTime")
private String consultTime = null;
@JsonProperty("replyTime")
private String replyTime = null;
@JsonProperty("anonymous")
private Short anonymous = null;
public ConsultModel memberName(String memberName) {
this.memberName = memberName;
return this;
}
/**
* 咨询会员名称
*
* @return memberName
**/
@ApiModelProperty(value = "咨询会员名称")
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public ConsultModel content(String content) {
this.content = content;
return this;
}
/**
* 咨询内容
*
* @return content
**/
@ApiModelProperty(value = "咨询内容")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public ConsultModel reply(String reply) {
this.reply = reply;
return this;
}
/**
* 回复内容
*
* @return reply
**/
@ApiModelProperty(value = "回复内容")
public String getReply() {
return reply;
}
public void setReply(String reply) {
this.reply = reply;
}
public ConsultModel consultTime(String consultTime) {
this.consultTime = consultTime;
return this;
}
/**
* 咨询时间
*
* @return consultTime
**/
@ApiModelProperty(value = "咨询时间")
public String getConsultTime() {
return consultTime;
}
public void setConsultTime(String consultTime) {
this.consultTime = consultTime;
}
public ConsultModel replyTime(String replyTime) {
this.replyTime = replyTime;
return this;
}
/**
* 回复时间
*
* @return replyTime
**/
@ApiModelProperty(value = "回复时间")
public String getReplyTime() {
return replyTime;
}
public void setReplyTime(String replyTime) {
this.replyTime = replyTime;
}
public ConsultModel anonymous(Short anonymous) {
this.anonymous = anonymous;
return this;
}
/**
* 是否匿名 1匿名|0不匿名
*
* @return anonymous
**/
@ApiModelProperty(value = "是否匿名 1匿名|0不匿名")
public Short getAnonymous() {
return anonymous;
}
public void setAnonymous(Short anonymous) {
this.anonymous = anonymous;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConsultModel consultModel = (ConsultModel) o;
return Objects.equals(this.memberName, consultModel.memberName) &&
Objects.equals(this.content, consultModel.content) &&
Objects.equals(this.reply, consultModel.reply) &&
Objects.equals(this.consultTime, consultModel.consultTime) &&
Objects.equals(this.replyTime, consultModel.replyTime) &&
Objects.equals(this.anonymous, consultModel.anonymous);
}
@Override
public int hashCode() {
return Objects.hash(memberName, content, reply, consultTime, replyTime, anonymous);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ConsultModel {\n");
sb.append(" memberName: ").append(toIndentedString(memberName)).append("\n");
sb.append(" content: ").append(toIndentedString(content)).append("\n");
sb.append(" reply: ").append(toIndentedString(reply)).append("\n");
sb.append(" consultTime: ").append(toIndentedString(consultTime)).append("\n");
sb.append(" replyTime: ").append(toIndentedString(replyTime)).append("\n");
sb.append(" anonymous: ").append(toIndentedString(anonymous)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep>/business/src/main/java/com/wises/business/goods/mapper/GoodsInfoMapper.java
package com.wises.business.goods.mapper;
import com.wises.business.goods.model.GoodsInfo;
import tk.mybatis.mapper.common.Mapper;
public interface GoodsInfoMapper extends Mapper<GoodsInfo> {
}<file_sep>/business/src/main/java/com/wises/business/goods/mapper/GoodsCategoryMapper.java
package com.wises.business.goods.mapper;
import com.wises.business.goods.model.GoodsCategory;
import tk.mybatis.mapper.common.Mapper;
public interface GoodsCategoryMapper extends Mapper<GoodsCategory> {
}<file_sep>/api-server/src/main/java/com/wises/gateway/component/image/utils/ShowImageUtils.java
package com.wises.gateway.component.image.utils;
import com.wises.gateway.component.image.config.ImageAuthConfig;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ShowImageUtils {
@Autowired
private ImageAuthConfig imageAuthConfig;
/**
* @param id
* 文件id
* @return
*/
public String getUrl(String id) {
return getUrl(id, 0, 0);
}
/**
* @param id
* 文件id
* @param width
* 图片宽度
* @param height
* 图片高度
* @return
*/
public String getUrl(String id, int width, int height) {
if(StringUtils.isEmpty(id)){
return "";
}
if(width < 0){
width = 0;
}
if(height < 0){
height = 0;
}
String url = imageAuthConfig.getDomain();
if (width == 0 && height == 0) {
url = url + id;
} else if (width == 0 && height != 0) {
url = url + id + "@" + height + "h_1l";
} else if (width != 0 && height == 0) {
url = url + id + "@" + width + "w_1l";
} else {
url = url + id + "@" + width + "w_" + height + "h_1l_0e";
}
return url;
}
}
<file_sep>/business/src/main/java/com/wises/business/common/constants/website/FloorType.java
/*
* Copyright 2016 Wicresoft, Inc. All rights reserved.
*/
package com.wises.business.common.constants.website;
/**
* 楼层类型 1 轮播图 2 主导航 3 广告 4 模板
*
* @author qun.su
*/
public enum FloorType {
CAROUSEL((short) 1, "轮播图"),
MAIN_NAVIGATION((short)2, "主导航"),
ADVERT((short)3, "广告"),
TEMPLATES((short)4, "模板");
private final Short code; //状态编码
private final String description;//状态描述
FloorType(Short code, String description) {
this.code = code;
this.description = description;
}
public Short code() {
return code;
}
public String description() {
return description;
}
}
<file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/evaluatons/EvaluationsApi.java
package com.wises.gateway.api.goods.evaluatons;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
@Api(value = "evaluations", description = "the evaluations API")
public interface EvaluationsApi {
@ApiOperation(value = "商品评价查询", notes = "根据商品id查询商品评价内容", response = EvaluationResult.class, tags = {"商品",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = EvaluationResult.class)})
@RequestMapping(value = "/evaluations",
produces = {"application/json"},
method = RequestMethod.GET)
EvaluationResult evaluationsGet(@Valid @ModelAttribute EvaluationParam param, BindingResult result);
}
<file_sep>/business/src/main/java/com/wises/business/website/mapper/JblFloorTplDetailMapper.java
package com.wises.business.website.mapper;
import com.wises.business.website.model.JblFloorTplDetail;
import tk.mybatis.mapper.common.Mapper;
public interface JblFloorTplDetailMapper extends Mapper<JblFloorTplDetail> {
}<file_sep>/api-server/src/main/java/com/wises/gateway/api/home/HomeApi.java
package com.wises.gateway.api.home;
import com.wises.gateway.common.CommonParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
@Api(value = "home", description = "the home API")
public interface HomeApi {
@ApiOperation(value = "首页楼层信息查询", notes = "网站首页信息查询,查询轮播图,主导航,广告,模板等商户在运营平台自定义的首页楼层信息。 ", response = HomeResult.class, tags = {"首页",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "获取首页楼层信息成功", response = HomeResult.class)})
@RequestMapping(value = "/home",
produces = {"application/json"},
method = RequestMethod.GET)
HomeResult indexGet(@Valid @ModelAttribute CommonParam commonParam, BindingResult result);
// HomeResult indexGet(@ApiParam(value = "客户端类型 H5|ios|android", required = true) @RequestParam(value = "client", required = true) String client,
// @ApiParam(value = "版本号", required = true) @RequestParam(value = "version", required = true) String version,
// @ApiParam(value = "token获取用户信息用", required = false) @RequestParam(value = "token", required = false) String token);
//HomeResult indexGet(@ApiParam(value = "参数对象") @RequestBody IndexParam param);
}
<file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/goods/GoodsApiController.java
package com.wises.gateway.api.goods.goods;
import com.wises.gateway.common.constants.RespCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@Slf4j
public class GoodsApiController implements GoodsApi {
public GoodsResult goodsGet(@Valid @ModelAttribute GoodsParam goodsParam, BindingResult result) {
try {
goodsParam.validResult(result);
return new GoodsResult().code(RespCode.SUCCESS.code()).message("ok");
// } catch (ApiException a) {
// log.error(a.getMessage());
// return new GoodsResult().code(a.getCode()).message(a.getMessage());
} catch (Exception e) {
log.error(e.getMessage());
return new GoodsResult().code(RespCode.ERROR.code()).message(e.getMessage());
}
}
}
<file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/evaluatons/EvaluationsApiController.java
package com.wises.gateway.api.goods.evaluatons;
import com.github.pagehelper.PageInfo;
import com.wises.business.goods.model.GoodsEvaluation;
import com.wises.business.goods.service.GoodsEvaluationService;
import com.wises.gateway.common.constants.RespCode;
import com.wises.gateway.exception.ApiException;
import com.wises.gateway.exception.ApiNotFoundException;
import com.wises.gateway.model.goods.EvaluationModel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
@RestController
@Slf4j
public class EvaluationsApiController implements EvaluationsApi {
@Autowired
GoodsEvaluationService goodsEvaluationService;
public EvaluationResult evaluationsGet(@Valid @ModelAttribute EvaluationParam param, BindingResult result) {
// 好评率返回放在商品详情接口里
try {
// 参数格式校验
param.validResult(result);
PageInfo<GoodsEvaluation> pageInfo = goodsEvaluationService.findByPageNumSize(param.getGoodsId());
if (pageInfo.getList().size() == 0) {
throw new ApiNotFoundException(1, "该商品评价信息不存在");
}
List<EvaluationModel> modelList = new ArrayList<>();
for (GoodsEvaluation evaluation : pageInfo.getList()) {
EvaluationModel evaluationModel = new EvaluationModel()
.nickName("")//用户昵称
.iconUrl("")//用户头像
.goodsSpec("")//用户购买订单中该商品规格信息
.scores(evaluation.getScores())
.content(evaluation.getContent())
.explain(evaluation.getExplains())
.evalTime(new DateTime(evaluation.getEvalTime()).toString("yyyy-MM-dd HH:mm:ss"))
.anonymous(evaluation.getAnonymous())
.images(new ArrayList<>());
modelList.add(evaluationModel);
}
return new EvaluationResult().code(RespCode.SUCCESS.code()).message("OK").data(modelList);
} catch (ApiException a) {
log.error(a.getMessage());
return new EvaluationResult().code(a.getCode()).message(a.getMessage());
} catch (Exception e) {
log.error(e.getMessage());
return new EvaluationResult().code(RespCode.ERROR.code()).message(e.getMessage());
}
}
}
<file_sep>/business/src/test/java/com/wises/search/service/EsServiceTest.java
package com.wises.search.service;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* EsServiceTest
* Created by larry.su on 2017/1/27.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:dbunit.xml"})
public class EsServiceTest {
@Autowired EsService esService;
@Test
public void addDocument() throws Exception {
esService.delDocument("website","blog","101");
Map<String,Object> map = new HashMap();
map.put("title","My second blog entry");
map.put("text","Still trying this out...");
esService.addDocument(JSONObject.fromObject(map),"website","blog","101");
}
@Test
public void getDocument() throws Exception {
Map<String, Object> map = esService.getDocument("website","blog","101");
Assert.isTrue(map.entrySet().size() == 2);
}
@Test
public void delDocument() throws Exception {
esService.delDocument("website","blog","101");
}
@Test
public void updateDocument() throws Exception {
Map<String,Object> map = new HashMap();
map.put("title","My second blog entry");
map.put("text","Still trying this out...");
esService.updateDocument("website","blog","101","title","My third blog entry");
}
@Test
public void addDocuments() throws Exception {
}
@Test
public void queryDocuments() throws Exception {
}
}<file_sep>/business/src/main/java/com/wises/business/website/model/JblFloor.java
package com.wises.business.website.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
@Table(name = "JBL_FLOOR")
public class JblFloor implements Serializable {
/**
* 主键ID
*/
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
/**
* 首页类型 首页 Index 默认
*/
@Column(name = "HOMEPAGE_TYPE")
private String homepageType;
/**
* 楼层类型 1 轮播图 2 主导航 3 秒杀栏楼层 4 广告 5 模板
*/
@Column(name = "FLOOR_TYPE")
private Short floorType;
/**
* 名称
*/
@Column(name = "FLOOR_NAME")
private String floorName;
/**
* 简介
*/
@Column(name = "FLOOR_INTRO")
private String floorIntro;
/**
* 是否启用:0不启用1启用
*/
@Column(name = "FLOOR_ACTIVE")
private Short floorActive;
/**
* 排序
*/
@Column(name = "FLOOR_SORT")
private Short floorSort;
/**
* 创建时间
*/
@Column(name = "CREATED_TIME")
private Date createdTime;
/**
* 模板ID
*/
@Column(name = "TEMPLATE_ID")
private String templateId;
//不是表中字段的属性必须加 @Transient 注解
@Transient
private List<JblFloorData> floorDataList;
//不是表中字段的属性必须加 @Transient 注解
@Transient
private JblFloorTpl floorTpl;
/**
* 获取主键ID
*
* @return ID - 主键ID
*/
public String getId() {
return id;
}
/**
* 设置主键ID
*
* @param id 主键ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取首页类型 首页 Index 默认
*
* @return HOMEPAGE_TYPE - 首页类型 首页 Index 默认
*/
public String getHomepageType() {
return homepageType;
}
/**
* 设置首页类型 首页 Index 默认
*
* @param homepageType 首页类型 首页 Index 默认
*/
public void setHomepageType(String homepageType) {
this.homepageType = homepageType;
}
/**
* 获取楼层类型 1 轮播图 2 主导航 3 秒杀栏楼层 4 广告 5 模板
*
* @return FLOOR_TYPE - 楼层类型 1 轮播图 2 主导航 3 秒杀栏楼层 4 广告 5 模板
*/
public Short getFloorType() {
return floorType;
}
/**
* 设置楼层类型 1 轮播图 2 主导航 3 秒杀栏楼层 4 广告 5 模板
*
* @param floorType 楼层类型 1 轮播图 2 主导航 3 秒杀栏楼层 4 广告 5 模板
*/
public void setFloorType(Short floorType) {
this.floorType = floorType;
}
/**
* 获取名称
*
* @return FLOOR_NAME - 名称
*/
public String getFloorName() {
return floorName;
}
/**
* 设置名称
*
* @param floorName 名称
*/
public void setFloorName(String floorName) {
this.floorName = floorName;
}
/**
* 获取简介
*
* @return FLOOR_INTRO - 简介
*/
public String getFloorIntro() {
return floorIntro;
}
/**
* 设置简介
*
* @param floorIntro 简介
*/
public void setFloorIntro(String floorIntro) {
this.floorIntro = floorIntro;
}
/**
* 获取是否启用:0不启用1启用
*
* @return FLOOR_ACTIVE - 是否启用:0不启用1启用
*/
public Short getFloorActive() {
return floorActive;
}
/**
* 设置是否启用:0不启用1启用
*
* @param floorActive 是否启用:0不启用1启用
*/
public void setFloorActive(Short floorActive) {
this.floorActive = floorActive;
}
/**
* 获取排序
*
* @return FLOOR_SORT - 排序
*/
public Short getFloorSort() {
return floorSort;
}
/**
* 设置排序
*
* @param floorSort 排序
*/
public void setFloorSort(Short floorSort) {
this.floorSort = floorSort;
}
/**
* 获取创建时间
*
* @return CREATED_TIME - 创建时间
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置创建时间
*
* @param createdTime 创建时间
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取模板ID
*
* @return TEMPLATE_ID - 模板ID
*/
public String getTemplateId() {
return templateId;
}
/**
* 设置模板ID
*
* @param templateId 模板ID
*/
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public List<JblFloorData> getFloorDataList() {
return floorDataList;
}
public void setFloorDataList(List<JblFloorData> floorDataList) {
this.floorDataList = floorDataList;
}
public JblFloorTpl getFloorTpl() {
return floorTpl;
}
public void setFloorTpl(JblFloorTpl floorTpl) {
this.floorTpl = floorTpl;
}
}<file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/consult/GetConsultParam.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.gateway.api.goods.consult;
import com.wises.gateway.common.CommonParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import org.hibernate.validator.constraints.NotEmpty;
/**
* GetConsultParam
* Created by larry.su on 2017/1/31.
*/
@Data
@ToString
@ApiModel(value = "GetConsultParam", description = "商品咨询参数对象")
public class GetConsultParam extends CommonParam {
@ApiModelProperty(value = "商品ID", required = true)
@NotEmpty(message = "goodsId不能为空")
private String goodsId;
}
<file_sep>/api-server/src/main/java/com/wises/gateway/api/goods/category/GoodsCategoriesApiController.java
package com.wises.gateway.api.goods.category;
import com.wises.business.goods.model.GoodsCategory;
import com.wises.business.goods.service.GoodsCategoryService;
import com.wises.gateway.common.CommonParam;
import com.wises.gateway.common.constants.RespCode;
import com.wises.gateway.component.image.utils.ShowImageUtils;
import com.wises.gateway.exception.ApiException;
import com.wises.gateway.model.goods.GoodsCategoryModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
public class GoodsCategoriesApiController implements GoodsCategoriesApi {
@Autowired
GoodsCategoryService goodsCategoryService;
@Autowired
private ShowImageUtils showImageUtils;
public GoodsCategoryResult goodsCategoriesGet(@Valid @ModelAttribute CommonParam commonParam, BindingResult result) {
try {
//参数格式校验
commonParam.validResult(result);
//待返回数据
List<GoodsCategoryModel> firstModelList = new ArrayList<>();
//查第一大类parentId=0
List<GoodsCategory> firstList = goodsCategoryService.findCategoriesByParentId("0");
if (firstList.size() == 0) {
log.info("未查询到商品分类信息!");
return new GoodsCategoryResult().code(1).message("未查询到商品分类信息");
}
for (GoodsCategory firstCategory : firstList) {
GoodsCategoryModel firstCategoryModel = createCategoryModel(firstCategory);
//循环查第二大类
List<GoodsCategory> secondList = goodsCategoryService
.findCategoriesByParentId(firstCategory.getId());
if (secondList.size() > 0) {
List<GoodsCategoryModel> secondModelList = new ArrayList<>();
for (GoodsCategory secondCategory : secondList) {
secondModelList.add(createCategoryModel(secondCategory));
}
firstCategoryModel.setGoodsCategoryModel(secondModelList);
}
firstModelList.add(firstCategoryModel);
}
return new GoodsCategoryResult().code(RespCode.SUCCESS.code()).message("ok").data(firstModelList);
} catch (ApiException ae) {
log.error(ae.getMessage());
return new GoodsCategoryResult().code(ae.getCode()).message(ae.getMessage());
} catch (Exception e) {
log.error(e.getMessage());
return new GoodsCategoryResult().code(RespCode.ERROR.code()).message(e.getMessage());
}
}
/**
* 商品分类model设置属性
*
* @param goodsCategory
* @return
*/
private GoodsCategoryModel createCategoryModel(GoodsCategory goodsCategory) {
GoodsCategoryModel categoryModel = new GoodsCategoryModel()
.id(goodsCategory.getId())
.name(goodsCategory.getName());
//设置图片URL
if (StringUtils.isNotBlank(goodsCategory.getImageId())) {
categoryModel.imageUrl(showImageUtils.getUrl(goodsCategory.getImageId()));
}
return categoryModel;
}
}
<file_sep>/api-server/src/main/java/com/wises/gateway/api/hotword/HotWordsApi.java
package com.wises.gateway.api.hotword;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
@Api(value = "热词", description = "热词获取接口")
public interface HotWordsApi {
@ApiOperation(value = "热词查询", notes = "查询热词", response = HotWordsResult.class, tags = {"商品",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = HotWordsResult.class)})
@RequestMapping(value = "/hotWords",
produces = {"application/json"},
method = RequestMethod.GET)
HotWordsResult hotWordsGet(@Valid @ModelAttribute HotWordsParam param, BindingResult result);
}
<file_sep>/api-server/src/main/java/com/wises/gateway/api/hotword/HotWordsParam.java
/*
* Copyright 2017 Wicrenet, Inc. All rights reserved.
*/
package com.wises.gateway.api.hotword;
import com.wises.gateway.common.CommonParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import javax.validation.constraints.Pattern;
/**
* GoodsParam
* Created by larry.su on 2017/2/4.
*/
@Data
@ToString
@ApiModel(value = "HotWordsParam", description = "热词参数对象")
public class HotWordsParam extends CommonParam {
@ApiModelProperty(value = "显示数量", required = true)
@Pattern(regexp = "^\\+?[1-9][0-9]*$", message = "必须为非零正整数")
private String showNumber;
}<file_sep>/demo/src/test/java/com/wises/demo/component/dbunit/DbUnitTestCase.java
/*
* Copyright 2016 Wicrenet, Inc. All rights reserved.
*/
package com.wises.demo.component.dbunit;
import com.wises.common.component.SpringContextUtil;
import org.dbunit.DBTestCase;
import org.dbunit.IDatabaseTester;
import org.dbunit.assertion.DbUnitAssert;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.datatype.DefaultDataTypeFactory;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
public class DbUnitTestCase extends DBTestCase {
private static final Logger logger = LoggerFactory.getLogger(DbUnitTestCase.class);
private DbUnitSetting dbUnitSetting;
public DbUnitTestCase() {
}
protected void setUp() throws Exception {
this.dbUnitSetting = SpringContextUtil.getBean(DbUnitSetting.class);
System.setProperty("dbunit.driverClass", this.dbUnitSetting.getDriverClass());
System.setProperty("dbunit.connectionUrl", this.dbUnitSetting.getJdbcUrl());
System.setProperty("dbunit.username", this.dbUnitSetting.getUser());
System.setProperty("dbunit.password", this.dbUnitSetting.getPassword());
if (!StringUtils.isEmpty(this.dbUnitSetting.getSchema())) {
System.setProperty("dbunit.schema", this.dbUnitSetting.getSchema());
}
super.setUp();
}
protected String getDataSetXmlClassPath() {
return this.getClass().getName();
}
protected IDataSet getDataSet() throws DataSetException {
String dataSetXmlClassPath = this.getDataSetXmlClassPath();
return readDataSet(dataSetXmlClassPath);
}
protected void setUpDatabaseConfig(DatabaseConfig config) {
super.setUpDatabaseConfig(config);
DefaultDataTypeFactory dataTypeFactory = new DefaultDataTypeFactory();
if (!StringUtils.isEmpty(this.dbUnitSetting.getDataTypeFactory())) {
try {
dataTypeFactory = (DefaultDataTypeFactory) Class.forName(this.dbUnitSetting.getDataTypeFactory()).newInstance();
} catch (Exception var4) {
logger.error("setUpDatabaseConfig", var4);
}
}
config.setProperty("http://www.dbunit.org/properties/datatypeFactory", dataTypeFactory);
}
public ITable queryTable(String tableName, String sqlQuery, String[] ignoreCols) throws Exception {
ITable queriedTable = this.getConnection().createQueryTable(tableName, sqlQuery);
ITable actual = DefaultColumnFilter.excludedColumnsTable(queriedTable, ignoreCols);
return actual;
}
public void assertByQuery(String tableName, IDataSet expectedDataset, String sqlQuery, String[] ignoreCols) throws Exception {
(new DbUnitAssert()).assertEqualsByQuery(expectedDataset, this.getConnection(), sqlQuery, tableName, ignoreCols);
}
public static IDataSet readDataSet(String classPath) throws DataSetException {
if (!StringUtils.isEmpty(classPath)) {
classPath = classPath.replaceAll("\\.", "/") + ".xml";
return (new FlatXmlDataSetBuilder()).build(DbUnitTestCase.class.getClassLoader().getResource(classPath));
} else {
return null;
}
}
protected IDatabaseTester newDatabaseTester() throws Exception {
return new MySQLJdbcDatabaseTester(this.dbUnitSetting.getDriverClass(),this.dbUnitSetting.getJdbcUrl(),
this.dbUnitSetting.getUser(),this.dbUnitSetting.getPassword(),this.dbUnitSetting.getSchema());
}
}
<file_sep>/api-server/README.md
## 客户端API服务网关
<file_sep>/api-server/src/main/java/com/wises/gateway/component/swagger/SwaggerConfig.java
package com.wises.gateway.component.swagger;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
//import springfox.documentation.service.Contact;
/**
* Swagger描述
* Created by larry.su on 2017/1/5.
*/
@EnableSwagger2
public class SwaggerConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Wises API")
.description("接口API")
.license("")
.licenseUrl("")
.termsOfServiceUrl("http://localhost:8088/v1")
.version("1.0.0")
.contact(new Contact("", "", ""))
.build();
}
@Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.wises.gateway.api"))
.build()
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
.apiInfo(apiInfo());
// .pathMapping("/v1");// 在这里可以设置请求的统一前缀
}
}
<file_sep>/api-server/src/main/java/com/wises/gateway/model/goods/EvaluationModel.java
package com.wises.gateway.model.goods;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 商品评价
*/
public class EvaluationModel {
@JsonProperty("nickName")
private String nickName = null;
@JsonProperty("iconUrl")
private String iconUrl = null;
@JsonProperty("goodsSpec")
private String goodsSpec = null;
@JsonProperty("scores")
private Short scores = null;
@JsonProperty("content")
private String content = null;
@JsonProperty("explain")
private String explain = null;
@JsonProperty("evalTime")
private String evalTime = null;
@JsonProperty("anonymous")
private Short anonymous = null;
@JsonProperty("images")
private List<String> images = new ArrayList<String>();
public EvaluationModel nickName(String nickName) {
this.nickName = nickName;
return this;
}
/**
* 评价人昵称
*
* @return nickName
**/
@ApiModelProperty(value = "评价人昵称")
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public EvaluationModel iconUrl(String iconUrl) {
this.iconUrl = iconUrl;
return this;
}
/**
* 评价人头像URL
*
* @return iconUrl
**/
@ApiModelProperty(value = "评价人头像URL")
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public EvaluationModel goodsSpec(String goodsSpec) {
this.goodsSpec = goodsSpec;
return this;
}
/**
* 商品规格
*
* @return goodsSpec
**/
@ApiModelProperty(value = "商品规格")
public String getGoodsSpec() {
return goodsSpec;
}
public void setGoodsSpec(String goodsSpec) {
this.goodsSpec = goodsSpec;
}
public EvaluationModel scores(Short scores) {
this.scores = scores;
return this;
}
/**
* 评价得分1-5分
*
* @return scores
**/
@ApiModelProperty(value = "评价得分1-5分")
public Short getScores() {
return scores;
}
public void setScores(Short scores) {
this.scores = scores;
}
public EvaluationModel content(String content) {
this.content = content;
return this;
}
/**
* 评价内容
*
* @return content
**/
@ApiModelProperty(value = "评价内容")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public EvaluationModel explain(String explain) {
this.explain = explain;
return this;
}
/**
* 商户解释
*
* @return explain
**/
@ApiModelProperty(value = "商户解释")
public String getExplain() {
return explain;
}
public void setExplain(String explain) {
this.explain = explain;
}
public EvaluationModel evalTime(String evalTime) {
this.evalTime = evalTime;
return this;
}
/**
* 评价时间
*
* @return evalTime
**/
@ApiModelProperty(value = "评价时间")
public String getEvalTime() {
return evalTime;
}
public void setEvalTime(String evalTime) {
this.evalTime = evalTime;
}
public EvaluationModel anonymous(Short anonymous) {
this.anonymous = anonymous;
return this;
}
/**
* 是否匿名,1匿名|0不匿名
*
* @return anonymous
**/
@ApiModelProperty(value = "是否匿名,1匿名|0不匿名")
public Short getAnonymous() {
return anonymous;
}
public void setAnonymous(Short anonymous) {
this.anonymous = anonymous;
}
public EvaluationModel images(List<String> images) {
this.images = images;
return this;
}
public EvaluationModel addImagesItem(String imagesItem) {
this.images.add(imagesItem);
return this;
}
/**
* 图片URL列表
*
* @return images
**/
@ApiModelProperty(value = "图片URL列表")
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EvaluationModel evaluationModel = (EvaluationModel) o;
return Objects.equals(this.nickName, evaluationModel.nickName) &&
Objects.equals(this.iconUrl, evaluationModel.iconUrl) &&
Objects.equals(this.goodsSpec, evaluationModel.goodsSpec) &&
Objects.equals(this.scores, evaluationModel.scores) &&
Objects.equals(this.content, evaluationModel.content) &&
Objects.equals(this.explain, evaluationModel.explain) &&
Objects.equals(this.evalTime, evaluationModel.evalTime) &&
Objects.equals(this.anonymous, evaluationModel.anonymous) &&
Objects.equals(this.images, evaluationModel.images);
}
@Override
public int hashCode() {
return Objects.hash(nickName, iconUrl, goodsSpec, scores, content, explain, evalTime, anonymous, images);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EvaluationModel {\n");
sb.append(" nickName: ").append(toIndentedString(nickName)).append("\n");
sb.append(" iconUrl: ").append(toIndentedString(iconUrl)).append("\n");
sb.append(" goodsSpec: ").append(toIndentedString(goodsSpec)).append("\n");
sb.append(" scores: ").append(toIndentedString(scores)).append("\n");
sb.append(" content: ").append(toIndentedString(content)).append("\n");
sb.append(" explain: ").append(toIndentedString(explain)).append("\n");
sb.append(" evalTime: ").append(toIndentedString(evalTime)).append("\n");
sb.append(" anonymous: ").append(toIndentedString(anonymous)).append("\n");
sb.append(" images: ").append(toIndentedString(images)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep>/demo/src/main/java/com/wises/demo/api/UserApi.java
//package com.wises.demo.api;
//
//import com.wises.common.model.response.WisesResponseEntity;
//import com.wises.demo.model.User;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//
//@Api(value = "User API", description = "用户服务接口")
//@RequestMapping("/users")
//public interface UserApi {
//
//
// @ApiOperation(value = "新增用户",
// notes = "新增用户",
// response = User.class,
// tags = {"用户服务",})
// @RequestMapping(value = "/", method = RequestMethod.POST)
// WisesResponseEntity save(@RequestBody User user);
//
//
// @ApiOperation(value = "根据姓名模糊查询",
// notes = "模糊查询",
// response = User.class,
// tags = {"用户服务",})
// @RequestMapping(value = "/{name}", method = RequestMethod.GET)
// WisesResponseEntity<User> query(@ApiParam(value = "姓名", name = "name")@PathVariable String name);
//
//
// @ApiOperation(value = "修改用户信息",
// notes = "修改用户",
// response = User.class,
// tags = {"用户服务",})
// @RequestMapping(value = "/{name}/{password}", method = RequestMethod.PATCH)
// WisesResponseEntity update(@ApiParam(value = "姓名", name = "name")@PathVariable String name
// ,@ApiParam(value = "密码", name = "password") @PathVariable String password);
//}
<file_sep>/business/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>wises-parent</artifactId>
<groupId>com.wises</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>business</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<!-- MyBatis Generator -->
<targetJavaProject>${basedir}/src/main/java</targetJavaProject>
<targetMapperPackage>com.wises.business.templates.mapper</targetMapperPackage>
<targetModelPackage>com.wises.business.templates.model</targetModelPackage>
<targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
<targetXMLPackage>mybatis_mapper</targetXMLPackage>
</properties>
<dependencies>
<dependency>
<groupId>com.wises</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--compile-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!--elasticsearch-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/db/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${mapper.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project><file_sep>/business/src/main/java/com/wises/business/promotion/model/PromoBuyandget.java
package com.wises.business.promotion.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
@Table(name = "PROMO_BUYANDGET")
public class PromoBuyandget implements Serializable {
/**
* 主键ID
*/
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
/**
* 商家ID
*/
@Column(name = "MERCHANT_ID")
private String merchantId;
/**
* 促销套餐认购ID
*/
@Column(name = "SUBSCRIPTION_ID")
private String subscriptionId;
/**
* 优惠券套餐模版ID
*/
@Column(name = "COUPON_TEMPLATE_ID")
private String couponTemplateId;
/**
* 买即送名称
*/
@Column(name = "NAME")
private String name;
/**
* 可用设备类型,0所有,1是PC, 2是APP
*/
@Column(name = "DEVICE_TYPE")
private Short deviceType;
/**
* 是否平台优惠 0 否 1是
*/
@Column(name = "PLATFORM")
private Short platform;
/**
* 购物范围,0全店铺,1分类,2单品
*/
@Column(name = "SCOPE")
private Short scope;
/**
* 分类ID
*/
@Column(name = "CATEGORY_ID")
private String categoryId;
/**
* 商品ID
*/
@Column(name = "GOODS_ID")
private String goodsId;
/**
* 活动开始时间
*/
@Column(name = "START_TIME")
private Date startTime;
/**
* 活动结束时间
*/
@Column(name = "END_TIME")
private Date endTime;
/**
* 活动状态,0默认 1-正常 2 已结束 3-管理员已关闭
*/
@Column(name = "STATE")
private Short state;
/**
* 备注
*/
@Column(name = "REMARK")
private String remark;
/**
* 订单类型 Goods 、 O2o
*/
@Column(name = "ORDER_TYPE")
private String orderType;
/**
* 获取主键ID
*
* @return ID - 主键ID
*/
public String getId() {
return id;
}
/**
* 设置主键ID
*
* @param id 主键ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取商家ID
*
* @return MERCHANT_ID - 商家ID
*/
public String getMerchantId() {
return merchantId;
}
/**
* 设置商家ID
*
* @param merchantId 商家ID
*/
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
/**
* 获取促销套餐认购ID
*
* @return SUBSCRIPTION_ID - 促销套餐认购ID
*/
public String getSubscriptionId() {
return subscriptionId;
}
/**
* 设置促销套餐认购ID
*
* @param subscriptionId 促销套餐认购ID
*/
public void setSubscriptionId(String subscriptionId) {
this.subscriptionId = subscriptionId;
}
/**
* 获取优惠券套餐模版ID
*
* @return COUPON_TEMPLATE_ID - 优惠券套餐模版ID
*/
public String getCouponTemplateId() {
return couponTemplateId;
}
/**
* 设置优惠券套餐模版ID
*
* @param couponTemplateId 优惠券套餐模版ID
*/
public void setCouponTemplateId(String couponTemplateId) {
this.couponTemplateId = couponTemplateId;
}
/**
* 获取买即送名称
*
* @return NAME - 买即送名称
*/
public String getName() {
return name;
}
/**
* 设置买即送名称
*
* @param name 买即送名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取可用设备类型,0所有,1是PC, 2是APP
*
* @return DEVICE_TYPE - 可用设备类型,0所有,1是PC, 2是APP
*/
public Short getDeviceType() {
return deviceType;
}
/**
* 设置可用设备类型,0所有,1是PC, 2是APP
*
* @param deviceType 可用设备类型,0所有,1是PC, 2是APP
*/
public void setDeviceType(Short deviceType) {
this.deviceType = deviceType;
}
/**
* 获取是否平台优惠 0 否 1是
*
* @return PLATFORM - 是否平台优惠 0 否 1是
*/
public Short getPlatform() {
return platform;
}
/**
* 设置是否平台优惠 0 否 1是
*
* @param platform 是否平台优惠 0 否 1是
*/
public void setPlatform(Short platform) {
this.platform = platform;
}
/**
* 获取购物范围,0全店铺,1分类,2单品
*
* @return SCOPE - 购物范围,0全店铺,1分类,2单品
*/
public Short getScope() {
return scope;
}
/**
* 设置购物范围,0全店铺,1分类,2单品
*
* @param scope 购物范围,0全店铺,1分类,2单品
*/
public void setScope(Short scope) {
this.scope = scope;
}
/**
* 获取分类ID
*
* @return CATEGORY_ID - 分类ID
*/
public String getCategoryId() {
return categoryId;
}
/**
* 设置分类ID
*
* @param categoryId 分类ID
*/
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
/**
* 获取商品ID
*
* @return GOODS_ID - 商品ID
*/
public String getGoodsId() {
return goodsId;
}
/**
* 设置商品ID
*
* @param goodsId 商品ID
*/
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
/**
* 获取活动开始时间
*
* @return START_TIME - 活动开始时间
*/
public Date getStartTime() {
return startTime;
}
/**
* 设置活动开始时间
*
* @param startTime 活动开始时间
*/
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
/**
* 获取活动结束时间
*
* @return END_TIME - 活动结束时间
*/
public Date getEndTime() {
return endTime;
}
/**
* 设置活动结束时间
*
* @param endTime 活动结束时间
*/
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
/**
* 获取活动状态,0默认 1-正常 2 已结束 3-管理员已关闭
*
* @return STATE - 活动状态,0默认 1-正常 2 已结束 3-管理员已关闭
*/
public Short getState() {
return state;
}
/**
* 设置活动状态,0默认 1-正常 2 已结束 3-管理员已关闭
*
* @param state 活动状态,0默认 1-正常 2 已结束 3-管理员已关闭
*/
public void setState(Short state) {
this.state = state;
}
/**
* 获取备注
*
* @return REMARK - 备注
*/
public String getRemark() {
return remark;
}
/**
* 设置备注
*
* @param remark 备注
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 获取订单类型 Goods 、 O2o
*
* @return ORDER_TYPE - 订单类型 Goods 、 O2o
*/
public String getOrderType() {
return orderType;
}
/**
* 设置订单类型 Goods 、 O2o
*
* @param orderType 订单类型 Goods 、 O2o
*/
public void setOrderType(String orderType) {
this.orderType = orderType;
}
}
|
56e084ef0a88d15ee072ff19697c5d46803af372
|
[
"Markdown",
"Java",
"Maven POM"
] | 50 |
Java
|
suqun/webapi
|
316d458065815250baf67d9ec3554ccdc95dc04f
|
915dcb19f03c62d5654a4bda8e0bac4f08698f2f
|
refs/heads/master
|
<file_sep>const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}))
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
const MongoClient = require('mongodb').MongoClient
let db = null
MongoClient.connect('mongodb://menomanabdulla:<EMAIL>:61660/star-wars-talk',(err,client) => {
if(err) return console.log(err)
db = client.db('star-wars-talk')
app.listen(3001,()=>{
console.log('listening on 3001')
})
})
/*app.listen(3000,function(){
console.log('app listen')
})*/
app.post('/ui',(req,res) => {
res.send('hello world')
})
app.get('/',(req,res)=>{
db.collection('quotes').find().toArray((err,result)=>{
if(err) return console.log(err)
res.render('index.ejs',{quotes:result})
})
})
app.post('/quotes', (req, res) => {
//console.log(req.body)
db.collection('quotes').save(req.body,(err,result)=>{
if(err) return console.log(err)
console.log('Successfully Saved to database')
res.redirect('/')
})
})
|
57db91fe2598712545bad4018ad67a2f483e55e5
|
[
"JavaScript"
] | 1 |
JavaScript
|
menomanabdulla/menCRUD
|
9346072796c5a980f92409f8678f56c791242fe2
|
0d540fb078c9ef558e6f9b654f3a5e98482e0027
|
refs/heads/master
|
<file_sep>(function() {
var config = {
base: '/src', // 基于调用seajs.use()的页面地址
alias: {
'jquery': 'build/jquery',
'spm-jquery': 'build/jquery',
'limit2.0': 'build/limit2.0',
'arale-class': 'class/class',
'arale-events': 'events/events',
'arale-base': 'base/base',
'arale-widget': 'widget/src/widget'
},
debug: true,
chartset: 'utf-8'
};
seajs.config(config);
if(typeof define === 'function') {
define(function(require, exports, module){
module.exports = config;
})
}
return config;
})()<file_sep>var gulp = require('gulp');
// babel
// (src.*)为文件名之前的完整路径
var matchRex = /(src.*)\/.*\.(\w+)/;
var babel = require('gulp-babel');
var babelTask = (e) => {
var match = e.path.replace(/\\/g, '/').match( matchRex ),
file, filePath;
if(match.length) {
file = match[0]; // src/dataRow.jsx
filePath = match[1];
gulp.src( file )
.pipe( babel( {
presets: ['es2015']
} ).on('error', (e) => {
console.error('error', e.message);
}) )
.pipe(gulp.dest( filePath ));
}
};
gulp.task('watch', function() {
// babel & jsx
gulp.watch(['src/**/*.jsx', 'src/**/*.es6']).on('change', (event) => {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...[babel]');
babelTask(event);
});
});
gulp.task('default', ['watch']);
|
c8c4b77d639d132a48f90e3f4bb8c085bf7c1552
|
[
"JavaScript"
] | 2 |
JavaScript
|
xuwb/custom-widget
|
59b96b205d4850a5d3cfddd756f6a0d2a8a6ca99
|
f29629040df06f42798a08f38c112704da4291ce
|
refs/heads/master
|
<file_sep><nav class="navbar fixed-top navbar-expand-lg ftco-navbar-light" id="ftco-navbar">
<div class="container">
<a class="navbar-brand" href="index.php">
<img src="images/NavLogo.png" width="80">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="oi oi-menu"></span> Menu
</button>
<div class="collapse navbar-collapse" id="ftco-nav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active"><a href="index.php" class="nav-link hvr-underline-from-left">Home</a></li>
<li class="nav-item">
<a class="nav-link hvr-underline-from-left" href="shop.php" aria-haspopup="true" aria-expanded="false">Shop</a>
</li>
<?php if (isset($_SESSION['idLogin'])) { ?>
<li class="nav-item"><a href="pesan.php" class="nav-link hvr-underline-from-left">Order List</a></li>
<li class="nav-item"><a href="history.php" class="nav-link hvr-underline-from-left">History</a></li>
<li class="nav-item"><a href="process/userLogout.php" class="nav-link hvr-underline-from-left">Logout</a></li>
<?php } ?>
<?php if (!isset($_SESSION['idLogin'])) { ?>
<li class="nav-item"><a href="login.php" class="nav-link hvr-underline-from-left">Login</a></li>
<?php } ?>
</ul>
</div>
</div>
</nav><file_sep><?php
include 'process/conSQL.php';
session_start();
if (!isset($_SESSION['idLogin'])) {
header("Location: index.php");
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == 2) {
header("Location: index.php");
}
}
include 'adminHeader.php';
?>
<body class="admin-bg">
<?php include 'script.php' ?>
</body>
</html><file_sep><footer class="mainfooter" role="contentinfo">
<div class="footer-middle">
<div class="container">
<div class="row">
<div class="col-3 text-center">
<h4 class="text-bright"><b>FOLLOW US</b></h4>
<ul class="social-network social-circle">
<li><a href="#" class="icoFacebook" title="Facebook"><i class="fab fa-facebook-f"></i></a></li>
<li><a href="#" class="icoLinkedin" title="Linkedin"><i class="fab fa-linkedin-in"></i></a></li>
<li><a href="#" class="icoTwitter" title="Twitter"><i class="fab fa-twitter"></i></a></li>
<li><a href="#" class="icoYoutube" title="Youtube"><i class="fas fa-play"></i></a></li>
</ul>
<p class="text-bright mt-2 mb-0">More Information:</p>
<p class="text-bright"><EMAIL></p>
</div>
<div class="col-6 text-center">
<img src="images/FooterLogo.png" width="180" class="mt-3">
</div>
<div class="col-3 text-center">
</div>
</div>
<div class="row">
<div class="col-md-12 copy">
<p class="text-center">© Copyright 2019 - WarePlan. All rights reserved.</p>
</div>
</div>
</div>
</div>
</footer>
<?php include 'script.php' ?>
</body>
</html><file_sep><?php
include 'conSQL.php';
session_start();
if (isset($_SESSION['idKonsumen'])) {
$userid = $_SESSION['idKonsumen'];
}
// if (isset($_SESSION['id'])) {
// $userid = $_SESSION['user'];
// }
$Deliver = $_POST["Deliver"];
//untuk nampilin waktu now saat pesen (udh bisa tampil waktu now, tp blm bisa mengambil idPesanan u/ mengisi detail_pesanan)
$time = "INSERT INTO pesanan (TanggalJam) VALUES (now())";
if (mysqli_query($con, $time)) {
$id_pesanan = mysqli_insert_id($con);
$query = "UPDATE detail_pesanan SET idPesanan = $id_pesanan, status = 'Accept', deliverto='$Deliver' WHERE idKonsumen='$userid' and status = '0'";
if (mysqli_query($con, $query)) {
//stok
header("Location: ../status.php");
}
}
<file_sep><head>
<?php
include 'process/conSQL.php';
session_start();
if (!isset($_SESSION['idLogin'])) {
header("Location: index.php");
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == 2) {
header("Location: index.php");
}
}
include 'adminHeader.php' ?>
</head>
<section class="ftco-section ftco-cart">
<div class="container">
<div class="col-md-12 heading-section text-center ftco-animate">
<h2 class="mb-4">Product List</h2></br>
</div>
<div class="row">
<div class="col-md-12 ftco-animate">
<div class="cart-list">
<p><a href="adminAddProduct.php" class="btn btn-primary py-3 px-4">Add Product</a></p>
<table id="barang" class="table table-strped">
<thead class="thead-primary">
<tr class="text-center">
<th>Image</th>
<th>Product Name</th>
<th>Category</th>
<th>Quantity</th>
<th>Price</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM barang order by idBarang desc";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$index = 1;
while ($row = mysqli_fetch_assoc($result)) {
$idBarang = $row["idBarang"];
echo "
<tr>
<td>" . "<img src='process/imgBarang/" . $row["foto"] . "' width=\"150\" alt=\"gambar\">" . "</td>
<td>" . $row["NamaBarang"] . "</td>
<td>" . $row["idKategori"] . "</td>
<td>" . $row["JumlahBarang"] . "</td>
<td>" . $row["HargaBarang"] . "</td>
<td>
<a href='adminUpdateProduct.php?id=$idBarang&idcat=" . $row["idKategori"] . "' class='btn btn-warning'>Update</a>
</td>
<td> <a href='process/deleteBarang.php?idBarang=$idBarang' class='btn btn-danger'>Delete</a> </td>
</tr>
";
}
}
mysqli_close($con);
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
<?php include 'script.php' ?>
</body>
</html><file_sep><?php
error_reporting(0);
include 'process/conSQL.php';
session_start();
if (!isset($_SESSION['idLogin'])) {
header("Location: index.php");
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == 1) {
header("Location: adminHome.php");
}
}
if (isset($_SESSION['idKonsumen'])) {
$userid = $_SESSION['idKonsumen'];
}
include 'header.php'
?>
<section class="ftco-section ftco-cart">
<div class="container">
<div class="col-md-12 heading-section text-center ftco-animate">
<h2 class="mb-4">Order List</h2>
</div>
<div class="row">
<div class="col-md-12 ftco-animate">
<div class="cart-list">
<table id="barang" class="table">
<thead class="thead-primary">
<tr class="text-center">
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$login = $_SESSION['idLogin'];
$query = "SELECT * FROM detail_pesanan dp
inner join konsumen k on k.idKonsumen = dp.idKonsumen
inner join Barang b on b.idBarang = dp.idBarang
where idLogin = $login AND status ='0'
";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$index = 1;
while ($row = mysqli_fetch_assoc($result)) {
$idBarang = $row["idBarang"];
$total = $row["jmlPesanan"] * $row["HargaBarang"];
echo "
<tr>
<td>" . $row["NamaBarang"] . "</td>
<td>" . $row["HargaBarang"] . "</td>
<td>" . $row["jmlPesanan"] . "</td>
<td>" . $total . "</td>
<td> <a href='process/deleteBrgUser.php?idBarang=$idBarang' class='btn btn-danger'>Delete</a> </td>
</tr>
";
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<div class="row justify-content-end">
<div class="col-lg-8 mt-5 cart-wrap ftco-animate">
</div>
<div class="col-lg-4 mt-5 cart-wrap ftco-animate">
<div class="cart-total mb-3">
<!-- ///disiini -->
<?php
$login = $_SESSION['idLogin'];
$queryyy = "SELECT SUM(bat) FROM (SELECT SUM(jmlPesanan * HargaBarang)
as bat FROM barang b INNER JOIN
detail_pesanan o ON b.idBarang = o.idBarang
WHERE idKonsumen = '$userid' AND status = '0' GROUP BY b.idBarang
) AS bat";
$resulttt = mysqli_query($con, $queryyy);
$rowww = mysqli_fetch_array($resulttt);
?>
<p class="d-flex total-price">
<span>Total</span>
<span>Rp <?= $rowww[0] ?></span>
</p>
<form action="process/Checkout.php" method="POST" enctype="multipart/form-data">
<p class="d-flex total-price">
</p>
<button class="d-flex total-price btn btn-primary py-3 px-4" type="submit" name="submit">PROCESS</button>
</p>
</form>
</span>
</div>
</div>
</div>
</section>
<?php include 'footer.php' ?><file_sep><head>
<?php
include 'process/conSQL.php';
session_start();
if (!isset($_SESSION['idLogin'])) {
header("Location: index.php");
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == 2) {
header("Location: index.php");
}
}
include 'adminHeader.php' ?>
</head>
<section class="ftco-section ftco-cart">
<div class="container">
<div class="col-md-12 heading-section text-center ftco-animate">
<h2 class="mb-4">Order List</h2></br>
</div>
<div class="row">
<div class="col-md-12 ftco-animate">
<div class="cart-list">
<p><a href="adminOrder.php" class="btn btn-primary py-3 px-4">Refresh</a></p>
<table id="barang" class="table table-strped">
<thead class="thead-primary">
<tr class="text-center">
<th>No</th>
<th>Username</th>
<th>Date</th>
<th>Order</th>
<th>Quantity</th>
<th>Sub Total</th>
<th>Alamat</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM detail_pesanan dp
inner join pesanan p on p.idPesanan = dp.idPesanan
inner join konsumen k on k.idKonsumen = dp.idKonsumen
inner join Barang b on b.idBarang = dp.idBarang
order by p.idPesanan desc
";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$index = 1;
while ($row = mysqli_fetch_assoc($result)) {
$idPesanan = $row["idPesanan"];
$idKonsumen = $row["idKonsumen"];
$total = $row["jmlPesanan"] * $row["HargaBarang"];
echo "
<tr>
<td>" . $index++ . "</td>
<td>" . $row["NamaKonsumen"] . "</td>
<td>" . $row["TanggalJam"] . "</td>
<td>" . $row["NamaBarang"] . "</td>
<td>" . $row["jmlPesanan"] . "</td>
<td>" . $total . "</td>
<td>" . $row["AlamatKonsumen"] . "</td>";
if ($row["status"] == 'Process') {
echo "
<td> <a href='process/statusProcess.php?idPesanan=$idPesanan&idKonsumen=$idKonsumen' class='btn btn-danger py-3 px-4'> " . $row["status"] . "</a></td>";
} else if ($row["status"] == 'Done') {
echo "
<td> <a href='' class='btn btn-primary disabled py-3 px-4'> " . $row["status"] . "</a></td>";
} else if ($row["status"] == 'Accept') {
echo "
<td> <a href='process/statusAccept.php?idPesanan=$idPesanan&idKonsumen=$idKonsumen' class='btn btn-info py-3 px-4'> " . $row["status"] . "</a></td>";
}
echo "
</tr>
";
}
}
//Accept,Process,done
mysqli_close($con);
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
<?php include 'script.php' ?>
</body>
</html><file_sep><?php
include 'conSQL.php';
session_start();
$userid;
if (isset($_SESSION['idKonsumen'])) {
$userid = $_SESSION['idKonsumen'];
}
$semua_jml = $_POST['jml'];
$semua_id_barang = $_POST['id_brg'];
$semua_nama_barang = $_POST['nama_brg'];
$semua_harga_barang = $_POST['harga_brg'];
$semua_stok_barang = $_POST['stok'];
$error = "";
// var_dump($semua_jml);
// return;
$semua_jml_tidak_nol = [];
$semua_update_query = [];
// var_dump($semua_jml[]);
// return;
$query = "INSERT INTO detail_pesanan(idPesanan,idKonsumen,idBarang,jmlPesanan,status) VALUES ";
for ($i = 0; $i < count($semua_jml); $i++) {
for ($j = 0; $j < count($semua_jml[$i]); $j++) {
if ($semua_jml[$i][$j] > 0) {
$id_brg = $semua_id_barang[$i][$j];
$stok_brg = $semua_stok_barang[$i][$j];
$nama_brg = $semua_nama_barang[$i][$j];
$harga_brg = $semua_harga_barang[$i][$j];
$jumlah_brg = $semua_jml[$i][$j];
$data = (object)array(
"id_barang" => $id_brg,
"stok_barang" => $stok_brg,
"nama_barang" => $nama_brg,
"harga_barang" => $harga_brg,
"jumlah" => $jumlah_brg
);
// var_dump($data);
// return;
array_push($semua_jml_tidak_nol, $data);
//ketika memanggil idKonsumen yang di ambil itu idUsernya
if (is_numeric($userid) && is_numeric($id_brg) && is_numeric($jumlah_brg)) {
$query = $query . "(0,$userid,$id_brg,$jumlah_brg,0),";
}
if ($jumlah_brg > $stok_brg) {
$error = urldecode("ketersediaan $nama_brg tidak cukup");
return header("Location:../index.php?error=$error");
} else {
// header("Location: ../index.php?error=barang tidak cukup $nama_brg");
// echo "<script type='text/javascript'>alert('ketersediaan $nama_brg tidak cukup');</script>";
$hasil = $stok_brg - $jumlah_brg;
$update_query = "UPDATE barang SET JumlahBarang = '$hasil' where idBarang = $id_brg";
array_push($semua_update_query, $update_query);
}
}
}
}
if (empty($semua_jml_tidak_nol)) {
$error = urldecode("tidak ada barang yang dipesan");
return header("Location:../index.php?error=$error");
}
// var_dump($semua_jml_tidak_nol);
$query = substr($query, 0, -1);
var_dump($query);
if (mysqli_query($con, $query)) {
foreach ($semua_update_query as $update_query) {
mysqli_query($con, $update_query);
}
}
return header("Location:../pesan.php");
mysqli_close($con);<file_sep>$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$("nav").addClass("solid");
$(".navbar-brand").addClass("show");
} else {
$("nav").removeClass("solid");
$(".navbar-brand").removeClass("show");
}
});
});
<file_sep><?php
include 'process/conSQL.php';
include 'header.php';
if (!isset($_SESSION['idLogin'])) {
// header("Location: index.php");
}
// $katid = $_GET['kat'];
?>
<!-- END nav -->
<style type="text/css">
.float {
width: 100px;
height: 200px;
position: fixed;
margin-top: 100px;
top: 500px;
right: 50px;
z-index: 999;
}
</style>
<section id="home" class="hero home-bg">
<div class="text-center" style="padding-bottom: 400px;">
<img src="images/HomeLogo.png" width="350" style="padding-top: 300px;">
</div>
</section>
<section id="Interests" class="interests">
<div class="container">
<div class="row text-bright py-5">
<div class="col-6">
<h1 class="text-left text-bright">
<font size="7">Hallo ~</font>
</h1>
<p class="text-justify mb-5 text-space">
<font> Penggunaan plastik pada dasarnya dapat memberikan kemudahan dan kepraktisan,
sehingga masyarakat sangat sulit untuk menghindari penggunaan plastik tersebut. Akan tetapi dibalik kemudahan dan kepraktisan tersebut, plastik juga memberikan dampak buruk khususnya bagi lingkungan. Plastik sendiri mengandung bahan anorganik buatan yang tersusun dari bahan-bahan kimia yang cukup berbahaya bagi lingkungan dan sulit untuk diuraikan secara alami.
Penguraian membutuhkan waktu kurang lebih 80 tahun agar dapat terdegradasi secara sempurna.</font>
</p>
</div>
<div class="col-2">
</div>
<div class="col-4">
<h1 class="text-left text-bright">
<font size="7">Feeds</font>
</h1>
<img class="mr-2 mb-2" height="120" src="wareplanImages/857046_720.jpg">
<img class="mr-2 mb-2" height="120" src="wareplanImages/1529842242.jpg">
<img class="mr-2 mb-2" height="120" src="wareplanImages/DhJKcaCUYAAkHYv.jpg">
</div>
</div>
</div>
</section>
<section id="Player" class="player">
<iframe frameborder="0" width="100%" height="500" src="https://www.youtube.com/embed/EyzUazucAhU" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<div class="container">
<div class="row text-bright text-space">
<div class="col-12">
<p class="text-center my-5">
<font size="2"> Pernahkah kalian menyadari berapa jumlah plastik yang kita gunakan setiap hari? Mulai dari tas plastik, sedotan, kemasan makanan dan minuman, serta masih banyak produk berbahan plastik lainnya. Lalu kemanakah semua sampah plastik yang kita gunakan itu berakhir? </font>
</p>
</div>
</div>
</div>
</section>
<section id="About" class="about">
<div class="container">
<div class="row py-5">
<div class="col-4">
<h1 class="text-left">
<font size="7">Lihat di Peta</font>
</h1>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3951.5096165257796!2d112.6152643147269!3d-7.946170994276415!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x2e788275cf02d1b9%3A0xc4c7c33021b07764!2sJl.%20Semanggi%20No.30a%2C%20Jatimulyo%2C%20Kec.%20Lowokwaru%2C%20Kota%20Malang%2C%20Jawa%20Timur%2065141!5e0!3m2!1sen!2sid!4v1576047741372!5m2!1sen!2sid" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen=""></iframe>
</div>
<div class="col-5 ml-auto">
<h4 class="text-left">
<font size="7">About</font>
</h4>
<p class="text-justify text-space">
<font> WarePlan adalah sebuah usaha yang bergerak dibidang Green Technology dimana inovasi yang digunakan dengan
memanfaatkan sampah plastik dan mengolahnya menjadi tatakan gelas unik yang dapat digunakan sebagai hiasan dinding rumah.</font>
</p>
</div>
</div>
</div>
</section>
<?php
$message = '';
if (isset($_GET["error"])) {
$message = $_GET["error"];
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
<?php include 'footer.php' ?><file_sep><?php
include 'process/conSQL.php';
include 'header.php';
if (!isset($_SESSION['idLogin'])) {
// header("Location: index.php");
}
// $katid = $_GET['kat'];
?>
<!-- END nav -->
<style type="text/css">
.float {
width: 100px;
height: 200px;
position: fixed;
top: 15%;
right: 50px;
z-index: 999;
}
</style>
<form action="process/userPesan.php" method="POST" enctype="multipart/form-data">
<?php
$query = "SELECT * FROM kategori";
$result = mysqli_query($con, $query);
$k = 0;
while ($row = mysqli_fetch_assoc($result)) {
?>
<section class="ftco-section" id="<?= $row['idKategori'] ?>">
<div class="container">
<div class="row justify-content-center mb-3 pb-3">
<div class="col-md-12 heading-section text-center ftco-animate">
<span class="subheading">Our Products</span>
<h2 class="mb-4"><?= $row['Kategori'] ?></h2>
<div class="row">
<?php
$query2 = "SELECT * FROM barang where idKategori=" . $row['idKategori'] . "";
$result2 = mysqli_query($con, $query2);
$i = 0;
while ($row1 = mysqli_fetch_assoc($result2)) {
?>
<div class="col-md-6 col-lg-2 ftco-animate">
<div class="product">
<center><img width="130px" height="130px" src="process/imgBarang/<?= $row1['foto'] ?>" alt=""></center>
<div class="overlay"></div>
<div class="text py-3 pb-4 px-3 text-center">
<input type="hidden" name="id_brg[<?php echo $k; ?>][<?php echo $i; ?>]" value="<?php echo $row1['idBarang']; ?>" />
<input type="hidden" name="stok[<?php echo $k; ?>][<?php echo $i; ?>]" value="<?php echo $row1['JumlahBarang']; ?>" />
<input type="hidden" name="nama_brg[<?php echo $k; ?>][<?php echo $i; ?>]" value="<?php echo $row1['NamaBarang']; ?>" />
<input type="hidden" name="harga_brg[<?php echo $k; ?>][<?php echo $i; ?>]" value="<?php echo $row1['HargaBarang']; ?>" />
<h3><?= $row1['NamaBarang'] ?></h3>
<div class="text-left">
<div class="row mb-1">
<div class="col-4">
<p class="price text-dark text-small">Harga:</p>
</div>
<div class="col">
<p class="price text-dark text-small">Rp. <?= $row1['HargaBarang'] ?></p>
</div>
</div>
<div class="row mb-2">
<div class="col-4">
<p class="price text-dark text-small">Stok:</p>
</div>
<div class="col">
<p class="price text-dark text-small"><?= $row1['JumlahBarang'] ?> Item</p>
</div>
</div>
<div class="row">
<div class="col-4">
<p class="price text-dark text-small">Order:</p>
</div>
<div class="col">
<input name="jml[<?php echo $k; ?>][<?php echo $i; ?>]" class="form-control" style="height: 25px !important;" type="input" alt="Jumlah yg diinginkan" placeholder="0">
</div>
</div>
</div>
</div>
</div>
</div>
<?php $i++;
} ?>
</div>
</div>
</div>
<?php
if (isset($_SESSION['idLogin'])) {
?>
<div class="float"><button class="btn btn-primary" style="height: 40px; width: 120px" type="submit" name="submit">Order</button></div>
<?php } else { ?>
<div class="float"><a href="login.php" type="submit" name="submit">
<button class="btn btn-primary" style="height: 40px; width: 120px">Order</button>
</a></div>
<?php } ?>
</div>
</section>
<?php $k++;
} ?>
</form>
<?php
$message = '';
if (isset($_GET["error"])) {
$message = $_GET["error"];
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
<?php include 'footer.php' ?><file_sep><head>
<?php
// error_reporting(0);
include 'process/conSQL.php';
include 'header.php';
if (!isset($_SESSION['idLogin'])) {
header("Location: index.php");
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == 1) {
header("Location: adminHome.php");
}
}
?>
</head>
<section class="ftco-section ftco-cart">
<div class="container">
<div class="col-md-12 heading-section text-center ftco-animate">
<h2 class="mb-4">History</h2>
</div>
<div class="row">
<div class="col-md-12 ftco-animate">
<div class="cart-list">
<p><a href="history.php" class="btn btn-primary py-3 px-4">Refresh</a></p>
<table id="history" class="table table-strped">
<thead class="thead-primary">
<tr class="text-center">
<th>Date</th>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$login = $_SESSION['idLogin'];
$query = "SELECT * FROM detail_pesanan dp
inner join pesanan p on p.idPesanan = dp.idPesanan
inner join konsumen k on k.idKonsumen = dp.idKonsumen
inner join Barang b on b.idBarang = dp.idBarang
where idLogin = $login
order by p.TanggalJam desc
";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$index = 1;
while ($row = mysqli_fetch_assoc($result)) {
$idBarang = $row["idBarang"];
$total = $row["jmlPesanan"] * $row["HargaBarang"];
// $image = $row["foto"];
// $image1 = $row["foto_galeri"];
echo "
<tr>
<td >" . $row["TanggalJam"] . "</td>
<td>" . $row["NamaBarang"] . "</td>
<td>" . $row["HargaBarang"] . "</td>
<td>" . $row["jmlPesanan"] . "</td>
<td>" . $total . "</td>
<td>" . $row["status"] . "</td>
</tr>
";
}
}
mysqli_close($con);
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
<head>
<?php include 'footer.php' ?>
</head><file_sep><?php
// session_start();
include 'process/conSQL.php';
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>WarePlan</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<?php include 'stylesheet.php' ?>
</head>
<body>
<?php include 'navbar.php' ?><file_sep><?php
session_start();
include 'conSQL.php';
$idBarang = $_GET['idBarang'];
$query = "DELETE FROM barang WHERE idBarang = $idBarang";
if (mysqli_query($con, $query)) {
header("Location: ../adminProduct.php");
} else {
header("Location: ../adminProduct.php?error=Tidak berhasil");
}
<file_sep><head>
<?php include 'header.php' ?>
<style type="text/css">
.jalan{
position: relative;
height: 100px;
}
.logo{
position: absolute;
height: 50px;
left: -50px;
animation: geraklogo 5s infinite;
}
@keyframes geraklogo{
0% {left: 30%;}
100% {left: 60%}
}
</style>
</head>
<section class="ftco-section ftco-cart">
<div class="container">
<div class=" jalan logo">
<p>
<img style="animation: swing;" src="images/logoStore.PNG" width="200px"></p>
</div><br><br><br><br><br><br><br><br><br><br><br>
<h3><center>Pesanan sedang diproses</center></h3>
<center><p><a href="history.php" class="btn btn-primary">Check Your History</a></p></center>
</div>
</section>
<file_sep><?php
// Include DB connection file
include 'conSQL.php';
// // Get the form value
$NamaKonsumen = $_POST["NamaKonsumen"];
$NoTelpKonsumen = $_POST["NoTelpKonsumen"];
$EmailKonsumen = $_POST["EmailKonsumen"];
$AlamatKonsumen = $_POST["AlamatKonsumen"];
$Username = $_POST['Username'];
$Password = $_POST['<PASSWORD>'];
$cek = mysqli_num_rows(mysqli_query($con, "SELECT * FROM login WHERE Username='$Username'"));
if ($cek > 0) {
$error = urldecode("username sudah di gunakan, mohon ganti username lain");
header("Location:../register.php?pesan=$error");
} else {
$query1 = "INSERT into login (Username,Password,loginLevel) values ('$Username','$Password','2')"; //resep= user
if (mysqli_query($con, $query1)) {
$idLogin = "select idLogin from login where Username = '$Username'";
if (mysqli_query($con, $idLogin)) {
$result_select = mysqli_query($con, $idLogin);
$row = mysqli_fetch_assoc($result_select);
$idLogin = $row['idLogin'];
// echo $id_user;
$query = "INSERT INTO konsumen (idLogin, NamaKonsumen, NoTelpKonsumen, AlamatKonsumen, EmailKonsumen) VALUES ($idLogin,'$NamaKonsumen','$NoTelpKonsumen', '$AlamatKonsumen', '$EmailKonsumen')";
mysqli_query($con, $query);
header("Location:../registerSuccess.php");
}
} else {
$error = urldecode("Data tidak berhasil ditambahakan");
header("Location:../register.php?pesan=$error");
}
}
// close mysql connection
mysqli_close($con);
<file_sep><?php include 'header.php';
if (isset($_GET['pesan'])) {
$mess = "<p>{$_GET['pesan']}</p>";
} else {
$mess = "";
}
?>
<body class="login-bg">
<section class="ftco-section ftco-no-pb ftco-no-pt">
<div class="container">
<div class="row">
<div class="col-md-7 py-5 wrap-about ml-auto">
<form action="process/userRegister.php" method="POST" class="p-5 contact-form">
<h1 class="text-dark"><b>Register</b></h1>
<h6 style="color: red;"><?php echo $mess; ?></h6>
<div class="row mb-3">
<div class="col">
<input type="text" class="form-control" name="NamaKonsumen" placeholder="Your Name" required="">
</div>
<div class="col">
<input type="text" class="form-control" name="Username" placeholder="Your Username" required="">
</div>
</div>
<div class="form-group">
<input type="Email" class="form-control" name="EmailKonsumen" placeholder="Your Email" required="">
</div>
<div class="form-group">
<input type="<PASSWORD>" class="form-control" name="Password" placeholder="<PASSWORD>" required="">
</div>
<div class="form-group">
<input type="text" class="form-control" name="AlamatKonsumen" placeholder="Your Address" required="">
</div>
<div class="form-group">
<input type="number" class="form-control" name="NoTelpKonsumen" placeholder="Your Phone Number" required="">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit" name="submit">Register</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php include 'script.php' ?>
</body>
</html><file_sep><?php
$dbUrl = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "wareplan";
$con = mysqli_connect($dbUrl,$dbUser,$dbPass,$dbName);
#check username dan password di database
if(!$con) {
die("Connection failed : " .mysqli_connect_error());
}
<file_sep><head>
<?php
include 'process/conSQL.php';
session_start();
if (!isset($_SESSION['idLogin'])) {
header("Location: index.php");
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == 2) {
header("Location: index.php");
}
}
$idBarang = $_GET['id'];
include 'adminHeader.php' ?>
</head>
</head>
<section class="ftco-section ftco-no-pb ftco-no-pt bg-white">
<div class="container">
<div class="row">
<div class="col-md-2 py-5 wrap-about pb-md-5 ftco-animate"></div>
<div class="col-md-8 py-5 wrap-about pb-md-5 ftco-animate">
<div class="heading-section-bold mb-4 mt-md-5">
<div class="ml-md-0">
</div>
</div>
<div class="pb-md-5">
<?php
$query = "SELECT * FROM Barang WHERE idBarang = '$idBarang'";
$result = mysqli_query($con, $query);
$item = mysqli_fetch_assoc($result);
?>
<form action="process/updateBarang.php" method="POST" enctype="multipart/form-data" class="bg-white p-5 contact-form">
<h1 class="text-dark"><b>Update Product</b></h1>
<input type="hidden" name="id_Barang" value="<?= $idBarang ?>">
<div class="form-group">
<label>Image</label>
<input type="hidden" name="id_Barang" value="<?php echo $idBarang ?>">
<input type="file" class="form-control" name="file" id="file" value="" placeholder="" required="">
</div>
<div class="form-group">
<label>Product Name</label>
<input type="Text" name="NamaBarang" id="NamaBarang" value="<?php echo $item["NamaBarang"] ?>" class="form-control" placeholder="" required="">
</div>
<div class="form-group">
<label>Category</label>
<div>
<select class="form-control" name="idKategori" id="idKategori" required>
<option disabled selected>Pilih</option>
<?php
$id = $_GET["idcat"];
$query = "SELECT * FROM kategori WHERE idKategori = $id";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?= $row['idKategori'] ?>" selected><?= $row['Kategori'] ?></option>
<?php } ?>
<?php
$query = "SELECT * FROM kategori";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?= $row['idKategori'] ?>"><?= $row['Kategori'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Quantity</label>
<input type="number" name="JumlahBarang" id="JumlahBarang" value="<?php echo $item["JumlahBarang"] ?>" class="form-control" placeholder="" required="">
</div>
<div class="form-group">
<label>Price</label>
<input type="number" name="HargaBarang" id="HargaBarang" value="<?php echo $item["HargaBarang"] ?>" class="form-control" placeholder="" required="">
</div>
<div class="form-group">
<a href="adminProduct.php" class="btn btn-secondary">Cancel</a>
<button class="btn btn-primary" type="submit" name="submit" value="Update">Update Product</button>
</div>
</form>
</div>
</div>
<div class="col-md-2 py-5 wrap-about pb-md-5 ftco-animate"></div>
</div>
</div>
</section>
<?php include 'script.php' ?>
</body>
</html><file_sep><?php
include 'header.php';
if (isset($_GET['pesan'])) {
$mess = "<p>{$_GET['pesan']}</p>";
} else {
$mess = "";
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == "user") {
header("Location: index.php");
}
}
?>
<body class="login-bg">
<section class="ftco-section ftco-no-pb ftco-no-pt">
<div class="container">
<div class="row">
<div class="col-md-7 py-5 wrap-about pb-md-5 ml-auto">
<div class="pb-md-5">
<form action="process/userLogin.php" class="p-5 contact-form" method="POST">
<h1 class="text-dark"><b>Login</b></h1>
<div class="form-group">
<input type="text" class="form-control" name="Username" placeholder="Your Username">
</div>
<div class="form-group">
<input type="<PASSWORD>" class="form-control" name="Password" placeholder="<PASSWORD>">
</div>
Don't have an account?<a href="register.php" class="text-dark"> Register</a></br>
<div class="form-group">
</br>
<?php echo $mess; ?>
<button class="btn btn-primary" type="submit" name="submit">Login</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<?php include 'script.php' ?>
</body>
</html><file_sep><?php
session_start();
include 'conSQL.php';
$idBarang = $_GET['idBarang'];
$query2 = "Select * from detail_pesanan WHERE idBarang = $idBarang AND status = '0'";
$query = "DELETE FROM detail_pesanan WHERE idBarang = $idBarang";
$result2 = mysqli_query($con, $query2);
$jumlah_barang_pesanan = 0;
if (mysqli_num_rows($result2) > 0) {
while ($row = mysqli_fetch_assoc($result2)) {
$jumlah_barang_pesanan += $row["jmlPesanan"];
echo "tes";
}
if (mysqli_query($con, $query)) {
$update_query = "UPDATE barang SET JumlahBarang = JumlahBarang + $jumlah_barang_pesanan where idBarang = $idBarang ";
if (mysqli_query($con, $update_query)) {
return header("Location: ../pesan.php");
}
// $hasil = $stokBrg - $jumlahBrg;
// $query2 = "UPDATE barang SET JumlahBarang = '$hasil' where idBarang = $idBarang ";
} else {
return header("Location: ../pesan.php?error=Tidak berhasil dihapus");
}
}
<file_sep><?php
session_start();
include 'conSQL.php';
$error = '';
if (isset($_POST["submit"])) {
if (!empty($_POST["idLogin"]) || !empty($_POST["Password"]) || !empty($_POST["Username"])) {
# Get username and password from user
$Username = $_POST["Username"];
$Password = $_POST["Password"];
# Write MySql Query
$query = "SELECT * FROM login l
left join konsumen k on k.idLogin = l.idLogin
WHERE l.Username='$Username' AND l.Password='$<PASSWORD>'";
# Get the query result
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
// var_dump($row);
// return;
$loginLevel = $row["loginLevel"];
if ($loginLevel == 1) {
# code...
$_SESSION["idLogin"] = 1;
$_SESSION["Username"] = $Username;
$_SESSION["loginLevel"] = $loginLevel;
header("Location: ../adminHome.php");
} else if ($loginLevel == 2) {
$_SESSION["idLogin"] = $row['idLogin'];
$_SESSION["idKonsumen"] = $row['idKonsumen'];
$_SESSION["Username"] = $Username;
$_SESSION["loginLevel"] = $loginLevel;
header("Location: ../index.php");
}
} else {
$error = urlencode("Username atau password salah!");
header("Location: ../login.php?pesan=$error");
}
# Close connection to database
mysqli_close($con);
} else {
$error = urlencode("Username atau password kosong!");
header("Location: ../login.php?pesan=$error");
}
}
<file_sep><?php
session_start();
$_SESSION["idLogin"] = $row['idLogin'];
// $_SESSION["username"] = $Username;
// $_SESSION["level"] = $level;
unset($_SESSION["idLogin"]);
session_unset();
session_destroy();
header("location:../index.php")
?><file_sep>-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Dec 02, 2019 at 12:57 PM
-- Server version: 10.1.16-MariaDB
-- PHP Version: 5.6.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `storeid`
--
-- --------------------------------------------------------
--
-- Table structure for table `barang`
--
CREATE TABLE `barang` (
`idBarang` int(11) NOT NULL,
`NamaBarang` varchar(255) NOT NULL,
`JumlahBarang` int(11) NOT NULL,
`HargaBarang` int(11) NOT NULL,
`idKategori` int(11) NOT NULL,
`supplier` varchar(255) NOT NULL,
`foto` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `barang`
--
INSERT INTO `barang` (`idBarang`, `NamaBarang`, `JumlahBarang`, `HargaBarang`, `idKategori`, `supplier`, `foto`) VALUES
(14, 'Better', 100, 1500, 1, 'Billa', 'better.jpg'),
(15, 'Es Teh', 36, 2000, 3, 'Anggota USMA', 'esteh.jpg'),
(17, 'Seragam HMTI', 17, 150000, 4, 'bila', 'hmti.jpg'),
(19, 'Leo', 11, 3000, 1, 'sardo', 'leo.jpg'),
(20, 'COCA COLA 380ML', 100, 4500, 3, 'PT. Coca Cola', 'cocacola380ml.jpg'),
(21, 'COCA COLA 250ML', 100, 3500, 3, 'PT. Coca Cola', 'cocacola250ml.png'),
(22, 'PILUS', 100, 500, 1, 'PERSADA', 'pilus.jpg'),
(23, 'CHOCOLATOS', 100, 1000, 1, 'PERSADA', 'chocolatos.jpg'),
(24, '<NAME>', 100, 500, 1, 'PERSADA', 'nabati.jpg'),
(25, '<NAME>', 100, 500, 1, 'PERSADA', 'selimut.jpg'),
(26, 'MAKARONI', 98, 500, 1, 'FITA', 'makaroni.jpg'),
(27, 'TANGO', 100, 1000, 1, 'PERSADA', 'tango.jpg'),
(28, '<NAME>', 100, 1000, 1, 'PERSADA', 'rosta.jpg'),
(29, '<NAME>', 100, 1000, 1, 'PERSADA', 'krisbee.jpg'),
(30, 'LEO', 100, 1000, 1, 'PERSADA', 'leo.jpg'),
(31, '<NAME>', 100, 1000, 1, 'PERSADA', 'tictac.jpg'),
(32, 'JETZ', 100, 1000, 1, 'PERSADA', 'jetz.jpg'),
(33, 'BENGBENG', 100, 1500, 1, 'PERSADA', 'bengbeng.jpg'),
(34, 'WALLENS', 100, 1500, 1, 'PERSADA', 'wallens.jpg'),
(35, 'FULLO', 100, 2000, 1, 'PERSADA', 'fullo.jpg'),
(36, '<NAME>', 100, 2000, 1, 'PERSADA', 'nabatorolls.jpg'),
(37, '<NAME>', 100, 2000, 1, 'PERSADA', 'sarigandum.jpg'),
(38, '<NAME>', 100, 2500, 1, 'PERSADA', 'nabati50.jpg'),
(39, '<NAME>', 100, 5500, 3, 'PERSADA', 'pulpy.png'),
(40, 'NUTRIFORCE', 100, 2500, 3, 'PERSADA', 'nutriforce.png'),
(41, '<NAME>', 100, 3000, 3, 'PERSADA', 'tehpucuk.jpg'),
(42, 'MINERAL', 99, 2500, 3, 'PERSADA', 'mineral.jpg'),
(43, 'FANTA 250ML', 100, 3500, 3, 'PT. Coca Cola', 'fanta250.jpg'),
(44, 'NUTRIBOOST', 100, 6000, 3, 'PERSADA', 'nutriboost.jpg'),
(45, 'KOPI', 100, 3000, 3, 'PERSADA', 'kopi.jpg'),
(46, '<NAME>', 0, 3000, 2, 'FROZEN FOOD', 'sosisgoreng.png'),
(47, '<NAME>', 99, 3000, 2, '<NAME>', 'krupuksambal.jpg'),
(48, '<NAME>', 100, 3000, 2, 'PASAR', 'tahukres.jpg'),
(49, 'TELA-TELA', 100, 3000, 2, 'PASAR', 'telatela.jpg'),
(50, '<NAME>', 100, 5000, 2, 'PERSADA', 'indomie.jpg'),
(51, 'POP MIE', 100, 5000, 2, 'PERSADA', 'pop.jpg'),
(52, '<NAME>', 100, 6000, 2, 'PERSADA', 'sarimieduo.jpg'),
(53, '<NAME>', 100, 190000, 4, 'DIVISI TENDER', 'almet.png'),
(54, '<NAME>', 100, 150000, 4, 'DIVISI TENDER', 'hma.jpg'),
(55, '<NAME>', 100, 150000, 4, 'DIVISI TENDER', 'hme.png'),
(56, '<NAME>', 100, 150000, 4, 'DIVISI TENDER', 'hmm.jpg'),
(57, '<NAME>', 100, 150000, 4, 'DIVISI TENDER', 'hms.png'),
(58, 'HOODIE POLINEMA WHITE', 100, 150000, 4, 'DIVISI TENDER', 'jaketPutih.PNG'),
(59, 'HOODIE POLINEMA NAVY', 98, 200000, 4, 'DIVISI TENDER', 'jaketBiru.PNG'),
(60, 'rice bowl', 10, 10000, 2, 'sinta', '2019-08-30 09.39.20 1.jpg');
-- --------------------------------------------------------
--
-- Table structure for table `detail_pesanan`
--
CREATE TABLE `detail_pesanan` (
`idPesanan` int(11) NOT NULL,
`idKonsumen` int(11) NOT NULL,
`idBarang` int(11) NOT NULL,
`jmlPesanan` int(11) NOT NULL,
`status` varchar(255) NOT NULL,
`deliverto` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `detail_pesanan`
--
INSERT INTO `detail_pesanan` (`idPesanan`, `idKonsumen`, `idBarang`, `jmlPesanan`, `status`, `deliverto`) VALUES
(16, 3, 11, 5, 'Done', 'Sekret Rispol'),
(18, 7, 14, 1, 'Done', 'Sekret Rispol'),
(18, 7, 15, 1, 'Done', 'Sekret Rispol'),
(18, 7, 18, 1, 'Done', 'Sekret Rispol'),
(19, 9, 15, 1, 'Done', 'Sekret Kompen'),
(19, 9, 19, 3, 'Done', 'Sekret Kompen'),
(20, 9, 14, 2, 'Done', 'Sekret Usma'),
(20, 9, 19, 1, 'Done', 'Sekret Usma'),
(20, 9, 19, 2, 'Done', 'Sekret Usma'),
(21, 9, 15, 2, 'Done', 'Sekret Usma'),
(22, 9, 17, 1, 'Done', 'Sekret HMTI'),
(23, 3, 19, 2, 'Done', 'Sekret Kompen'),
(24, 10, 15, 2, 'Done', 'Sekret Usma'),
(24, 10, 18, 2, 'Done', 'Sekret Usma'),
(25, 5, 14, 5, 'Done', 'Sekret Usma'),
(26, 5, 18, 2, 'Done', 'Sekret Usma'),
(27, 5, 15, 4, 'Done', 'Sekret PP'),
(28, 9, 14, 1, 'Done', 'Sekret SENI'),
(28, 9, 15, 2, 'Done', 'Sekret SENI'),
(28, 9, 19, 1, 'Done', 'Sekret SENI'),
(29, 9, 17, 1, 'Process', 'Sekret HMTI'),
(30, 5, 59, 2, 'Done', 'Sekret HMM'),
(31, 11, 46, 100, 'Done', 'Sekret HMTK'),
(32, 12, 26, 2, 'Done', 'Sekret PASTI'),
(32, 12, 42, 1, 'Done', 'Sekret PASTI'),
(32, 12, 47, 1, 'Done', 'Sekret PASTI');
-- --------------------------------------------------------
--
-- Table structure for table `kategori`
--
CREATE TABLE `kategori` (
`idKategori` int(11) NOT NULL,
`Kategori` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `kategori`
--
INSERT INTO `kategori` (`idKategori`, `Kategori`) VALUES
(1, 'Snack'),
(2, 'Meals'),
(3, 'Drinks'),
(4, 'Konveksi');
-- --------------------------------------------------------
--
-- Table structure for table `konsumen`
--
CREATE TABLE `konsumen` (
`idKonsumen` int(10) NOT NULL,
`NamaKonsumen` varchar(255) NOT NULL,
`NoTelpKonsumen` int(25) NOT NULL,
`EmailKonsumen` varchar(255) NOT NULL,
`idLogin` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `konsumen`
--
INSERT INTO `konsumen` (`idKonsumen`, `NamaKonsumen`, `NoTelpKonsumen`, `EmailKonsumen`, `idLogin`) VALUES
(1, 'milla', 897645532, '<EMAIL>', 2),
(2, 'afi', 887802, '<EMAIL>', 3),
(3, 'bila', 889083, '<EMAIL>', 4),
(4, 'dini', 86790885, '<EMAIL>', 5),
(5, 'fita', 887809, '<EMAIL>', 6),
(6, 'linda', 998730, '<EMAIL>', 7),
(7, 'iren', 98222, '<EMAIL>', 8),
(8, 'serli', 8890223, '<EMAIL>', 9),
(9, 'itik', 0, '<EMAIL>', 10),
(10, 'david', 880093, '<EMAIL>', 11),
(11, 'Ahaha', 2147483647, '<EMAIL>', 12),
(12, 'sinta', 8878098, '<EMAIL>', 13);
-- --------------------------------------------------------
--
-- Table structure for table `login`
--
CREATE TABLE `login` (
`idLogin` int(10) NOT NULL,
`Username` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`loginLevel` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `login`
--
INSERT INTO `login` (`idLogin`, `Username`, `Password`, `loginLevel`) VALUES
(1, 'admin', '<PASSWORD>', 1),
(2, 'milla', 'milla', 2),
(3, 'afi', 'afi', 2),
(4, 'bila', 'bila', 2),
(5, 'dini', 'dini', 2),
(6, 'fita', 'fita', 2),
(7, 'linda', 'linda', 2),
(8, 'iren', 'iren', 2),
(9, 'serli', 'serli', 2),
(10, 'itik', 'itik', 2),
(11, 'david', 'david', 2),
(12, 'ahaha', 'ahaha', 2),
(13, 'sinta', 'sinta', 2);
-- --------------------------------------------------------
--
-- Table structure for table `pesanan`
--
CREATE TABLE `pesanan` (
`idPesanan` int(11) NOT NULL,
`TanggalJam` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `pesanan`
--
INSERT INTO `pesanan` (`idPesanan`, `TanggalJam`) VALUES
(3, '2019-11-18 11:00:00'),
(4, '2019-11-18 20:36:03'),
(5, '2019-11-18 20:38:12'),
(6, '2019-11-18 20:55:45'),
(7, '2019-11-18 20:57:38'),
(8, '2019-11-18 21:02:36'),
(9, '2019-11-18 21:04:14'),
(10, '2019-11-18 21:12:04'),
(11, '2019-11-18 21:14:00'),
(14, '2019-11-19 15:07:22'),
(15, '2019-11-19 15:08:22'),
(16, '2019-11-19 15:09:10'),
(17, '2019-11-19 15:55:19'),
(18, '2019-11-20 13:47:31'),
(19, '2019-11-20 17:16:57'),
(20, '2019-11-20 17:25:49'),
(21, '2019-11-20 17:26:31'),
(22, '2019-11-20 17:53:45'),
(23, '2019-11-20 18:08:51'),
(24, '2019-11-24 18:44:39'),
(25, '2019-11-25 00:15:29'),
(26, '2019-11-25 00:17:23'),
(27, '2019-11-25 00:20:19'),
(28, '2019-11-25 00:22:24'),
(29, '2019-11-25 00:25:55'),
(30, '2019-11-25 14:15:12'),
(31, '2019-11-29 16:17:14'),
(32, '2019-12-02 11:19:55');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `barang`
--
ALTER TABLE `barang`
ADD PRIMARY KEY (`idBarang`);
--
-- Indexes for table `detail_pesanan`
--
ALTER TABLE `detail_pesanan`
ADD PRIMARY KEY (`idPesanan`,`idKonsumen`,`idBarang`,`jmlPesanan`);
--
-- Indexes for table `kategori`
--
ALTER TABLE `kategori`
ADD PRIMARY KEY (`idKategori`);
--
-- Indexes for table `konsumen`
--
ALTER TABLE `konsumen`
ADD PRIMARY KEY (`idKonsumen`),
ADD KEY `fk_login_konsumen` (`idLogin`);
--
-- Indexes for table `login`
--
ALTER TABLE `login`
ADD PRIMARY KEY (`idLogin`);
--
-- Indexes for table `pesanan`
--
ALTER TABLE `pesanan`
ADD PRIMARY KEY (`idPesanan`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `barang`
--
ALTER TABLE `barang`
MODIFY `idBarang` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=61;
--
-- AUTO_INCREMENT for table `kategori`
--
ALTER TABLE `kategori`
MODIFY `idKategori` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `konsumen`
--
ALTER TABLE `konsumen`
MODIFY `idKonsumen` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `login`
--
ALTER TABLE `login`
MODIFY `idLogin` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT for table `pesanan`
--
ALTER TABLE `pesanan`
MODIFY `idPesanan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `konsumen`
--
ALTER TABLE `konsumen`
ADD CONSTRAINT `fk_login_konsumen` FOREIGN KEY (`idLogin`) REFERENCES `login` (`idLogin`);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
include 'process/conSQL.php';
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == "user") {
header("Location: index.php");
}
}
include 'header.php';
?>
<body class="regisSuccess-bg">
<section class="ftco-section ftco-no-pb ftco-no-pt">
<div class="container">
<div class="row">
<div class="col-md-7 py-5 wrap-about pb-md-5 ml-auto">
<div class="pb-md-5">
<form action="process/userLogin.php" class="p-5 contact-form" method="POST">
<h1 class="text-dark"><b>Success</b></h1>
<h4>register is successed</h4>
<div class="form-group">
<a href="login.php" class="btn btn-primary">Login</a>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</body><file_sep><head>
<?php
include 'process/conSQL.php';
session_start();
if (!isset($_SESSION['idLogin'])) {
header("Location: index.php");
}
if (isset($_SESSION['loginLevel'])) {
if ($_SESSION['loginLevel'] == 2) {
header("Location: index.php");
}
}
include 'adminHeader.php' ?>
</head>
<section class="ftco-section ftco-no-pb ftco-no-pt bg-white">
<div class="container">
<div class="row">
<div class="col-md-2 py-5 wrap-about pb-md-5 ftco-animate"></div>
<div class="col-md-8 py-5 wrap-about pb-md-5 ftco-animate">
<div class="heading-section-bold mb-4 mt-md-5">
<div class="ml-md-0">
</div>
</div>
<?php
$message = '';
if (isset($_GET["error"])) {
$message = $_GET["error"];
echo "
<p style='color:red; font-style:italic'>$message</p>
";
}
?>
<div class="pb-md-5">
<form action="process/addBarang.php" method="POST" enctype="multipart/form-data">
<h1 class="text-dark"><b>Add Product</b></h1>
<div class="form-group">
<label>Image <a style='color:red;'>*ukuran foto 1x1</a></label>
<input type="file" name="file" id="file" class="form-control" placeholder="" required>
</div>
<div class="form-group">
<label>Product Name</label>
<input type="Text" class="form-control" placeholder="" name="NamaBarang" id="NamaBarang" required>
</div>
<div class="form-group">
<label>Kategori</label>
<div class=".col-auto .mr-auto">
<select class="form-control" name="idKategori" id="idKategori" required>
<option disabled selected>Pilih</option>
<?php
$query = "SELECT * FROM kategori";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?= $row['idKategori'] ?>">
<?= $row['Kategori'] ?>
</option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Quantity</label>
<input type="number" class="form-control" placeholder="" name="JumlahBarang" id="JumlahBarang" required>
</div>
<div class="form-group">
<label>Price</label>
<input type="number" class="form-control" placeholder="" name="HargaBarang" id="HargaBarang" required>
</div>
<div class="form-group">
<a href="adminProduct.php" class="btn btn-secondary">Cancel</a>
<button class="btn btn-primary" type="submit" name="submit">Add Product</button>
</div>
</form>
</div>
</div>
<div class="col-md-2 py-5 wrap-about pb-md-5 ftco-animate"></div>
</div>
</div>
<script>
function clearForm() {
$('NamaBarang').val('');
$('JumlahBarang').val('');
$('HargaBarang').val('');
$('idKategori').val('');
$('supplier').val('');
}
</script>
</section>
<head>
<?php include 'footer.php' ?>
</head><file_sep><?php
session_start();
include 'conSQL.php';
$idPesanan = $_GET['idPesanan'];
$idKonsumen = $_GET['idKonsumen'];
$query = "UPDATE detail_pesanan SET status = 'Process' where idPesanan='$idPesanan'AND idKonsumen='$idKonsumen'";
if (mysqli_query($con, $query)) {
header("Location: ../adminOrder.php");
} else {
header("Location: ../adminOrder.php?error=Tidak berhasil");
}
|
70c4dbd27cc7fb3d745a75e1abad07086b7ed5be
|
[
"JavaScript",
"SQL",
"PHP"
] | 27 |
PHP
|
afifahmn/Wareplan
|
5bf8a63df78a8b598c2ae1473661dece28366882
|
627fcef7a5b15f47d6ac9405b14001a9d5ff33d3
|
refs/heads/master
|
<file_sep>/*
* servoControll.h
*
* Created on: 19 déc. 2019
* Author: Antoine
*/
#ifndef INC_SERVOCONTROL_H_
#define INC_SERVOCONTROL_H_
#include <stdint.h>
#include "HerkulexServo.h"
typedef enum _articulation
{
chevilleDroite,
genouDroit,
hancheDroite,
bassinDroit,
bassinGauche,
hancheGauche,
genouGauche,
chevilleGauche
} Articulation;
typedef enum _walkPhase
{
WalkPhase_None,
WalkPhase_One,
WalkPhase_Two,
WalkPhase_Three,
WalkPhase_Four,
WalkPhase_Five,
WalkPhase_Six
} WalkPhase;
void walk(HerkulexServo **articulations, uint8_t numberOfStep);
void initialisePosition(HerkulexServo **articulations);
#endif /* INC_SERVOCONTROL_H_ */
<file_sep>/*
* servoControl.c
*
* Created on: 19 déc. 2019
* Author: Antoine
*/
#include "servoControl.h"
void walk(HerkulexServo **articulations, uint8_t numberOfStep)
{
uint16_t walkTime = 1120;
WalkPhase phase = WalkPhase_None;
uint8_t step = 0;
while (step < numberOfStep)
{
switch (phase)
{
case WalkPhase_None:
if (step == 0)
{
phase = WalkPhase_One;
}
else
{
phase = WalkPhase_Three;
}
break;
case WalkPhase_One:
prepareSynchronizedMove((**(articulations + 0)).m_bus, walkTime);
setPosition(*(articulations + bassinDroit), 22.5f, 0, HerkulexLed_Blue);
setPosition(*(articulations + bassinGauche), 22.5f, 0, HerkulexLed_Blue);
setPosition(*(articulations + chevilleDroite), -20.0f, 0, HerkulexLed_Blue);
setPosition(*(articulations + chevilleGauche), -20.0f, 0, HerkulexLed_Blue);
// setTorqueOff(*(articulations + chevilleGauche));
executeMove((**(articulations + 0)).m_bus);
setLedColor(*(articulations + genouGauche), HerkulexLed_Blue);
setLedColor(*(articulations + genouDroit), HerkulexLed_Blue);
setLedColor(*(articulations + hancheGauche), HerkulexLed_Blue);
setLedColor(*(articulations + hancheDroite), HerkulexLed_Blue);
HAL_Delay(walkTime);
setTorqueOn(*(articulations + chevilleGauche));
phase = WalkPhase_Two;
break;
case WalkPhase_Two:
prepareSynchronizedMove((**(articulations + 0)).m_bus, walkTime);
setPosition(*(articulations + hancheGauche), 30.0f, 0, HerkulexLed_Cyan);
setPosition(*(articulations + genouGauche), -30.0f, 0, HerkulexLed_Cyan);
executeMove((**(articulations + 0)).m_bus);
setLedColor(*(articulations + bassinDroit), HerkulexLed_Cyan);
setLedColor(*(articulations + bassinGauche), HerkulexLed_Cyan);
setLedColor(*(articulations + chevilleDroite), HerkulexLed_Cyan);
setLedColor(*(articulations + chevilleGauche), HerkulexLed_Cyan);
setLedColor(*(articulations + genouDroit), HerkulexLed_Cyan);
setLedColor(*(articulations + hancheDroite), HerkulexLed_Cyan);
HAL_Delay(walkTime);
phase = WalkPhase_Three;
break;
case WalkPhase_Three:
prepareSynchronizedMove((**(articulations + 0)).m_bus, walkTime);
setPosition(*(articulations + bassinDroit), -22.5f, 0, HerkulexLed_Purple);
setPosition(*(articulations + bassinGauche), -22.5f, 0, HerkulexLed_Purple);
// setTorqueOff(*(articulations + chevilleDroite));
setPosition(*(articulations + chevilleGauche), 20.0f, 0, HerkulexLed_Purple);
setPosition(*(articulations + chevilleDroite), 20.0f, 0, HerkulexLed_Purple);
executeMove((**(articulations + 0)).m_bus);
setLedColor(*(articulations + genouDroit), HerkulexLed_Purple);
setLedColor(*(articulations + genouGauche), HerkulexLed_Purple);
setLedColor(*(articulations + hancheDroite), HerkulexLed_Purple);
setLedColor(*(articulations + hancheGauche), HerkulexLed_Purple);
HAL_Delay(walkTime);
setTorqueOn(*(articulations + chevilleDroite));
phase = WalkPhase_Four;
break;
case WalkPhase_Four:
prepareSynchronizedMove((**(articulations + 0)).m_bus, walkTime);
setPosition(*(articulations + genouDroit), 27.5f, 0, HerkulexLed_White);
setPosition(*(articulations + genouGauche), 0, 0, HerkulexLed_White);
setPosition(*(articulations + hancheDroite), -30.0f, 0, HerkulexLed_White);
setPosition(*(articulations + hancheGauche), 0, 0, HerkulexLed_White);
executeMove((**(articulations + 0)).m_bus);
setLedColor(*(articulations + bassinDroit), HerkulexLed_White);
setLedColor(*(articulations + bassinGauche), HerkulexLed_White);
setLedColor(*(articulations + chevilleDroite), HerkulexLed_White);
setLedColor(*(articulations + chevilleGauche), HerkulexLed_White);
HAL_Delay(walkTime);
phase = WalkPhase_Five;
break;
case WalkPhase_Five:
prepareSynchronizedMove((**(articulations + 0)).m_bus, walkTime);
setPosition(*(articulations + bassinDroit), 22.5, 0, HerkulexLed_Green);
setPosition(*(articulations + bassinGauche), 22.5, 0, HerkulexLed_Green);
setPosition(*(articulations + chevilleDroite), -20.0f, 0, HerkulexLed_Green);
// setTorqueOff(*(articulations + chevilleGauche));
setPosition(*(articulations + chevilleGauche), -20.0f, 0, HerkulexLed_Purple);
executeMove((**(articulations + 0)).m_bus);
setLedColor(*(articulations + hancheDroite), HerkulexLed_Green);
setLedColor(*(articulations + genouGauche), HerkulexLed_Green);
setLedColor(*(articulations + genouDroit), HerkulexLed_Green);
setLedColor(*(articulations + hancheGauche), HerkulexLed_Green);
HAL_Delay(walkTime);
setTorqueOn(*(articulations + chevilleGauche));
phase = WalkPhase_Six;
break;
case WalkPhase_Six:
prepareSynchronizedMove((**(articulations + 0)).m_bus, walkTime);
setPosition(*(articulations + genouDroit), 0, 0, HerkulexLed_Yellow);
setPosition(*(articulations + genouGauche), -30.0f, 0, HerkulexLed_Yellow);
setPosition(*(articulations + hancheDroite), 0, 0, HerkulexLed_Yellow);
setPosition(*(articulations + hancheGauche), 30.0f, 0, HerkulexLed_Yellow);
executeMove((**(articulations + 0)).m_bus);
setLedColor(*(articulations + bassinDroit), HerkulexLed_Yellow);
setLedColor(*(articulations + bassinGauche), HerkulexLed_Yellow);
setLedColor(*(articulations + chevilleDroite), HerkulexLed_Yellow);
setLedColor(*(articulations + chevilleGauche), HerkulexLed_Yellow);
HAL_Delay(walkTime);
phase = WalkPhase_None;
step++;
break;
default:
break;
}
}
initialisePosition(articulations);
}
void initialisePosition(HerkulexServo **articulations)
{
HerkulexServoBus *bus = (**(articulations)).m_bus;
prepareSynchronizedMove(bus, 1120);
setPosition(*(articulations + bassinDroit), 0, 0, HerkulexLed_Green);
setPosition(*(articulations + bassinGauche), 0, 0, HerkulexLed_Green);
setPosition(*(articulations + chevilleDroite), 0, 0, HerkulexLed_Green);
setPosition(*(articulations + chevilleGauche), 0, 0, HerkulexLed_Green);
setPosition(*(articulations + hancheDroite), 0, 0, HerkulexLed_Green);
setPosition(*(articulations + hancheGauche), 0, 0, HerkulexLed_Green);
setPosition(*(articulations + genouDroit), 0, 0, HerkulexLed_Green);
setPosition(*(articulations + genouGauche), 0, 0, HerkulexLed_Green);
executeMove(bus);
HAL_Delay(100);
}
<file_sep>/*
* HerkluexServo.c
*
* Created on: 11 déc. 2019
* Author: Antoine
*/
#include "HerkulexServo.h"
/**
* @brief Initialize the servo bus structure
* @param HUART_Handler : A pointer to the UART handler used to communicate with the servomotors
* @retval Initialized ServoBus structure
*/
HerkulexServoBus *initializeServoBus(UART_HandleTypeDef *HUART_Handler)
{
HerkulexServoBus *servoBus = (HerkulexServoBus *)malloc(sizeof(HerkulexServoBus));
if (servoBus != NULL)
{
servoBus->m_serial = HUART_Handler;
for (uint8_t i = 0; i < HERKULEX_PACKET_RX_MAX_DATA; i++)
{
servoBus->m_rx_buffer[i] = 0;
}
servoBus->m_last_serial = 0;
servoBus->m_rx_packet.size = 0x00;
servoBus->m_rx_packet.id = 0x00;
servoBus->m_rx_packet.cmd = HerkulexCommand_None;
servoBus->m_rx_packet.checksum1 = 0x00;
servoBus->m_rx_packet.checksum2 = 0x00;
for (uint8_t i = 0; i < HERKULEX_PACKET_RX_MAX_DATA; i++)
{
*(servoBus->m_rx_packet.data + i) = 0;
}
servoBus->m_rx_packet.status_error = HerkulexStatusError_None;
servoBus->m_rx_packet.status_detail = HerkulexStatusDetail_None;
servoBus->m_rx_packet.error = HerkulexPacketError_None;
servoBus->m_rx_packet_ready = 0;
for (uint8_t i = 0; i < HERKULEX_SERIAL_TX_BUFFER; i++)
{
*(servoBus->m_tx_buffer + i) = 0;
}
servoBus->m_move_tags = 0;
servoBus->m_schedule_state = HerkulexScheduleState_None;
}
return servoBus;
}
/**
@brief Construct and end a specific UART packet
@param self : The ServoBus used to communicate
@param id : Servomotor ID
@param cmd : enum of the command to send to the servo
@param pData : array of optional data to send
@param dataLen : Lenght of the pData array
@retval None
*/
void sendPacket(HerkulexServoBus *self, uint8_t id, HerkulexCommand cmd, uint8_t *pData, uint8_t dataLen)
{
uint8_t checksum1;
uint8_t checksum2;
uint8_t packetSize = 7 + dataLen;
uint8_t packet[7] = {0xFF, 0xFF, packetSize, id, (uint8_t)cmd, 0x00, 0x00};
/* uint8_t packet[packetSize]; */
packet[0] = 0xFF;
packet[1] = 0xFF;
packet[2] = packetSize;
packet[3] = id;
packet[4] = (uint8_t)cmd;
checksum1 = packetSize ^ id ^ (uint8_t)cmd;
if (pData && dataLen > 0)
{
for (uint8_t i = 0; i < dataLen; i++)
{
checksum1 ^= *(pData + i);
/* packet[7 + i] = *(pData + i); */
}
}
checksum1 = checksum1 & 0xFE;
checksum2 = (~checksum1) & 0xFE;
packet[5] = checksum1;
packet[6] = checksum2;
HAL_UART_Transmit(self->m_serial, packet, 7, 10);
printf("Data transmitted: 0x%.2X 0x%.2X 0x%.2X 0x%.2X 0x%.2X 0x%.2X 0x%.2X", packet[0], packet[1], packet[2], packet[3], packet[4], packet[5], packet[6]);
if (pData && dataLen > 0)
{
HAL_UART_Transmit(self->m_serial, pData, dataLen, 10);
for (uint8_t i = 0; i < dataLen; i++)
{
printf(" 0x%.2X", *(pData + i));
}
}
printf("\n\r");
// HAL_UART_Transmit(self->m_serial, packet, packetSize, 10);
// printf("Packet sent : ");
// for (uint8_t i = 0; i < packetSize; i++)
// {
// printf("0x%.2X ", packet[i]);
// }
// printf("\n\r");
}
/**
* @brief Process a received packet
* @param bus : ServoBus receiving the data
* @param dataLen : Lenght of the data to receive
* @retval None
*/
void processPacket(HerkulexServoBus *bus, const uint8_t dataLen)
{
uint8_t bytesToProcess = 0;
uint8_t dataIdx = 0;
uint8_t chkSum1 = 0;
uint8_t chkSum2 = 0;
HerkulexParserState parserState = HerkulexParserState_Header1;
HAL_UART_Receive(bus->m_serial, bus->m_rx_buffer, dataLen, 10);
if ((bus->m_rx_buffer[0] != 0xFF) || (bus->m_rx_buffer[1] != 0xFF))
{
return;
}
bytesToProcess = bus->m_rx_buffer[2];
while (bytesToProcess > 0)
{
uint8_t recByte = bus->m_rx_buffer[bus->m_rx_buffer[2] - bytesToProcess];
switch (parserState)
{
case HerkulexParserState_Header1:
if (recByte == 0xFF)
{
parserState = HerkulexParserState_Header2;
}
break;
case HerkulexParserState_Header2:
if (recByte == 0xFF)
{
parserState = HerkulexParserState_Length;
}
else
{
parserState = HerkulexParserState_Header1;
}
break;
case HerkulexParserState_Length:
bus->m_rx_packet.size = recByte;
chkSum1 = recByte;
parserState = HerkulexParserState_ID;
break;
case HerkulexParserState_ID:
bus->m_rx_packet.id = recByte;
chkSum1 ^= recByte;
parserState = HerkulexParserState_Command;
break;
case HerkulexParserState_Command:
bus->m_rx_packet.cmd = (HerkulexCommand)recByte;
chkSum1 ^= recByte;
parserState = HerkulexParserState_Checksum1;
break;
case HerkulexParserState_Checksum1:
bus->m_rx_packet.checksum1 = recByte;
parserState = HerkulexParserState_Checksum2;
break;
case HerkulexParserState_Checksum2:
bus->m_rx_packet.checksum2 = recByte;
parserState = HerkulexParserState_Data;
break;
case HerkulexParserState_Data:
bus->m_rx_packet.data[dataIdx] = recByte;
chkSum1 ^= recByte;
dataIdx++;
if (dataIdx > HERKULEX_PACKET_RX_MAX_DATA)
{
dataIdx = HERKULEX_PACKET_RX_MAX_DATA;
}
break;
default:
break;
}
}
if (dataIdx >= 2)
{
bus->m_rx_packet.status_error = bus->m_rx_packet.data[dataIdx - 2];
bus->m_rx_packet.status_detail = bus->m_rx_packet.data[dataIdx - 1];
}
chkSum1 = chkSum1 & 0xFE;
chkSum2 = (~chkSum1) & 0xFE;
if (chkSum1 != bus->m_rx_packet.checksum1 || chkSum2 != bus->m_rx_packet.checksum2)
{
bus->m_rx_packet.error |= HerkulexPacketError_Checksum;
}
bus->m_rx_packet_ready = 1;
}
/**
* @brief Transfer the data from the ServoBus buffer to the appropriate Servo data structure
* @param bus : ServoBus to extract data from
* @param response : pointer to the data structure of the receiving Servo
* @retval Success or not of the function
*/
uint8_t getPacket(HerkulexServoBus *bus, HerkulexPacket *response)
{
if (bus->m_rx_packet_ready == 0)
{
return 0;
}
response->size = bus->m_rx_packet.size;
response->id = bus->m_rx_packet.id;
response->cmd = bus->m_rx_packet.cmd;
response->checksum1 = bus->m_rx_packet.checksum1;
response->checksum2 = bus->m_rx_packet.checksum2;
for (uint8_t i = 0; i < HERKULEX_PACKET_RX_MAX_DATA; i++)
{
response->data[i] = bus->m_rx_packet.data[i];
}
response->status_error = bus->m_rx_packet.status_error;
response->status_detail = bus->m_rx_packet.status_detail;
response->error = bus->m_rx_packet.error;
bus->m_rx_packet_ready = 0;
return 1;
}
/**
* @brief Send a packet trough the bus and wait for the Servo to repond.
* Once the Servo responded, the response is stored in is internal data structure
* @param self : Pointer to the ServoBus used for communication
* @param response : Pointer the the Packet structure of the Servo
* @param id : ID of the Servo
* @param cmd : Enum of the command to send
* @param pData : Array of the optional additional data to send
* @param dataLen : Lenght of the data array
* @retval Succes or not
*/
uint8_t sendPacketAndWaitResponse(HerkulexServoBus *self, HerkulexPacket *response, uint8_t id, HerkulexCommand cmd, uint8_t *pData, uint8_t dataLen)
{
uint8_t success = 0;
uint32_t time_started = 0;
uint8_t dataLenToReceive;
if (cmd == HerkulexCommand_Stat)
{
dataLenToReceive = 9; /* 7 minimal bytes + status_error + status_detail */
}
else
{
dataLenToReceive = 9 + *(pData + 1);
}
self->m_rx_packet_ready = 0;
for (uint8_t attempts = 0; attempts < HERKULEX_PACKET_RETRIES; attempts++)
{
sendPacket(self, id, cmd, pData, dataLen);
time_started = HAL_GetTick();
while (!getPacket(self, response) && ((HAL_GetTick() - time_started) < HERKULEX_PACKET_RX_TIMEOUT))
{
processPacket(self, dataLenToReceive);
}
if ((response->error == HerkulexPacketError_None) && (response->id = id) && (response->cmd == (cmd | 0x40)))
{
success = 1;
break;
}
else
{
HAL_Delay(HERKULEX_PACKET_RX_TIMEOUT);
}
}
return success;
}
/**
* @brief Switch the state of the bus to individual move
* @note In individual move, each servo will be controlled independently from each other
* @param self : The ServoBus
* @retval None
*/
void prepareIndividualMove(HerkulexServoBus *self)
{
self->m_schedule_state = HerkulexScheduleState_IndividualMove;
self->m_move_tags = 0;
}
/**
* @brief Switch the state of the ServoBus to execute synchronized move of the Servos
* @note In synchronised move, the Servs will all have the same time to execute the position change
* @param self : The ServoBus
* @param time_ms : The time, in milliseconds, allowed to the Servos to execute the move
* @retval None
*/
void prepareSynchronizedMove(HerkulexServoBus *self, uint16_t time_ms)
{
uint8_t playtime = (uint8_t)(time_ms / 11.2f);
self->m_schedule_state = HerkulexScheduleState_SynchronizedMove;
*(self->m_tx_buffer + 0) = playtime;
self->m_move_tags = 0;
}
/**
* @brief Execute the move scheduled on the ServoBus and switch the scheduled state to none
* @param self : The ServoBus to execute the moves from
* @retval None
*/
void executeMove(HerkulexServoBus *self)
{
uint8_t dataLen;
switch (self->m_schedule_state)
{
case HerkulexScheduleState_IndividualMove:
dataLen = self->m_move_tags * 5;
sendPacket(self, HERKULEX_BROADCAST_ID, HerkulexCommand_IJog, self->m_tx_buffer, dataLen);
break;
case HerkulexScheduleState_SynchronizedMove:
dataLen = 1 + self->m_move_tags * 4;
sendPacket(self, HERKULEX_BROADCAST_ID, HerkulexCommand_SJog, self->m_tx_buffer, dataLen);
break;
case HerkulexScheduleState_None:
break;
}
self->m_schedule_state = HerkulexScheduleState_None;
self->m_move_tags = 0;
}
/* Structure used to store the servos responses */
HerkulexPacket m_response = {0, 0, HerkulexCommand_None, 0, 0, {0}, HerkulexStatusError_None, HerkulexStatusDetail_None, HerkulexPacketError_None};
/* Array used to store the tx data from the servos */
uint8_t tx_buffer[5] = {0, 0, 0, 0, 0};
/**
* @brief Initialize a Servo structure, assiciating a ServoBus and an ID to that Servo
* @param servoBus : Pointer to the servoBus used to communicate with the Servo
* @param id : ID of the Servo
* @retval Pointer to an initialized structure
*/
HerkulexServo *initializeServo(HerkulexServoBus *servoBus, uint8_t id)
{
HerkulexServo *servo = (HerkulexServo *)malloc(sizeof(HerkulexServo));
if (servo != NULL)
{
servo->m_bus = servoBus;
servo->m_id = id;
servo->m_led = HerkulexLed_Off;
servo->m_position_control_mode = 1;
servo->m_response = &m_response;
servo->m_tx_buffer = tx_buffer;
}
return servo;
}
/**
* @brief Write the command to the appropriate tx buffer depending on the ServoBus scheduled state
* @param servo : Pointer to the servo to control
* @param jog_lsb : og command lsb
* @param jog_msb : Jog command msb
* @param set
* @param playtime : Playtime of the movement
* @retval None
*/
void jog(HerkulexServo *servo, uint8_t jog_lsb, uint8_t jog_msb, uint8_t set, uint8_t playtime)
{
uint8_t idx_offset;
switch (servo->m_bus->m_schedule_state)
{
case HerkulexScheduleState_None:
*(servo->m_tx_buffer + 0) = jog_lsb;
*(servo->m_tx_buffer + 1) = jog_msb;
*(servo->m_tx_buffer + 2) = set;
*(servo->m_tx_buffer + 3) = servo->m_id;
*(servo->m_tx_buffer + 4) = playtime;
sendPacket(servo->m_bus, HERKULEX_BROADCAST_ID, HerkulexCommand_IJog, servo->m_tx_buffer, 5);
break;
case HerkulexScheduleState_IndividualMove:
if (((servo->m_bus->m_move_tags + 1) * 5) > HERKULEX_SERIAL_TX_BUFFER)
{
return; /* No room for another move tag, exit */
}
idx_offset = servo->m_bus->m_move_tags * 5; /* 5 bytes per tag */
*(servo->m_bus->m_tx_buffer + idx_offset) = jog_lsb;
*(servo->m_bus->m_tx_buffer + idx_offset + 1) = jog_msb;
*(servo->m_bus->m_tx_buffer + idx_offset + 2) = set;
*(servo->m_bus->m_tx_buffer + idx_offset + 3) = servo->m_id;
*(servo->m_bus->m_tx_buffer + idx_offset + 4) = playtime;
servo->m_bus->m_move_tags++;
break;
case HerkulexScheduleState_SynchronizedMove:
if ((1 + (servo->m_bus->m_move_tags + 1) * 4) > HERKULEX_SERIAL_TX_BUFFER)
{
return; /* No room for another move tag, exit */
}
idx_offset = 1 + servo->m_bus->m_move_tags * 4; /* 4 bytes per tag, 1 byte offset for time */
servo->m_bus->m_tx_buffer[idx_offset] = jog_lsb;
servo->m_bus->m_tx_buffer[idx_offset + 1] = jog_msb;
servo->m_bus->m_tx_buffer[idx_offset + 2] = set;
servo->m_bus->m_tx_buffer[idx_offset + 3] = servo->m_id;
servo->m_bus->m_move_tags++;
break;
default:
break;
}
}
/**
* @brief Set the servo to the desired position
* @param servo : Pointer to the Servo to control
* @param degree : Desired position in degree
* @param time_ms : Time allowed to execute the move, in milliseconds
* @param led : Color of the Servo led
* @retval None
*/
void setPosition(HerkulexServo *servo, float degree, uint8_t time_ms, HerkulexLed led)
{
uint16_t pos;
pos = (uint16_t)(512 + (degree / 0.325f));
uint8_t playtime = (uint8_t)(time_ms / 11.2f);
if (!servo->m_position_control_mode)
{
return;
}
uint8_t jog_lsb;
uint8_t jog_msb;
uint8_t set;
jog_lsb = (uint8_t)pos;
jog_msb = (uint8_t)(pos >> 8);
if (led != HerkulexLed_Ignore)
{
servo->m_led = led;
set = (uint8_t)(led << 2);
}
else
{
set = (uint8_t)(servo->m_led << 2);
}
jog(servo, jog_lsb, jog_msb, set, playtime);
}
/**
* @brief Set the rotation speed of the Servo
* @param servo : Pointer to the Servo to control
* @param speed : Rotation speed
* @param time_ms : Time of the rotation in milliseconds
* @param led : Led color of the Servo
* @retval None
*/
void setSpeed(HerkulexServo *servo, uint16_t speed, uint16_t time_ms, HerkulexLed led)
{
uint8_t playtime = (uint8_t)(time_ms / 11.2f);
if (servo->m_position_control_mode)
{
return;
}
uint8_t jog_lsb;
uint8_t jog_msb;
uint8_t set;
uint16_t speed_raw;
if (speed >= 0)
{
speed_raw = speed;
}
else
{
speed_raw = -speed;
}
speed_raw &= 0x03FF; /* Upper speed limit to 1023 */
jog_lsb = (uint8_t)speed_raw;
jog_msb = (uint8_t)(speed_raw >> 8);
if (speed < 0)
{
jog_msb |= 0x40;
}
if (led != HerkulexLed_Ignore)
{
servo->m_led = led;
set = (uint8_t)(led) << 2;
}
else
{
set = (uint8_t)(servo->m_led) << 2;
}
set |= 0x02; /* Continuous rotation flag */
jog(servo, jog_lsb, jog_msb, set, playtime);
}
/**
* @brief Set the torque ON on the desired Servo
* @param servo : Pointer to the Servo to control
* @retval None
*/
void setTorqueOn(HerkulexServo *servo)
{
writeRam(servo, HerkulexRamRegister_TorqueControl, 0x60);
}
/**
* @brief Set the torque OFF on the desired Servo
* @param servo : Pointer to the Servo to control
* @retval None
*/
void setTorqueOff(HerkulexServo *servo)
{
writeRam(servo, HerkulexRamRegister_TorqueControl, 0x00);
}
/**
* @brief Set the brake on the desired Servo
* @param servo : Pointer to the Servo to controll
* @retval None
*/
void setBrake(HerkulexServo *servo)
{
writeRam(servo, HerkulexRamRegister_TorqueControl, 0x40);
}
/**
* @brief Set the led color of the desired Servo
* @param servo : Pointer to the Servo to control
* @param color : desired led color
* @retval None
*/
void setLedColor(HerkulexServo *servo, HerkulexLed color)
{
if (color == HerkulexLed_Ignore)
{
return;
}
servo->m_led = color;
writeRam(servo, HerkulexRamRegister_LedControl, (uint8_t)color);
}
/**
* @brief Write the desired one byte value to a specified RAM register
* @param servo : Pointer to the Servo to control
* @param reg : register to write to
* @param val : value to write
* @retval None
*/
void writeRam(HerkulexServo *servo, HerkulexRamRegister reg, uint8_t val)
{
*(servo->m_tx_buffer + 0) = (uint8_t)reg;
*(servo->m_tx_buffer + 1) = 1;
*(servo->m_tx_buffer + 2) = val;
sendPacket(servo->m_bus, servo->m_id, HerkulexCommand_RamWrite, servo->m_tx_buffer, 3);
}
/**
* @brief Write the desired two bytes value to a specified RAM register
* @param servo : Pointer to the Servo to control
* @param reg : register to write to
* @param val : value to write
* @retval None
*/
void writeRam2(HerkulexServo *servo, HerkulexRamRegister reg, uint16_t val)
{
*(servo->m_tx_buffer + 0) = (uint8_t)reg;
*(servo->m_tx_buffer + 1) = 2;
*(servo->m_tx_buffer + 2) = (uint8_t)val;
*(servo->m_tx_buffer + 3) = (uint8_t)(val >> 8);
sendPacket(servo->m_bus, servo->m_id, HerkulexCommand_RamWrite, servo->m_tx_buffer, 4);
}
/**
* @brief Write the desired one byte value to a specified EEP register
* @param servo : Pointer to the Servo to control
* @param reg : register to write to
* @param val : value to write
* @retval None
*/
void writeEep(HerkulexServo *servo, HerkulexEepRegister reg, uint8_t val)
{
*(servo->m_tx_buffer + 0) = (uint8_t)reg;
*(servo->m_tx_buffer + 1) = 1;
*(servo->m_tx_buffer + 2) = val;
sendPacket(servo->m_bus, servo->m_id, HerkulexCommand_EepWrite, servo->m_tx_buffer, 3);
}
/**
* @brief Write the desired two bytes value to a specified EEP register
* @param servo : Pointer to the Servo to control
* @param reg : register to write to
* @param val : value to write
* @retval None
*/
void writeEep2(HerkulexServo *servo, HerkulexEepRegister reg, uint16_t val)
{
*(servo->m_tx_buffer + 0) = (uint8_t)reg;
*(servo->m_tx_buffer + 1) = 2;
*(servo->m_tx_buffer + 2) = (uint8_t)val;
*(servo->m_tx_buffer + 3) = (uint8_t)(val >> 8);
sendPacket(servo->m_bus, servo->m_id, HerkulexCommand_EepWrite, servo->m_tx_buffer, 4);
}
/**
* @brief Read a specific one byte value from the Servo RAM register
* @param servo : Pointer to the servo to read from
* @param reg : register to read
* @retval Value of the register
*/
uint8_t readRam(HerkulexServo *servo, HerkulexRamRegister reg)
{
servo->m_tx_buffer[0] = (uint8_t)reg;
servo->m_tx_buffer[1] = 1;
sendPacketAndWaitResponse(servo->m_bus, servo->m_response, servo->m_id, HerkulexCommand_RamRead, servo->m_tx_buffer, 2);
return servo->m_response->data[2];
}
/**
* @brief Read a specific two bytes value from the Servo RAM register
* @param servo : Pointer to the servo to read from
* @param reg : register to read
* @retval Value of the register
*/
uint16_t readRam2(HerkulexServo *servo, HerkulexRamRegister reg);
/**
* @brief Read a specific one byte value from the Servo EEP register
* @param servo : Pointer to the servo to read from
* @param reg : register to read
* @retval Value of the register
*/
uint8_t readEep(HerkulexServo *servo, HerkulexEepRegister reg);
/**
* @brief Read a specific two bytes value from the Servo RAM register
* @param servo : Pointer to the servo to read from
* @param reg : register to read
* @retval Value of the register
*/
uint8_t readEep2(HerkulexServo *servo, HerkulexEepRegister reg);
/**
* @brief enable the position control mode of the servo
* @param servo : Pointer to the Servo to control
* @retval None
*/
void enablePositionControlMode(HerkulexServo *servo)
{
if (servo->m_position_control_mode)
{
return;
}
servo->m_position_control_mode = 1;
uint8_t set;
set = (uint8_t)servo->m_led << 2;
set |= 0x02; /* Continuous rotation */
set |= 0x20; /* jog invalid */
*(servo->m_tx_buffer + 0) = 0x00;
*(servo->m_tx_buffer + 1) = 0x00;
*(servo->m_tx_buffer + 2) = set;
*(servo->m_tx_buffer + 3) = servo->m_id;
*(servo->m_tx_buffer + 4) = 0x00;
sendPacket(servo->m_bus, HERKULEX_BROADCAST_ID, HerkulexCommand_IJog, servo->m_tx_buffer, 5);
}
/**
* @brief enable the speed control mode for the Servo
* @param servo : Pointer to the Servo to control
* @retval None
*/
void enableSpeedControlMode(HerkulexServo *servo)
{
if (!servo->m_position_control_mode)
{
return;
}
servo->m_position_control_mode = 0;
uint8_t set = 0;
set |= ((uint8_t)servo->m_led) << 2;
set |= 0x20; /* jog invalid, continuous rotation bit (0x02) implicitly set to 0 */
*(servo->m_tx_buffer + 0) = 0x00; /* jog lsb */
*(servo->m_tx_buffer + 1) = 0x00; /* jog msb */
*(servo->m_tx_buffer + 2) = set;
*(servo->m_tx_buffer + 3) = servo->m_id;
*(servo->m_tx_buffer + 4) = 0x00; /* playtime */
sendPacket(servo->m_bus, HERKULEX_BROADCAST_ID, HerkulexCommand_IJog, servo->m_tx_buffer, 5);
}
/**
* @brief Reboot the servo
* @param servo : Pointer to the Servo to control
* @retval None
*/
void servoReboot(HerkulexServo *servo)
{
sendPacket(servo->m_bus, servo->m_id, HerkulexCommand_Reboot, NULL, 0);
}
/**
* @brief Reset the Servo EEP values to the factory default, option is given to skip changing the ID and baud rate of the Servo
* @param servo : Pointer to the Servo to reset
* @param skipID : 0 for no, 1 for yes
* @param skipBaud : 0 for no, 1 for yes
* @retval None
*/
void rollBackToFactoryDefault(HerkulexServo *servo, uint8_t skipID, uint8_t skipBaud)
{
*(servo->m_tx_buffer + 0) = skipID ? 1 : 0;
*(servo->m_tx_buffer + 1) = skipBaud ? 1 : 0;
sendPacket(servo->m_bus, servo->m_id, HerkulexCommand_Rollback, servo->m_tx_buffer, 2);
}
<file_sep>/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include "HerkulexServo.h"
#include "servoControl.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
unsigned char buttonPressed;
unsigned char receivedUART;
unsigned char passed;
uint8_t rData[9] = {0};
uint32_t nLoop;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin);
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart);
void resetToFactoryDefault(uint8_t id);
void askStat(uint8_t id);
void reboot(uint8_t id);
void changeID(uint8_t oldID, uint8_t newID);
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
buttonPressed = 0;
receivedUART = 0;
passed = 0;
HerkulexServoBus *herkulexBus = initializeServoBus(&huart5);
HerkulexServo *servo_chevilleDroite = initializeServo(herkulexBus, 0xDA);
HerkulexServo *servo_genouDroit = initializeServo(herkulexBus, 0xDC);
HerkulexServo *servo_hancheDroite = initializeServo(herkulexBus, 0xDB);
HerkulexServo *servo_bassinDroit = initializeServo(herkulexBus, 0xCB);
HerkulexServo *servo_bassinGauche = initializeServo(herkulexBus, 0xBB);
HerkulexServo *servo_hancheGauche = initializeServo(herkulexBus, 0xDD);
HerkulexServo *servo_genouGauche = initializeServo(herkulexBus, 0xCA);
HerkulexServo *servo_chevilleGauche = initializeServo(herkulexBus, 0xCC);
HerkulexServo *articulations[8] = {servo_chevilleDroite, servo_genouDroit, servo_hancheDroite, servo_bassinDroit, servo_bassinGauche, servo_hancheGauche, servo_genouGauche, servo_chevilleGauche};
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_UART5_Init();
MX_USART2_UART_Init();
MX_DMA_Init();
/* USER CODE BEGIN 2 */
for (uint8_t i = 0; i < 8; i++)
{
setTorqueOn(articulations[i]);
}
initialisePosition(articulations);
HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, GPIO_PIN_SET);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
if (buttonPressed)
{
HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, GPIO_PIN_RESET);
walk(articulations, 10);
buttonPressed = 0;
}
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the USART2 and Loop until the end of transmission */
HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
buttonPressed = 1;
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(huart);
/* NOTE: This function should not be modified, when the callback is needed,
* the HAL_UART_RxCpltCallback could be implemented in the user file
* */
receivedUART = 1;
}
void resetToFactoryDefault(uint8_t id)
{
uint8_t data_len = 0x09;
uint8_t cmd = 0x08;
uint8_t checksum1;
uint8_t checksum2;
uint8_t data1 = 0x00;
uint8_t data2 = 0x00;
uint8_t tData[0x09];
checksum1 = data_len ^ id ^ cmd ^ data1 ^ data2;
checksum1 = checksum1 & 0xFE;
checksum2 = (~checksum1) & 0xFE;
tData[0] = 0xFF;
tData[1] = 0xFF;
tData[2] = data_len;
tData[3] = id;
tData[4] = cmd;
tData[5] = checksum1;
tData[6] = checksum2;
tData[7] = data1;
tData[8] = data2;
printf("\n\rData sent: ");
for (uint8_t i = 0; i < sizeof(tData); i++)
{
printf("%.2X ", tData[i]);
}
printf("\n\r");
HAL_UART_Transmit(&huart5, tData, sizeof(tData), 1000);
}
void askStat(uint8_t id)
{
const uint8_t data_len = 0x07;
uint8_t cmd = 0x07;
uint8_t checksum1;
uint8_t checksum2;
uint8_t tData[data_len];
checksum1 = data_len ^ id ^ cmd;
checksum1 = checksum1 & 0xFE;
checksum2 = (~checksum1) & 0xFE;
tData[0] = 0xFF;
tData[1] = 0xFF;
tData[2] = data_len;
tData[3] = id;
tData[4] = cmd;
tData[5] = checksum1;
tData[6] = checksum2;
printf("\n\rData sent: ");
for (uint8_t i = 0; i < sizeof(tData); i++)
{
printf("%.2X ", tData[i]);
}
printf("\n\r");
HAL_UART_Transmit(&huart5, tData, sizeof(tData), 1000);
}
void reboot(uint8_t id)
{
const uint8_t data_len = 0x07;
uint8_t cmd = 0x09;
uint8_t checksum1;
uint8_t checksum2;
uint8_t tData[data_len];
checksum1 = data_len ^ id ^ cmd;
checksum1 = checksum1 & 0xFE;
checksum2 = (~checksum1) & 0xFE;
tData[0] = 0xFF;
tData[1] = 0xFF;
tData[2] = data_len;
tData[3] = id;
tData[4] = cmd;
tData[5] = checksum1;
tData[6] = checksum2;
printf("\n\rData sent: ");
for (uint8_t i = 0; i < sizeof(tData); i++)
{
printf("%.2X ", tData[i]);
}
printf("\n\r");
HAL_UART_Transmit(&huart5, tData, sizeof(tData), 1000);
}
void changeID(uint8_t oldID, uint8_t newID)
{
const uint8_t data_len = 0x0A;
uint8_t cmd = 0x01;
uint8_t checksum1;
uint8_t checksum2;
uint8_t data1 = 0x06;
uint8_t data2 = 0x01;
uint8_t data3 = newID;
uint8_t tData[data_len];
checksum1 = data_len ^ oldID ^ cmd ^ data1 ^ data2 ^ data3;
checksum1 = checksum1 & 0xFE;
checksum2 = (~checksum1) & 0xFE;
tData[0] = 0xFF;
tData[1] = 0xFF;
tData[2] = data_len;
tData[3] = oldID;
tData[4] = cmd;
tData[5] = checksum1;
tData[6] = checksum2;
tData[7] = data1;
tData[8] = data2;
tData[9] = data3;
printf("\n\rData sent: ");
for (uint8_t i = 0; i < sizeof(tData); i++)
{
printf("%.2X ", tData[i]);
}
printf("\n\r");
HAL_UART_Transmit(&huart5, tData, sizeof(tData), 1000);
cmd = 0x03;
data1 = 0x00;
checksum1 = data_len ^ oldID ^ cmd ^ data1 ^ data2 ^ data3;
checksum1 = checksum1 & 0xFE;
checksum2 = (~checksum1) & 0xFE;
printf("\n\rData sent: ");
for (uint8_t i = 0; i < sizeof(tData); i++)
{
printf("%.2X ", tData[i]);
}
printf("\n\r");
HAL_UART_Transmit(&huart5, tData, sizeof(tData), 1000);
askStat(newID);
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/*
* HerkulexServo.h
*
* Created on: Dec 6, 2019
* Author: Antoine
*/
#ifndef INC_HERKULEXSERVO_H_
#define INC_HERKULEXSERVO_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "usart.h"
/* Broadcast ID to send a command to all servos */
#define HERKULEX_BROADCAST_ID 0xFE
/* Minimum size for the TX buffer */
#define SERVO_TX_BUFFER_SIZE sizeof(uint8_t) * 5
/* Timeout for sending packet */
#ifndef HERKULEX_PACKET_RX_TIMEOUT
#define HERKULEX_PACKET_RX_TIMEOUT 1 // milliseconds
#endif
/* Retries before considering failed communication */
#ifndef HERKULEX_PACKET_RETRIES
#define HERKULEX_PACKET_RETRIES 6
#endif
/* Delay before trying to resend packet */
#ifndef HERKULEX_PACKET_RESEND_DELAY
#define HERKULEX_PACKET_RESEND_DELAY 70 // microseconds
#endif
/* Maximum data sent to the servo */
#ifndef HERKULEX_PACKET_RX_MAX_DATA
#define HERKULEX_PACKET_RX_MAX_DATA 4 // bytes
#endif
#ifndef HERKULEX_SERIAL_RX_BUFFER
#define HERKULEX_SERIAL_RX_BUFFER 30 // bytes
#endif
/* Number of servo to controll */
#ifndef HERKULEX_MAX_SCHEDULED_SERVOS
#define HERKULEX_MAX_SCHEDULED_SERVOS 8
#endif
#ifndef HERKULEX_SERIAL_TX_BUFFER
#define HERKULEX_SERIAL_TX_BUFFER (1 + HERKULEX_MAX_SCHEDULED_SERVOS * 5)
#endif
/* Hex code of the command */
typedef enum
{
HerkulexCommand_None = 0x00,
HerkulexCommand_EepWrite = 0x01,
HerkulexCommand_EepRead = 0x02,
HerkulexCommand_RamWrite = 0x03,
HerkulexCommand_RamRead = 0x04,
HerkulexCommand_IJog = 0x05,
HerkulexCommand_SJog = 0x06,
HerkulexCommand_Stat = 0x07,
HerkulexCommand_Rollback = 0x08,
HerkulexCommand_Reboot = 0x09
} HerkulexCommand;
/* Values of the EEP register */
typedef enum
{
HerkulexEepRegister_ModelNo1 = 0,
HerkulexEepRegister_ModelNo2 = 1,
HerkulexEepRegister_Version1 = 2,
HerkulexEepRegister_Version2 = 3,
HerkulexEepRegister_BaudRate = 4,
HerkulexEepRegister_ID = 6,
HerkulexEepRegister_AckPolicy = 7,
HerkulexEepRegister_AlarmLedPolicy = 8,
HerkulexEepRegister_TorquePolicy = 9,
HerkulexEepRegister_MaxTemperature = 11,
HerkulexEepRegister_MinVoltage = 12,
HerkulexEepRegister_MaxVoltage = 13,
HerkulexEepRegister_AccelerationRatio = 14,
HerkulexEepRegister_MaxAccelerationTime = 15,
HerkulexEepRegister_DeadZone = 16,
HerkulexEepRegister_SaturatorOffset = 17,
HerkulexEepRegister_SaturatorSlope = 18,
HerkulexEepRegister_PwmOffset = 20,
HerkulexEepRegister_MinPwm = 21,
HerkulexEepRegister_MaxPwm = 22,
HerkulexEepRegister_OverloadPwmThreshold = 24,
HerkulexEepRegister_MinPosition = 26,
HerkulexEepRegister_MaxPosition = 28,
HerkulexEepRegister_PositionKp = 30,
HerkulexEepRegister_PositionKd = 32,
HerkulexEepRegister_PositionKi = 34,
HerkulexEepRegister_PositionFF1stGain = 36,
HerkulexEepRegister_PositionFF2ndGain = 38,
HerkulexEepRegister_LedBlinkPeriod = 44,
HerkulexEepRegister_AdcFaultCheckPeriod = 45,
HerkulexEepRegister_PacketGarbageCheckPeriod = 46,
HerkulexEepRegister_StopDetectionPeriod = 47,
HerkulexEepRegister_OverloadProtectionPeriod = 48,
HerkulexEepRegister_StopThreshold = 49,
HerkulexEepRegister_InPositionMargin = 50,
HerkulexEepRegister_CalibrationDifference = 53
} HerkulexEepRegister;
/* Values of the RAM register */
typedef enum
{
HerkulexRamRegister_ID = 0,
HerkulexRamRegister_AckPolicy = 1,
HerkulexRamRegister_AlarmLedPolicy = 2,
HerkulexRamRegister_TorquePolicy = 3,
HerkulexRamRegister_MaxTemperature = 5,
HerkulexRamRegister_MinVoltage = 6,
HerkulexRamRegister_MaxVoltage = 7,
HerkulexRamRegister_AccelerationRatio = 8,
HerkulexRamRegister_MaxAccelerationTime = 9,
HerkulexRamRegister_DeadZone = 10,
HerkulexRamRegister_SaturatorOffset = 11,
HerkulexRamRegister_SaturatorSlope = 12,
HerkulexRamRegister_PwmOffset = 14,
HerkulexRamRegister_MinPwm = 15,
HerkulexRamRegister_MaxPwm = 16,
HerkulexRamRegister_OverloadPwmThreshold = 18,
HerkulexRamRegister_MinPosition = 20,
HerkulexRamRegister_MaxPosition = 22,
HerkulexRamRegister_PositionKp = 24,
HerkulexRamRegister_PositionKd = 26,
HerkulexRamRegister_PositionKi = 28,
HerkulexRamRegister_PositionFF1stGain = 30,
HerkulexRamRegister_PositionFF2ndGain = 32,
HerkulexRamRegister_LedBlinkPeriod = 38,
HerkulexRamRegister_AdcFaultCheckPeriod = 39,
HerkulexRamRegister_PacketGarbageCheckPeriod = 40,
HerkulexRamRegister_StopDetectionPeriod = 41,
HerkulexRamRegister_OverloadProtectionPeriod = 42,
HerkulexRamRegister_StopThreshold = 43,
HerkulexRamRegister_InPositionMargin = 44,
HerkulexRamRegister_CalibrationDifference = 47,
HerkulexRamRegister_StatusError = 48,
HerkulexRamRegister_StatusDetail = 49,
HerkulexRamRegister_TorqueControl = 52,
HerkulexRamRegister_LedControl = 53,
HerkulexRamRegister_Voltage = 54,
HerkulexRamRegister_Temperature = 55,
HerkulexRamRegister_CurrentControlMode = 56,
HerkulexRamRegister_Tick = 57,
HerkulexRamRegister_CalibratedPosition = 58,
HerkulexRamRegister_AbsolutePosition = 60,
HerkulexRamRegister_DifferentialPosition = 62,
HerkulexRamRegister_Pwm = 64,
HerkulexRamRegister_AbsoluteGoalPosition = 68,
HerkulexRamRegister_AbsoluteDesiredTrajPos = 70,
HerkulexRamRegister_DesiredVelocity = 72
} HerkulexRamRegister;
/* Hex values of the servo LED states */
typedef enum
{
HerkulexLed_Off = 0x00,
HerkulexLed_Red = 0x04,
HerkulexLed_Green = 0x01,
HerkulexLed_Blue = 0x02,
HerkulexLed_Yellow = 0x05,
HerkulexLed_Cyan = 0x03,
HerkulexLed_Purple = 0x06,
HerkulexLed_White = 0x07,
HerkulexLed_Ignore = 0xFF
} HerkulexLed;
/* Flags of the packet error */
typedef enum
{
HerkulexPacketError_None = 0,
HerkulexPacketError_Timeout = 0b00000001,
HerkulexPacketError_Length = 0b00000010,
HerkulexPacketError_Command = 0b00000100,
HerkulexPacketError_Checksum = 0b00001000
} HerkulexPacketError;
/* Flags of the status error from the STAT command response */
typedef enum
{
HerkulexStatusError_None = 0,
HerkulexStatusError_InputVoltage = 0b00000001,
HerkulexStatusError_PotLimit = 0b00000010,
HerkulexStatusError_TemperatureLimit = 0b00000100,
HerkulexStatusError_InvalidPacket = 0b00001000,
HerkulexStatusError_Overload = 0b00010000,
HerkulexStatusError_DriverFault = 0b00100000,
HerkulexStatusError_EEPDistorted = 0b01000000,
HerkulexStatusError_Reserved = 0b10000000
} HerkulexStatusError;
/* Flags of the status detail from the STAT command response */
typedef enum
{
HerkulexStatusDetail_None = 0,
HerkulexStatusDetail_Moving = 0b00000001,
HerkulexStatusDetail_InPosition = 0b00000010,
HerkulexStatusDetail_ChecksumError = 0b00000100,
HerkulexStatusDetail_UnknownCommand = 0b00001000,
HerkulexStatusDetail_ExceedRegRange = 0b00010000,
HerkulexStatusDetail_GarbageDetected = 0b00100000,
HerkulexStatusDetail_MotorOn = 0b01000000,
HerkulexStatusDetail_Reserved = 0b10000000
} HerkulexStatusDetail;
/* Scheduled bus state */
typedef enum
{
HerkulexScheduleState_None = 0,
HerkulexScheduleState_IndividualMove,
HerkulexScheduleState_SynchronizedMove
} HerkulexScheduleState;
/* Received packet parser state */
typedef enum
{
HerkulexParserState_Header1,
HerkulexParserState_Header2,
HerkulexParserState_Length,
HerkulexParserState_ID,
HerkulexParserState_Command,
HerkulexParserState_Checksum1,
HerkulexParserState_Checksum2,
HerkulexParserState_Data
} HerkulexParserState;
/* Structure of a packet (send and receive) */
typedef struct
{
uint8_t size;
uint8_t id;
HerkulexCommand cmd;
uint8_t checksum1;
uint8_t checksum2;
uint8_t data[HERKULEX_PACKET_RX_MAX_DATA];
uint8_t status_error;
uint8_t status_detail;
HerkulexPacketError error;
} HerkulexPacket;
/* Structure of the ServoBus used to send and receive the data */
typedef struct _HerkulexServoBus
{
UART_HandleTypeDef *m_serial;
uint8_t m_rx_buffer[7 + HERKULEX_PACKET_RX_MAX_DATA];
uint64_t m_last_serial;
HerkulexPacket m_rx_packet;
uint8_t m_rx_packet_ready;
uint8_t m_tx_buffer[HERKULEX_SERIAL_TX_BUFFER];
uint8_t m_move_tags;
HerkulexScheduleState m_schedule_state;
} HerkulexServoBus;
HerkulexServoBus *initializeServoBus(UART_HandleTypeDef *HUART_Handler);
void sendPacket(HerkulexServoBus *self, uint8_t id, HerkulexCommand cmd, uint8_t *pData, uint8_t dataLen);
void processPacket(HerkulexServoBus *bus, const uint8_t dataLen);
uint8_t getPacket(HerkulexServoBus *bus, HerkulexPacket *response);
uint8_t sendPacketAndWaitResponse(HerkulexServoBus *self, HerkulexPacket *response, uint8_t id, HerkulexCommand cmd, uint8_t *pData, uint8_t dataLen);
void prepareIndividualMove(HerkulexServoBus *self);
void prepareSynchronizedMove(HerkulexServoBus *self, uint16_t time_ms);
void executeMove(HerkulexServoBus *self);
/* Structure of a Servomotor */
typedef struct _HerkulexServo
{
HerkulexServoBus *m_bus;
uint8_t m_id;
HerkulexLed m_led;
uint8_t m_position_control_mode;
HerkulexPacket *m_response;
uint8_t *m_tx_buffer;
} HerkulexServo;
HerkulexServo *initializeServo(HerkulexServoBus *servoBus, uint8_t id);
void jog(HerkulexServo *servo, uint8_t jog_lsb, uint8_t jog_msb, uint8_t set, uint8_t playtime);
void setPosition(HerkulexServo *servo, float degree, uint8_t time_ms, HerkulexLed led);
void setSpeed(HerkulexServo *servo, uint16_t speed, uint16_t time_ms, HerkulexLed led);
void setTorqueOn(HerkulexServo *servo);
void setTorqueOff(HerkulexServo *servo);
void setBrake(HerkulexServo *servo);
void setLedColor(HerkulexServo *servo, HerkulexLed color);
void writeRam(HerkulexServo *servo, HerkulexRamRegister reg, uint8_t val);
void writeRam2(HerkulexServo *servo, HerkulexRamRegister reg, uint16_t val);
void writeEep(HerkulexServo *servo, HerkulexEepRegister reg, uint8_t val);
void writeEep2(HerkulexServo *servo, HerkulexEepRegister reg, uint16_t val);
uint8_t readRam(HerkulexServo *servo, HerkulexRamRegister reg);
uint16_t readRam2(HerkulexServo *servo, HerkulexRamRegister reg);
uint8_t readEep(HerkulexServo *servo, HerkulexEepRegister reg);
uint8_t readEep2(HerkulexServo *servo, HerkulexEepRegister reg);
void enablePositionControlMode(HerkulexServo *servo);
void enableSpeedControlMode(HerkulexServo *servo);
void servoReboot(HerkulexServo *servo);
void rollBackToFactoryDefault(HerkulexServo *servo, uint8_t skipID, uint8_t skipBaud);
#endif /* INC_HERKULEXSERVO_H_ */
|
e04e735e74a57096b671ab73a335ef943d4c047d
|
[
"C"
] | 5 |
C
|
francoisdo/exo
|
fa815c095bd663cfdf69a6c6cf228546e9548a23
|
7f60abf89fdd9914bc93adaf2e9572c71c9fd1df
|
refs/heads/master
|
<file_sep>package _02_The_Wave;
import java.util.ArrayList;
public class _01_TheWave {
/*
* Background: https://en.wikipedia.org/wiki/Wave_%28audience%29
*
* Task: Your task is to create a function that turns a string into a Wave. You
* will be passed a string and you must return that string in an ArrayList where
* an uppercase letter is a person standing up. Example: wave("hello") =>
* "Hello", "hEllo", "heLlo", "helLo", "hellO"
*
* 1. The input string will always be lower case but maybe empty. 2. If the
* character in the string is whitespace then pass over it as if it was an empty
* seat.
*/
public static ArrayList<String> wave(String str) {
ArrayList<String> waveStr = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
String a = str.charAt(i) + "";
String oldStr = a;
if (Character.isAlphabetic(a.charAt(0))){
a = a.toUpperCase();
oldStr = str.substring(0,i) + a + str.substring(i + 1, str.length());
}
if(Character.isWhitespace(oldStr.charAt(0)) == false){
waveStr.add(oldStr);
}
}
System.out.println(waveStr);
return waveStr;
}
}
|
44ec3806a63af29f85ff4213a281c6bf838eeef0
|
[
"Java"
] | 1 |
Java
|
League-level3-student/level3-module3-ShivamPansuria07
|
b36a46d929e9f4fababab487c82ce635bded3e92
|
06d63dc538604d26353918a3a0f2e0a30e65cf70
|
refs/heads/master
|
<file_sep>set -e
REPO_URL="http://yum.puppetlabs.com/el/6/products/i386/puppetlabs-release-6-11.noarch.rpm"
if ["$EUID" -ne "0"]; then
echo "This script should be run as root" >&2
exit 1
fi
if which puppet > /dev/null 2>&1; then
echo "Puppet already installed"
exit 0
fi
# Install puppet labs repo
echo "configuring puppetlabs repo.."
repo_path =$(mktemp)
wget --output-document=${repo_path} ${REPO_URL} 2>/dev/null
rpm -i ${repo_path} > /dev/null
# Install puppet..
echo "installing puppet"
yum install -y puppet > /dev/null
echo "Puppet installed!!"
<file_sep>Vagrant.configure(2) do |config|
config.vm.box = "dev-env"
config.vm.hostname = "development.puppetlabs.vm"
config.vm.network "private_network", ip: "172.31.0.202"
config.vm.network "forwarded_port", guest: 80, host: 8084
config.vm.provision :shell, :path => "centos_7_x.sh"
# Puppet shared folder
config.vm.synced_folder "puppet", "/puppet"
#puppet provision setup
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "puppet/manifests"
puppet.module_path = "puppet/modules"
puppet.manifest_file = "site.pp"
end
end
<file_sep>http://html5doctor.com/blockquote-q-cite/
|
6e54f82d74b9234ebc88a99c5b57103ae084cedd
|
[
"Markdown",
"Ruby",
"Shell"
] | 3 |
Shell
|
omps/omps.orig
|
56a702717f0956046684e784cbd023c6427db515
|
89a48fcd3520858744c5e5d6f85c0667966eecec
|
refs/heads/master
|
<repo_name>hubpython/actividad-00-actividad0<file_sep>/ejercicio-01/holamundo.py
print("<NAME>")
print("Hello earth")
|
4fe4bea166d3f2af29328865c07cf5c0a6cfdaaf
|
[
"Python"
] | 1 |
Python
|
hubpython/actividad-00-actividad0
|
6a45d20574523013565fc72465c3cb3f740c9fcf
|
a6bdf49085c465faf30c423019721b9ad3e83093
|
refs/heads/master
|
<file_sep>require 'spec_helper'
describe Timecop2::Person do
describe :relationships do
it { should have_many :projects }
it { should have_many :jobs }
end
describe :presentation do
it { should have_grid_data :name, :gender, :phone }
end
end
<file_sep>require 'spec_helper'
describe Timecop2::Mixins::Business do
subject { ::Business.new }
it { should be_a SopCoreModels::Mixins::Business }
it { should be_a Timecop2::Mixins::Business }
end
<file_sep>class CreateTimecop2Jobs < ActiveRecord::Migration
def change
create_table :timecop2_jobs do |t|
t.references :business
t.references :project
t.references :person
t.string :name
t.decimal :duration
t.string :notes
t.timestamps
end
add_index :timecop2_jobs, :business_id
add_index :timecop2_jobs, :project_id
add_index :timecop2_jobs, :person_id
end
end
<file_sep>Rails.application.routes.draw do
mount SopSettings::Engine => "/settings", :as => :sop_settings
mount SopAdmin::Engine => "/admin", :as => :sop_admin
mount Timecop2::Engine => "/timecop2"
root :to => 'timecop2/welcome#index'
end
<file_sep># These is where you can add settings for your engine.
#
# If your engine requires more than one settings pod, you can create additional
# files similar to this one - all files in the /lib/timecop2/settings
# folder will be loaded.
module Timecop2
# Your engine's settings.
module Settings
# Default settings pod for your engine. Uncomment the below block to activate them.
# class Timecop2Settings < SopSettings::Settings
# # The title of the pod containing the settings (can be I18n)
# self.title = 'The Settings Pod Title'
#
# # The description of the pod containing the settings (can be I18n)
# self.description = 'The Settings Pod Description'
#
# # Adding a link to the settings. If :url is a symbol, will try to call url_for(:url)
# # during rendering.
# #
# # Calling add_settings multiple times will append additional links to the settings pod.
#
# add_setting do |s|
# s.title = "Some Path Settings"
# s.for = '/some_path'
# end
#
# add_setting do |s|
# s.title = "Some Object Settings"
# s.for = :object
# end
# end
end
end<file_sep>module Timecop2
class Person < ActiveRecord::Base
belongs_to :business
has_many :projects
has_many :jobs
attr_accessible :gender, :name, :phone
grid_data_is :name, :gender, :phone
def formatted
name
end
end
end
<file_sep>
module Timecop2
class WelcomeController < ApplicationController
end
end
<file_sep>module Timecop2
class Job < ActiveRecord::Base
belongs_to :business
belongs_to :project
belongs_to :person
attr_accessible :name, :notes, :duration
grid_data_is :project, :name, :duration
end
end
<file_sep>require "timecop2/engine"
module Timecop2
end
<file_sep>require('/assets/dev/sop_ui_components.js');
require('/assets/sop_ui_components.js');
stylesheet('/assets/sop_ui_components.css');
<file_sep>require 'spec_helper'
describe Timecop2::Job do
describe :relationships do
it { should belong_to :person }
it { should belong_to :project }
end
describe :presentation do
it { should have_grid_data :project, :name, :duration }
end
end
<file_sep># This migration comes from sop_settings (originally 20120316144513)
class CreateTrials < ActiveRecord::Migration
def change
create_table :sop_settings_trials do |t|
t.references :business
t.string :service_uid
t.date :ends_at
t.timestamps
end
add_index :sop_settings_trials, :service_uid
end
end
<file_sep>class CreateTimecop2Projects < ActiveRecord::Migration
def change
create_table :timecop2_projects do |t|
t.references :business
t.string :name
t.decimal :budget
t.string :notes
t.boolean :done
t.timestamps
end
add_index :timecop2_projects, :business_id
end
end
<file_sep>SopSupport::Menu.main_menu do |m|
m.resource :jobs, :engine => :timecop2
m.resource :projects, :engine => :timecop2
m.resource :people, :engine => :timecop2
# Put your menu items here.
# e.g.
# m.resource :my_resource, :engine => :my_engine
end
<file_sep># This migration comes from sop_core_models_engine (originally 20120312104804)
class AddActivationFieldsToUser < ActiveRecord::Migration
def change
add_column :users, :activated, :boolean, :default => true
add_column :users, :activation_token, :string, :limit => 40
add_index :users, :activation_token
User.update_all(:activated => true)
end
end
<file_sep>require 'spec_helper'
describe Timecop2::ProjectsController do
it { should restfully_respond :for => :business }
end
<file_sep>Bundler.require
module Timecop2
class Engine < ::Rails::Engine
config.after_initialize do
Dir[root.join('lib/timecop2/settings/**/*.rb')].each { |f| require f }
end
# Include engine specific extensions to sop core models
require 'timecop2/mixins/sop_authentication/signup'
require 'timecop2/mixins/sop_authentication/signup_wizard'
initializer 'sop_authentication_extensions' do
ActionDispatch::Reloader.to_prepare do
SopAuthentication::Signup.send(:include, Timecop2::Mixins::SopAuthentication::Signup)
SopAuthentication::SignupWizard.send(:include, Timecop2::Mixins::SopAuthentication::SignupWizard)
end
end
# Include engine specific extensions to sop core models
require 'timecop2/mixins/user'
require 'timecop2/mixins/business'
initializer 'sop_core_models_extensions' do
ActionDispatch::Reloader.to_prepare do
::User.send(:include, Timecop2::Mixins::User)
::Business.send(:include, Timecop2::Mixins::Business)
end
end
# Autoload from the lib directory
config.autoload_paths << File.expand_path('../../', __FILE__)
isolate_namespace Timecop2
end
end
<file_sep>require 'spec_helper'
describe Timecop2::JobsController do
it { should restfully_respond :for => :business }
end
<file_sep>require 'spec_helper'
describe Timecop2::Mixins::SopAuthentication::SignupWizard do
subject { SopAuthentication::SignupWizard.new(SopAuthentication::Signup.new) }
it { should be_a Timecop2::Mixins::SopAuthentication::SignupWizard }
end
<file_sep>require 'spec_helper'
describe 'timecop2/jobs/index' do
before :each do
assigns[:jobs] = Timecop2::Job.scoped
build_ui 'timecop2/jobs/index'
end
subject { ui }
it { should have_child :grid_dialog_pattern }
describe 'the Grid Dialog Pattern' do
before(:each) { @grid_dialog_pattern = ui.children_of_type(:grid_dialog_pattern).first }
subject { @grid_dialog_pattern }
its(:model) { should be_a Timecop2::Job }
end
end
<file_sep>require 'timecop2/menu'<file_sep>class Timecop2::Dependencies < SopSupport::Dependencies::Definition
# Example dependency definition
# dependency :example_dependency do |actual|
# 'attach' given actual object here..
# end
end
<file_sep>Timecop2::Engine.routes.draw do
resources :jobs
resources :projects
resources :people
end
<file_sep># This migration comes from sop_settings (originally 20120312142316)
class AddBusinessSubscriptions < ActiveRecord::Migration
def change
create_table :sop_settings_service_subscriptions do |t|
t.references :business
t.string :service_uid
t.timestamps
end
end
end
<file_sep>module Timecop2
class Project < ActiveRecord::Base
belongs_to :business
belongs_to :person
has_many :jobs
attr_accessible :budget, :done, :name, :notes
grid_data_is :name, :budget, :done
def formatted
name
end
end
end
<file_sep>= Timecop2
This project rocks and uses The SageOne Platform.<file_sep># This migration comes from sop_core_models_engine (originally 20111206120032)
class AddHasAccessToUser < ActiveRecord::Migration
def change
add_column :users, :has_access, :boolean, :default => true
end
end
<file_sep>require 'spec_helper'
describe Timecop2::Project do
describe :relationships do
it { should belong_to :person }
it { should have_many :jobs }
end
describe :presentation do
it { should have_grid_data :name, :budget, :done }
end
end
<file_sep>class CreateTimecop2People < ActiveRecord::Migration
def change
create_table :timecop2_people do |t|
t.references :business
t.string :name
t.string :gender
t.string :phone
t.timestamps
end
add_index :timecop2_people, :business_id
end
end
<file_sep>module Timecop2
class JobsController < Timecop2::ApplicationController
restfully_responds :for => :business
end
end
<file_sep>require 'spec_helper'
describe Timecop2::PeopleController do
it { should restfully_respond :for => :business }
end
<file_sep>require 'spec_helper'
describe Timecop2::Mixins::SopAuthentication::Signup do
subject { SopAuthentication::Signup.new }
it { should be_a Timecop2::Mixins::SopAuthentication::Signup }
end
|
4b58e2e481506103ae0aaac1ae32093bd2eda3f2
|
[
"JavaScript",
"RDoc",
"Ruby"
] | 32 |
Ruby
|
celeduc/timecop2
|
6795d2ad1a6e9cacc13ad3db146152bde6542674
|
dc69d72972e4ad057ee2a7532b1f8f43ec764ea8
|
refs/heads/master
|
<repo_name>sentervip/nrf52832sdk15.0.0<file_sep>/nRF5_SDK_15.0.0_a53641a/examples/ble_peripheral/tutorial_ble_app_uart.noAdc/app_getData.h
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nrf.h"
#include "nrf_drv_saadc.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_timer.h"
#include "boards.h"
#include "app_error.h"
#include "nrf_delay.h"
#include "app_util_platform.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include <nrf_delay.h>
#define SAMPLES_IN_BUFFER 5
void saadc_init(void);
void saadc_sampling_event_init(void);
void saadc_sampling_event_enable(void);
<file_sep>/nRF5_SDK_15.0.0_a53641a/examples/ble_peripheral/tutorial_ble_app_uart/app_getData.h
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nrf.h"
#include "nrf_drv_saadc.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_timer.h"
#include "boards.h"
#include "app_error.h"
#include "nrf_delay.h"
#include "app_util_platform.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include <nrf_delay.h>
//spi
#define SPI2APP_CACHE 1
#define SPI2APP 1
#define CAP_ONE_TIME_BUF_LEN (1952*2) //1952
#define MAX_SPI_BUF 244 //244
#define MAX_SPI2APP_CNT (CAP_ONE_TIME_BUF_LEN / MAX_SPI_BUF )
#define SPI_INSTANCE 0 /**< SPI instance index. */
//ble
#define N_CAP_NODE 4
#define MAX_BLE_BUF 244 //MAX_SPI_BUF
#define MAX_BLE2APP_CNT (CAP_ONE_TIME_BUF_LEN /MAX_BLE_BUF)
//sadc
#define ENABLE 1
#define DISABLE 0
#define SAMPLES_IN_BUFFER 4
typedef enum{
LEVEL1=1,
LEVEL2=2,
LEVEL3=4,
LEVEL4=8,
ALL_LEVEL=0x3f
}tagCapLevel;
typedef enum{
RESET_CAP,
RESET_ALL,
STOP_CAP,
START_CAP,
DISABLE_ADC,
ENABLE_ADC,
}tagCapCmd;
typedef struct{
nrf_drv_timer_t timer;
nrf_saadc_value_t buf[SAMPLES_IN_BUFFER];
nrf_ppi_channel_t ppiChannel;
uint8_t locked;
uint8_t levelEnable;
int16_t * pLevelData;
}TagAppAdc;
extern TagAppAdc g_str_app_adc;
extern uint8_t g_CurrentLevel ;
extern int16_t g_levelData[2][N_CAP_NODE];
extern uint8_t g_save[];
void saadc_init(void);
int16_t saadc_getData(void);
void saadc_sampling_event_init(void);
void saadc_sampling_event_enable(void);
void saadc_sampling_event_disable(void);
extern void captrue_cmd(uint8_t type);
<file_sep>/nRF5_SDK_15.0.0_a53641a/examples/ble_peripheral/tutorial_ble_app_uart/app_getData.c
#include "app_getData.h"
//static const nrf_drv_timer_t m_timer = NRF_DRV_TIMER_INSTANCE(1);
//static nrf_saadc_value_t m_buffer_pool[2][SAMPLES_IN_BUFFER];
//static nrf_ppi_channel_t m_ppi_channel;
//static uint32_t m_adc_evt_counter;
extern uint8_t g_CapFlag;
//sadc预设值和实际值
int16_t g_levelData[2][N_CAP_NODE] ={{0},{0}};
uint8_t g_CurrentLevel = 0;
TagAppAdc g_str_app_adc = {NRF_DRV_TIMER_INSTANCE(1),{0},NRF_PPI_CHANNEL0,0,0, &g_levelData[0][0]};
void timer_handler(nrf_timer_event_t event_type, void * p_context)
{
}
void saadc_sampling_event_init(void)
{
ret_code_t err_code;
err_code = nrf_drv_ppi_init();
APP_ERROR_CHECK(err_code);
nrf_drv_timer_config_t timer_cfg = NRF_DRV_TIMER_DEFAULT_CONFIG;
timer_cfg.bit_width = NRF_TIMER_BIT_WIDTH_32;
err_code = nrf_drv_timer_init(&g_str_app_adc.timer, &timer_cfg, timer_handler);
APP_ERROR_CHECK(err_code);
/* setup m_timer for compare event every 400ms */
uint32_t ticks = nrf_drv_timer_ms_to_ticks(&g_str_app_adc.timer, 40); //400
nrf_drv_timer_extended_compare(&g_str_app_adc.timer,
NRF_TIMER_CC_CHANNEL0,
ticks,
NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK,
false);
//nrf_drv_timer_enable(&g_str_app_adc.timer); //by aizj
uint32_t timer_compare_event_addr = nrf_drv_timer_compare_event_address_get(&g_str_app_adc.timer,
NRF_TIMER_CC_CHANNEL0);
uint32_t saadc_sample_task_addr = nrf_drv_saadc_sample_task_get();
/* setup ppi channel so that timer compare event is triggering sample task in SAADC */
err_code = nrf_drv_ppi_channel_alloc(&g_str_app_adc.ppiChannel);
APP_ERROR_CHECK(err_code);
err_code = nrf_drv_ppi_channel_assign(g_str_app_adc.ppiChannel,
timer_compare_event_addr,
saadc_sample_task_addr);
APP_ERROR_CHECK(err_code);
}
void saadc_sampling_event_enable(void)
{
ret_code_t err_code = nrf_drv_ppi_channel_enable(g_str_app_adc.ppiChannel);
APP_ERROR_CHECK(err_code);
}
void saadc_sampling_event_disable(void)
{
ret_code_t err_code = nrf_drv_ppi_channel_disable(g_str_app_adc.ppiChannel);
APP_ERROR_CHECK(err_code);
}
void saadc_callback(nrf_drv_saadc_evt_t const * p_event)
{
if (p_event->type == NRF_DRV_SAADC_EVT_DONE && !g_str_app_adc.locked) //采集完成
{
ret_code_t err_code;
err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, SAMPLES_IN_BUFFER);
APP_ERROR_CHECK(err_code);
//calc level
int16_t aver = p_event->data.done.p_buffer[0]; //+ p_event->data.done.p_buffer[1]) >>1;
int16_t tmp;
for(int i=0; i<N_CAP_NODE;i++){
if( !(g_str_app_adc.levelEnable & 1<<i)){
tmp = g_levelData[0][i];
if( aver >=( g_levelData[0][i] - (tmp/(2<<i))) && aver <= (g_levelData[0][i] + (tmp/(2<<i))) ){
captrue_cmd(START_CAP);
captrue_cmd(DISABLE_ADC);
g_str_app_adc.levelEnable |= (1<<i);
g_levelData[1][i] = aver;
g_CurrentLevel = i;
// NRF_LOG_INFO("cap level[%d]:%d",i,aver);
printf("cap level[%d]:%d",i,aver);
}
}
}
//NRF_LOG_INFO("adc: %d",aver);
}
}
void saadc_init(void)
{
ret_code_t err_code;
nrf_saadc_channel_config_t channel_config =
NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN6);
err_code = nrf_drv_saadc_init(NULL, saadc_callback);
APP_ERROR_CHECK(err_code);
err_code = nrf_drv_saadc_channel_init(0, &channel_config);
APP_ERROR_CHECK(err_code);
err_code = nrf_drv_saadc_buffer_convert(g_str_app_adc.buf, SAMPLES_IN_BUFFER);
APP_ERROR_CHECK(err_code);
// err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[1], SAMPLES_IN_BUFFER);
// APP_ERROR_CHECK(err_code); // mask by aizj
}
void saadc_callback2(nrf_drv_saadc_evt_t const * p_event)
{
}
void saadc_init2(void)
{
ret_code_t err_code;
nrf_saadc_channel_config_t channel_config =
NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE_Z1(NRF_SAADC_INPUT_AIN6);
err_code = nrf_drv_saadc_init(NULL, saadc_callback2);
APP_ERROR_CHECK(err_code);
err_code = nrf_drv_saadc_channel_init(0, &channel_config);
APP_ERROR_CHECK(err_code);
}
int16_t saadc_getData(void)
{
ret_code_t err_code;
for(int i=0;i<1;i++){
err_code = nrfx_saadc_sample_convert(NRF_SAADC_INPUT_AIN6,&g_levelData[0][i]);
APP_ERROR_CHECK(err_code);
//g_levelData[0][0] = g_levelData[0][0]*3/1024;
//NRF_LOG_INFO("adc: %d,code=%d",g_levelData[0][i],err_code);
//printf("adc: %d,code=%d\n",g_levelData[0][i],err_code);
}
return g_levelData[0][0];
}
|
b056d5e684921be7c6c92db2be5c2e7bb442196b
|
[
"C"
] | 3 |
C
|
sentervip/nrf52832sdk15.0.0
|
816cad7c0c2c1ebf271bc099554eaf17482bb8b9
|
bcab56a73b780b08d8968a5b53a70bb121910497
|
refs/heads/master
|
<file_sep>enum ActionType {
ADD_ORDER = 'addOrder',
REMOVE_ORDER = 'removeOrder',
}
export default ActionType;
<file_sep>import { createStore } from 'vuex';
import { MenuItem } from '@/interface/MenuItem';
import { OrderItem } from '@/interface/OrderItem';
import menuData from '@/data/menu.json';
import MutationType from '@/store/MutationType';
import { Order } from '@/interface/Order';
export default createStore({
state: {
menuItems: menuData as unknown as Array<MenuItem>,
orderItems: Array<OrderItem>(),
order: null,
},
mutations: {
setMenuItems(state, menuItems) {
state.menuItems = menuItems;
},
insertOrderItem(state, newOrder: OrderItem) {
state.orderItems.push(newOrder);
},
updateOrderItem(state, newOrder) {
const currentOrder = state.orderItems.find((item) => item.name === newOrder.name);
Object.assign(currentOrder, newOrder);
},
deleteOrderItem(state, orderName) {
state.orderItems = state.orderItems.filter((orderItem) => orderItem.name !== orderName);
},
addOrder(state, order) {
state.order = order;
},
},
actions: {
addOrder(context, newOrder: OrderItem) {
const currentOrder = this.state.orderItems
.find((orderItem) => orderItem.name === newOrder.name);
if (currentOrder === undefined) {
const temp = newOrder;
temp.quantity = 1;
context.commit(MutationType.INSERT_ORDER_ITEM, newOrder);
} else {
currentOrder.quantity += 1;
context.commit(MutationType.UPDATE_ORDER_ITEM, newOrder);
}
},
removeOrder(context, orderName: string) {
context.commit(MutationType.DELETE_ORDER_ITEM, orderName);
},
finalizeOrder(context, order: Order) {
context.commit(MutationType.ADD_ORDER, order);
},
},
});
<file_sep>import { OrderItem } from './OrderItem';
export interface Order {
customerName: string;
tableNumber: number;
menus: Array<OrderItem>;
createdTime: Date;
}
<file_sep>export interface OrderItem {
name: string;
quantity: number;
individualPrice: number;
notes: string;
}
<file_sep>enum MutationType {
INSERT_ORDER_ITEM = 'insertOrderItem',
UPDATE_ORDER_ITEM = 'updateOrderItem',
DELETE_ORDER_ITEM = 'deleteOrderItem',
ADD_ORDER = 'updateOrder'
}
export default MutationType;
|
b8be4faad0012b5264e0d3cb18ccf4e7dd04adfc
|
[
"TypeScript"
] | 5 |
TypeScript
|
ilhamdcp/pos-desktop-app
|
565e9f872faf4c3bc85399409576871f5eaeaa96
|
c2b8635f4a8713563a0b77984b4b9338bd74fcf0
|
refs/heads/master
|
<repo_name>nullworks/co-library<file_sep>/src/Test.cpp
#include "co/UrlEncoding.hpp"
#include "co/HttpRequest.hpp"
#include "co/OnlineService.hpp"
#include <iostream>
#include <thread>
#include <chrono>
void urlEncodingTest()
{
std::cout << "URL ENCODING TEST\n";
std::cout << co::urlEncode("This is a testing string! '*'") << '\n';
std::cout << co::urlDecode(co::urlEncode("Testing -.*.-()()()")) << '\n';
std::cout << co::urlDecode("Testing+string+with+spaces") << '\n';
}
void queryStringTest()
{
std::cout << "QUERYSTRING TEST\n";
co::UrlEncodedBody body{};
body.add("test", "testing");
// body.add("testing key", "! TESTING VALUE ***");
body.add("=", "&");
std::cout << std::string(body) << '\n';
}
void requestSerializeTest()
{
std::cout << "HTTP REQUEST PARSING TEST\n";
co::HttpRequest rq("POST", "localhost", 8000, "/testing url", "E=E");
rq.addHeader("Content-Type", "application/json");
rq.setBody("{\"test\":true}");
auto vec = rq.serialize();
std::cout << std::string(vec.begin(), vec.end()) << '\n';
}
void httpRequestTest()
{
std::cout << "HTTP REQUEST/RESPONSE TEST\n";
co::HttpRequest rq("GET", "nullifiedcat.xyz", 80, "/", "");
co::NonBlockingHttpRequest nrq(rq);
try
{
nrq.send();
while (!nrq.update())
;
auto response = nrq.getResponse();
std::cout << "Got response: " << response.getStatus() << "\n" << response.getBody() << "\n";
std::cout << "Date: " << response.getHeader("Date") << '\n';
}
catch (std::exception &e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
void onlineServiceTest()
{
co::OnlineService service{};
service.setHost("localhost:8000");
service.setErrorHandler([](std::string error) { std::cout << "API Error: " << error << '\n'; });
service.login("<PASSWORD>", [](co::ApiCallResult result, std::optional<co::logged_in_user> user) {
if (user.has_value())
std::cout << "Logged in as " << user->username << '\n';
else
std::cout << "Error logging in\n";
});
service.userIdentify({ 123456 }, [](co::ApiCallResult result, std::optional<co::identified_user_group> group) {
if (!group.has_value())
{
std::cout << "Error while identifying users..\n";
return;
}
for (auto &u : group->users)
{
std::cout << "Steam3: " << u.first << ": " << u.second.username << "\n";
std::cout << "Groups: \n";
for (auto &r : u.second.groups)
{
std::cout << '\t' << r.name << " (" << (r.display_name.has_value() ? *r.display_name : "<none>") << ")\n";
}
std::cout << "Uses " << (u.second.uses_software.has_value() ? (u.second.uses_software->name) : "unknown software") << "\n";
}
});
service.gameStartup(123456);
while (true)
{
// Somewhere in game loop
// Non-blocking function
service.processPendingCalls();
using namespace std::chrono_literals;
std::this_thread::sleep_for(1s);
}
}
int main()
{
onlineServiceTest();
return 0;
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(cathook-online)
set(CMAKE_CXX_STANDARD 17)
add_library(co-library STATIC "")
add_executable(co-test "")
target_include_directories(co-library PRIVATE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include/co>)
target_include_directories(co-library PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>)
set_target_properties(co-library PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
set_target_properties(co-test PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
target_compile_definitions(co-library PRIVATE
_GLIBCXX_USE_CXX11_ABI=0)
target_compile_definitions(co-test PRIVATE
_GLIBCXX_USE_CXX11_ABI=0)
target_link_libraries(co-test co-library)
add_subdirectory(include)
add_subdirectory(src)<file_sep>/include/co/UrlEncoding.hpp
#pragma once
#include <string>
namespace co
{
std::string urlEncode(const std::string &input);
std::string urlDecode(const std::string &input);
} // namespace co<file_sep>/include/co/OnlineService.hpp
#pragma once
#include <string>
#include <vector>
#include <functional>
#include <memory>
#include <optional>
#include "HttpRequest.hpp"
#include "json.hpp"
namespace co
{
enum class ApiCallResult
{
OK,
BAD_REQUEST,
UNAUTHORIZED,
FORBIDDEN,
NOT_FOUND,
CONFLICT,
TOO_MANY_REQUESTS,
SERVER_ERROR,
UNKNOWN
};
struct group
{
group(const nlohmann::json &);
std::string name;
std::optional<std::string> display_name;
};
struct software
{
software(const nlohmann::json &);
std::string name;
bool friendly;
};
struct identified_user
{
identified_user(const nlohmann::json &);
std::string username;
bool steamid_verified;
std::optional<std::string> color;
std::vector<group> groups;
std::optional<software> uses_software;
};
struct identified_user_group
{
identified_user_group(const nlohmann::json &);
std::unordered_map<unsigned, identified_user> users{};
};
struct logged_in_user
{
logged_in_user(const nlohmann::json &);
std::string username;
};
class OnlineService
{
public:
using error_handler_type = std::function<void(std::string)>;
void setHost(std::string host);
void setErrorHandler(error_handler_type handler);
void login(std::string key, std::function<void(ApiCallResult, std::optional<logged_in_user>)> callback);
void gameStartup(unsigned steamId);
void userIdentify(const std::vector<unsigned> &steamIdList, std::function<void(ApiCallResult, std::optional<identified_user_group>)> callback);
void processPendingCalls();
protected:
using callback_type = std::function<void(ApiCallResult, HttpResponse &)>;
using pair_type = std::pair<std::unique_ptr<NonBlockingHttpRequest>, callback_type>;
void makeRequest(HttpRequest rq, callback_type callback);
static ApiCallResult resultFromStatus(int status);
void error(std::string message);
std::string host_address{};
int host_port{};
bool loggedIn{ false };
std::string api_key{};
std::vector<pair_type> pendingCalls{};
error_handler_type error_handler{ nullptr };
};
} // namespace co<file_sep>/src/co/CMakeLists.txt
target_sources(co-library PRIVATE
"${CMAKE_CURRENT_LIST_DIR}/UrlEncoding.cpp"
"${CMAKE_CURRENT_LIST_DIR}/HttpRequest.cpp"
"${CMAKE_CURRENT_LIST_DIR}/OnlineService.cpp")<file_sep>/src/co/HttpRequest.cpp
#include "HttpRequest.hpp"
#include "UrlEncoding.hpp"
#include <sstream>
#include <stdio.h>
#include <cstdlib>
#include <unistd.h>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
namespace co
{
HttpResponse::HttpResponse(const std::vector<char> &data)
{
std::ostringstream message{};
for (size_t i = 0; i < data.size(); ++i)
{
if (data[i] == '\r' && (i < data.size() - 1) && data[i + 1] == '\n')
{
// \r\n\r\n, body begins
if (message.str().empty())
{
body = std::string(data.begin() + i + 2, data.end());
return;
}
else
{
if (!got_status)
{
parseStatus(message.str());
got_status = true;
}
else
{
parseHeader(message.str());
}
}
message.str("");
++i;
}
else
{
message << data[i];
}
}
}
std::string HttpResponse::getHeader(const std::string &key) const
{
std::string key_lower = key;
for (auto &i : key_lower)
i = std::tolower(i);
if (headers.find(key_lower) == headers.end())
return "";
return headers.at(key_lower);
}
int HttpResponse::getStatus() const
{
return status;
}
std::string HttpResponse::getBody() const
{
return body;
}
void HttpResponse::parseStatus(std::string message)
{
std::istringstream ss{ message };
std::string version;
ss >> version;
ss >> status;
}
void HttpResponse::parseHeader(std::string message)
{
std::string key;
std::string value;
auto colon = message.find(':');
if (colon == std::string::npos)
throw new std::runtime_error("Malformed header");
key = message.substr(0, colon);
auto start = message.find_first_not_of(' ', colon + 1);
if (start == std::string::npos)
value = "";
else
value = message.substr(start);
for (char &c : key)
c = std::tolower(c);
headers[key] = value;
}
void UrlEncodedBody::add(const std::string &key, const std::string &value)
{
pairs.push_back(std::make_pair(key, value));
}
UrlEncodedBody::operator std::string() const
{
std::ostringstream stream{};
bool first{ true };
for (const auto &p : pairs)
{
if (!first)
stream << '&';
else
first = false;
stream << urlEncode(p.first) << '=' << urlEncode(p.second);
}
return stream.str();
}
HttpRequest::HttpRequest(std::string method, std::string host, int port, std::string path, std::string query) : method(method), host(host), port(port), address(path), query(query)
{
addHeader("Host", port == 80 ? host : host + ":" + std::to_string(port));
}
void HttpRequest::addHeader(const std::string &key, const std::string &value)
{
headers[key] = value;
}
void HttpRequest::setBody(const std::string &body)
{
addHeader("Content-Length", std::to_string(body.size()));
this->body = body;
}
std::vector<char> HttpRequest::serialize() const
{
std::ostringstream stream{};
stream << method << ' ' << address;
if (query.size())
stream << '?' << query;
stream << " HTTP/1.0\r\n";
for (const auto &p : headers)
{
stream << p.first << ": " << p.second << "\r\n";
}
stream << "\r\n" << body;
std::string result = stream.str();
return std::vector<char>(result.begin(), result.end());
}
NonBlockingHttpRequest::NonBlockingHttpRequest(const HttpRequest &request)
{
this->request = request.serialize();
port = request.port;
host = request.host;
send();
}
void NonBlockingHttpRequest::send()
{
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
throw std::runtime_error("Failed to open the socket: " + std::to_string(errno));
hostent *host = gethostbyname(this->host.c_str());
if (host == nullptr)
throw std::runtime_error("Failed to locate the host: " + std::to_string(errno));
sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
memcpy(&server.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
if (connect(sock, (sockaddr *) &server, sizeof(server)) < 0)
throw std::runtime_error("Could not connect to server: " + std::to_string(errno));
int sent = 0;
int total = request.size();
do
{
int s = write(sock, request.data() + sent, total - sent);
if (s < 0)
throw std::runtime_error("Could not write to socket: " + std::to_string(errno));
if (s == 0)
break;
sent += s;
} while (sent < total);
fcntl(sock, F_SETFL, O_NONBLOCK);
}
bool NonBlockingHttpRequest::update()
{
if (finished)
return true;
while (true)
{
size_t f = response.size() - received;
if (f < 512)
response.resize(response.size() + 1024);
f += 512;
int r = read(sock, response.data() + received, f);
if (r < 0)
{
if (errno == EAGAIN)
return false;
else
throw std::runtime_error("Could not read from socket: " + std::to_string(errno));
}
if (r == 0)
{
finished = true;
return true;
}
received += r;
}
}
HttpResponse NonBlockingHttpRequest::getResponse()
{
return HttpResponse(std::vector<char>(response.begin(), response.begin() + received));
}
} // namespace co<file_sep>/src/co/UrlEncoding.cpp
#include "UrlEncoding.hpp"
#include <sstream>
#include <iomanip>
unsigned char hexToChar(char i)
{
if (i >= '0' && i <= '9')
return i - '0';
if (i >= 'a' && i <= 'f')
return i - 'a' + 10;
if (i >= 'A' && i <= 'F')
return i - 'A' + 10;
return 0;
}
namespace co
{
std::string urlEncode(const std::string &input)
{
std::ostringstream stream{};
for (auto i : input)
{
if (std::isalnum(i) || i == '-' || i == '_' || i == '.' || i == '~')
stream << i;
else
stream << '%' << std::uppercase << std::hex << std::setw(2) << unsigned(i) << std::nouppercase;
}
return stream.str();
}
std::string urlDecode(const std::string &input)
{
std::ostringstream stream{};
std::istringstream inputStream{ input };
char c;
while (inputStream.get(c))
{
if (c == '+')
stream << ' ';
else if (c == '%')
{
char result = 0;
char c1;
char c2;
inputStream >> c1 >> c2;
result |= (hexToChar(c1) << 4) | hexToChar(c2);
stream << result;
}
else
stream << c;
}
return stream.str();
}
} // namespace co<file_sep>/src/co/OnlineService.cpp
#include "OnlineService.hpp"
#include "json.hpp"
namespace co
{
group::group(const nlohmann::json &json)
{
name = json["name"].get<std::string>();
if (json["display"].is_null())
display_name = std::nullopt;
else
display_name = json["display"].get<std::string>();
}
software::software(const nlohmann::json &json)
{
name = json["name"].get<std::string>();
friendly = json["friendly"].get<bool>();
}
identified_user::identified_user(const nlohmann::json &json)
{
username = json["username"].get<std::string>();
steamid_verified = json["verified"].get<bool>();
if (json["color"].is_null())
color = std::nullopt;
else
color = json["color"].get<std::string>();
for (auto &e : json["groups"])
{
groups.emplace_back(e);
}
if (json["software"].is_null())
uses_software = std::nullopt;
else
uses_software = co::software{ json["software"] };
}
identified_user_group::identified_user_group(const nlohmann::json &json)
{
for (auto it = json.begin(); it != json.end(); ++it)
{
unsigned steamId;
try
{
steamId = std::stoul(it.key());
}
catch (std::invalid_argument)
{
return;
}
users.emplace(steamId, identified_user{ it.value() });
}
}
logged_in_user::logged_in_user(const nlohmann::json &json)
{
username = json["username"].get<std::string>();
}
void OnlineService::makeRequest(HttpRequest rq, callback_type callback)
{
pendingCalls.emplace_back(std::make_unique<NonBlockingHttpRequest>(rq), std::move(callback));
}
void OnlineService::processPendingCalls()
{
if (pendingCalls.empty())
return;
for (auto i = 0u; i < pendingCalls.size(); ++i)
{
if (pendingCalls[i].first->update())
{
auto response = pendingCalls[i].first->getResponse();
ApiCallResult result = resultFromStatus(response.getStatus());
if (pendingCalls[i].second)
pendingCalls[i].second(result, response);
pendingCalls.erase(pendingCalls.begin() + i);
--i;
}
}
}
void OnlineService::setHost(std::string host)
{
auto colon = host.find(':');
if (colon != std::string::npos)
host_port = std::stoi(host.substr(colon + 1));
else
host_port = 80;
host_address = host.substr(0, colon);
// DEBUG
printf("Host = %s, port = %d\n", host_address.c_str(), host_port);
}
void OnlineService::setErrorHandler(error_handler_type handler)
{
error_handler = handler;
}
void OnlineService::error(std::string message)
{
if (error_handler)
error_handler(message);
}
ApiCallResult OnlineService::resultFromStatus(int status)
{
if (status >= 200 && status < 300)
return ApiCallResult::OK;
if (status >= 500)
return ApiCallResult::SERVER_ERROR;
if (status == 400)
return ApiCallResult::BAD_REQUEST;
if (status == 401)
return ApiCallResult::UNAUTHORIZED;
if (status == 403)
return ApiCallResult::FORBIDDEN;
if (status == 404)
return ApiCallResult::NOT_FOUND;
if (status == 409)
return ApiCallResult::CONFLICT;
if (status == 429)
return ApiCallResult::TOO_MANY_REQUESTS;
return ApiCallResult::UNKNOWN;
}
void OnlineService::login(std::string key, std::function<void(ApiCallResult, std::optional<logged_in_user>)> callback)
{
UrlEncodedBody body{};
body.add("key", key);
HttpRequest request("GET", host_address, host_port, "/user/me", body);
api_key = key;
makeRequest(request, [this, callback](ApiCallResult result, HttpResponse &response) {
std::optional<logged_in_user> user = std::nullopt;
if (result == ApiCallResult::OK)
{
auto j = nlohmann::json::parse(response.getBody());
user = logged_in_user{ j };
}
callback(result, user);
});
}
void OnlineService::userIdentify(const std::vector<unsigned> &steamIdList, std::function<void(ApiCallResult, std::optional<identified_user_group>)> callback)
{
std::ostringstream stream{};
bool first{ true };
for (auto &i : steamIdList)
{
if (!first)
stream << ',';
else
first = false;
stream << i;
}
UrlEncodedBody query{};
query.add("key", api_key);
query.add("ids", stream.str());
HttpRequest request("GET", host_address, host_port, "/game/identify", query);
makeRequest(request, [callback](ApiCallResult result, HttpResponse &response) {
if (result == ApiCallResult::OK)
{
auto json = nlohmann::json::parse(response.getBody());
callback(result, std::make_optional<identified_user_group>(json));
}
else
{
callback(result, std::nullopt);
}
});
}
void OnlineService::gameStartup(unsigned steamId)
{
UrlEncodedBody query{};
query.add("key", api_key);
query.add("steam", std::to_string(steamId));
HttpRequest request("POST", host_address, host_port, "/game/startup", query);
makeRequest(request, [](ApiCallResult result, HttpResponse &response) {});
}
} // namespace co
<file_sep>/include/co/CMakeLists.txt
target_sources(co-library PRIVATE
"${CMAKE_CURRENT_LIST_DIR}/UrlEncoding.hpp"
"${CMAKE_CURRENT_LIST_DIR}/HttpRequest.hpp"
"${CMAKE_CURRENT_LIST_DIR}/json.hpp"
"${CMAKE_CURRENT_LIST_DIR}/OnlineService.hpp")<file_sep>/src/CMakeLists.txt
target_sources(co-test PRIVATE
"${CMAKE_CURRENT_LIST_DIR}/Test.cpp")
add_subdirectory(co)<file_sep>/include/co/HttpRequest.hpp
#pragma once
#include <vector>
#include <string>
#include <unordered_map>
namespace co
{
class HttpResponse
{
public:
HttpResponse(const std::vector<char> &data);
std::string getHeader(const std::string &key) const;
int getStatus() const;
std::string getBody() const;
protected:
void parseStatus(std::string message);
void parseHeader(std::string message);
int status{};
bool got_status{ false };
std::unordered_map<std::string, std::string> headers{};
std::string body{};
};
class UrlEncodedBody
{
public:
void add(const std::string &key, const std::string &value);
operator std::string() const;
protected:
std::vector<std::pair<std::string, std::string>> pairs{};
};
class HttpRequest
{
public:
HttpRequest(std::string method, std::string host, int port, std::string path, std::string query);
void addHeader(const std::string &key, const std::string &value);
void setBody(const std::string &body);
std::vector<char> serialize() const;
const std::string method;
const std::string host;
const int port;
const std::string address;
const std::string query;
protected:
std::unordered_map<std::string, std::string> headers{};
std::string body{};
};
class NonBlockingHttpRequest
{
public:
NonBlockingHttpRequest(const HttpRequest &request);
void send();
bool update();
HttpResponse getResponse();
protected:
int port;
std::string host;
int sock{};
bool finished{ false };
int received{ 0 };
std::vector<char> request{};
std::vector<char> response{};
};
} // namespace co
|
6239d0cd6e9e2d6ce2af56606375ee53bea687f7
|
[
"CMake",
"C++"
] | 11 |
C++
|
nullworks/co-library
|
6d15c3e19acc233e63f7ce5eec085ba2621af127
|
55a51715d16d3d0f66fc8ec81787a9f71cd0f4bd
|
refs/heads/master
|
<repo_name>xiaoliang008/image-completion-using-GANs<file_sep>/old_files/loss/clean.sh
cat loss.csv |sed -e 's/\]//g' | sed -e 's/\[//g' > out
cp out loss.csv
<file_sep>/Dataset/Flower_Dataset/convert_images_to_numpy_pt1.py
import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
import glob
from PIL import Image
image_list = []
f=open('img_processed_pt1.log','w+')
for filename in glob.glob('/home/nishant.puri2577/data/jpg2/*'): #assuming gif
im=misc.imread(filename)
image_list.append(im)
print len(image_list)
train=image_list[0].reshape(12288)
for i in range(1,20000):
if(i%100==0):
f.write('images processed' + str(i))
f.write('\n')
f.flush()
train=np.vstack((train,image_list[i].reshape(12288)))
np.savetxt("train_pt1.csv", train, fmt='%i', delimiter=",")
<file_sep>/Dataset/Face_Dataset/create_random_val_set.py
from PIL import Image
import glob, os, sys
import scipy.misc
import numpy as np
count_test = 0
count_train = 0
test_folder = "/home/icarus/Documents/DCGAN_Tensorflow/FacesDataset/face_data_test/"
train_folder = "/home/icarus/Documents/DCGAN_Tensorflow/FacesDataset/face_data_train/"
for filename in glob.glob('/home/icarus/Documents/DCGAN_Tensorflow/FacesDataset/face_data/*'):
image = scipy.misc.imread(filename)
f, e = os.path.splitext(filename)
if (np.random.random() > 0.9):
count_test +=1
outname = test_folder + str(count_test) + e
else:
count_train +=1
outname = train_folder + str(count_train) + e
scipy.misc.imsave(outname, image)
<file_sep>/Dataset/Face_Dataset/ppm_to_jpg.py
from PIL import Image
import glob, os, sys
count = 0
print "aya"
for filename in glob.glob('/home/icarus/Documents/DCGAN_Tensorflow/FacesDataset/faces/*'):
f, e = os.path.splitext(filename)
outfile = f + ".jpg"
count += 1
print outfile
try:
Image.open(filename).save(outfile)
except IOError:
print "cannot convert" + filename
print count
<file_sep>/Nearest Neighbor Experiments/image_all_nn.py
import json
import collections
import numpy as np
from sklearn.decomposition import PCA
import matplotlib
#import utils
matplotlib.use('Agg')
from pylab import figure, axes, pie, title, show
import matplotlib.pyplot as plt
#import numpy as np
from scipy import misc
#import matplotlib.pyplot as plt
import glob
from PIL import Image
import pandas as pd
train=pd.read_csv("/home/nishant.puri2577/data/train_nparray/train.csv")
train=train.values
print train.shape
train=train.astype(np.uint8)
train=train/256.
image_list = []
for filename in glob.glob('/home/nishant.puri2577/data/generated_faces/*'):
im=misc.imread(filename)
image_list.append(im)
test=image_list[0].reshape(12288)
for i in range(1,len(image_list)):
test=np.vstack((test,image_list[i].reshape(12288)))
test=test/256.
cnt_test=test.shape[0]
cnt_train=train.shape[0]
train_sq_sum=np.sum(train*train,axis=1)
train_sq=np.repeat(train_sq_sum.reshape((1,train_sq_sum.shape[0])),cnt_test,axis=0)
test_sq_sum=np.sum(test*test,axis=1)
test_sq=np.repeat(test_sq_sum.reshape((test_sq_sum.shape[0],1)),cnt_train,axis=1)
c=train_sq+test_sq-2*test.dot(train.T)
closest_image_idx=np.argmin(c,1)
min_dist=np.min(c,1)
def closest_im(i):
plt.close()
plt.clf()
image=(test[i]*256).astype(np.uint8)
#show_sample(image)
image_nn=train[closest_image_idx[i],:]
l2_dist=np.sqrt(min_dist[i])
#print "l2 distance is: ", l2_dist
image_nn=(image_nn*256).astype(np.uint8)
#show_sample(image_nn)
image=image.reshape((64,64,3))
image_nn=image_nn.reshape((64,64,3))
plt.figure()
plt.suptitle('L2 distance: '+str(l2_dist),fontsize=16)
plt.figure(1)
plt.subplot(121)
plt.imshow(image)
plt.axis("off")
plt.title('Generated Image')
plt.subplot(122)
plt.imshow(image_nn)
plt.axis("off")
plt.title('Closest Neighbor')
#plt.suptitle('L2 distance: '+str(l2_dist),fontsize=16)
plt.savefig('gen_closest'+ str(i) + '_' + str(l2_dist) + '.png')
for i in range(len(image_list)):
closest_im(i)
<file_sep>/Dataset/Face_Dataset/crop_image_centers.py
from PIL import Image
import glob, os, sys
import scipy.misc
for filename in glob.glob('/home/icarus/Documents/DCGAN_Tensorflow/FacesDataset/data/celebA/*'):
image = scipy.misc.imread(filename)
f, e = os.path.splitext(filename)
outname = f + "_cropped" + e
im2 = scipy.misc.imresize(image[55:163, 30:148], [64,64])
scipy.misc.imsave(outname, im2)
<file_sep>/README.md
# Context-Aware Image Inpainting using Deep Convolutional Generative Adversarial Networks
Context Aware Image Inpainting aims to fill a region in an image based on the context of surrounding pixels. Given a mask, a network is trained to predict the content in the mask. The generated content needs to be well aligned with surrounding pixels and should look realistic based on the context. We plan to use Deep Convolutional Generative Adversarial Network (DCGAN) to generate realistic images along with scores of how realistic they are. The DCGANs output can then be used to reconstruct the whole image by solving the optimization problem of a proposed loss function.
## Implementation Details
- Dataset: [Oxford 102 Flower Category Dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/) |
[Download Link](https://www.dropbox.com/s/2n7qd2qq39hsmnw/jpg2.zip?dl=0)
- Framework: TensorFlow
- DCGAN Architecture: DCGAN model architecture inspired from [Radford et al](https://arxiv.org/pdf/1511.06434.pdf). The input is a noise vector, drawn from some well-known prior distribution (for example: a uniform distribution [−1, 1]), followed by a fully connected layer. This is followed by a series of fractionally-strided convolutions, where the numbers of channels are halved, and image dimension doubles from the previous layer. The output layer is of dimension equal to the size of the image space.
- Performance Measure: Qualitative

## Some Fun GIFs of our results -
These GIFs show our training process, from the first epoch to the end of training, for a given set of noise points


## Authors:
[<NAME>](https://github.com/aashima-arora239), [<NAME>](https://github.com/nishant-puri), [<NAME>](https://github.com/siddharthbhatnagar)
This is the course project for COMS 4995 - Deep Learning for Computer Vision
## References
* Goodfellow, Ian, et al. "Generative adversarial nets." Advances in neural information processing systems. 2014
* <NAME>, <NAME>, and <NAME>. "Unsupervised representation learning with deep convolutional generative adversarial networks." arXiv preprint arXiv:1511.06434 2015
* <NAME>, et al. "Improved techniques for training gans." Advances in Neural Information Processing Systems. 2016
* <NAME>, et al. "Semantic Image Inpainting with Perceptual and Contextual Losses." arXiv preprint arXiv:1607.07539 2016
* <NAME>, et al. "Infogan: Interpretable representation learning by information maximizing generative adversarial nets." Advances in Neural Information Processing Systems. 2016
* Denton, <NAME>., <NAME>, and <NAME>. "Deep Generative Image Models using a Laplacian Pyramid of Adversarial Networks." Advances in neural information processing systems. 2015
* https://github.com/jacobgil/keras-dcgan
* http://bamos.github.io/2016/08/09/deep-completion/
* https://github.com/soumith/dcgan.torch
* https://github.com/carpedm20/DCGAN-tensorflow
* https://github.com/rajathkumarmp/DCGAN
<file_sep>/image_completion.py
from __future__ import division
import os
import time
from glob import glob
import tensorflow as tf
from six.moves import xrange
import math
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import time as ti
import csv
import matplotlib.pyplot as plt
from pympler import asizeof
import time as ti
from PIL import Image
import scipy.misc
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
image_size = 64
image_shape = [image_size, image_size, 3]
img_width, img_height = 64, 64
data_dir = '../face_data_test_ic'
learning_rate= 0.0002
beta1= 0.5
batch_size=64
alpha = 0.2
lambda_val = 0.001
def preprocessing(image):
return image/127.5 - 1;
def minibatch_discrimination(input_tensor, name, num_kernels=100, kernel_dim=5):
with tf.variable_scope(name) as scope:
input_shape = input_tensor.get_shape().as_list()
print "input-shape" , input_shape
batch_size = input_shape[0]
print batch_size
features = input_shape[1]
print features
W = tf.get_variable("weight", [features, num_kernels * kernel_dim], initializer=tf.contrib.layers.xavier_initializer())
bias = tf.get_variable("bias", [num_kernels], initializer=tf.constant_initializer(0.0))
activation = tf.matmul(input_tensor,W)
print activation.get_shape()
activation = tf.reshape(activation,[-1,num_kernels,kernel_dim])
a1 = tf.expand_dims(activation, 3)
a2 = tf.transpose(activation, perm=[1,2,0])
a2 = tf.expand_dims(a2, 0)
abs_diff = tf.reduce_sum(tf.abs(a1 - a2), reduction_indices=[2])
expsum = tf.reduce_sum(tf.exp(-abs_diff), reduction_indices=[2])
expsum = expsum + bias
print expsum.get_shape()
return tf.concat([input_tensor,expsum],axis=1)
def gaussian_noise_layer(input_tensor, std=0.2):
noise = tf.random_normal(shape=tf.shape(input_tensor), mean=0.0, stddev=std, dtype=tf.float32)
return input_tensor + noise
def lrelu(x,alpha=0.2):
return tf.maximum(x, alpha*x)
def linear(input_tensor, input_dim, output_dim, name=None):
with tf.variable_scope(name):
weights = tf.get_variable("weights", [input_dim, output_dim], initializer=tf.truncated_normal_initializer(stddev=math.sqrt(3.0 / (input_dim + output_dim))))
bias = tf.get_variable("bias", [output_dim], initializer=tf.constant_initializer(0.0))
return tf.matmul(input_tensor, weights) + bias
def conv_2d(input_tensor, input_dim, output_dim, name=None):
with tf.variable_scope(name):
kernel = tf.get_variable("kernel", [5, 5,input_dim, output_dim], initializer=tf.truncated_normal_initializer(stddev=0.02))
bias = tf.get_variable("bias", [output_dim], initializer=tf.constant_initializer(0.0))
conv = tf.nn.conv2d(input_tensor, kernel, strides=[1, 2, 2, 1],padding='SAME')
return conv+bias
def conv_2dtranspose(input_tensor, input_dim, output_shape,name=None):
output_dim=output_shape[-1]
with tf.variable_scope(name):
kernel = tf.get_variable("kernel", [5, 5, output_dim, input_dim], initializer=tf.random_normal_initializer(stddev=0.02))
bias = tf.get_variable("bias", [output_dim], initializer=tf.constant_initializer(0.0))
deconv = tf.nn.conv2d_transpose(input_tensor, kernel, output_shape=output_shape, strides=[1, 2, 2, 1],padding='SAME')
return deconv+bias
def batch_norm(input_tensor,name,is_train=True):
return tf.contrib.layers.batch_norm(input_tensor,decay=0.9, updates_collections=None, epsilon=1e-5, scale=True,
is_training=is_train, scope=name)
load_img_datagen = ImageDataGenerator(preprocessing_function = preprocessing)
img_input = load_img_datagen.flow_from_directory(
data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None)
def generator(z):
l1=linear(input_tensor=z,name="g_lin", input_dim=100, output_dim=1024*4*4)
l2= tf.reshape(l1, [-1, 4, 4, 1024])
l3 = lrelu(batch_norm(input_tensor=l2,name="g_bn0"))
print l3
#conv1
l4=conv_2dtranspose(input_tensor=l3,name="g_c2dt1",input_dim=1024,output_shape=[batch_size,8,8,512])
l5=lrelu(batch_norm(input_tensor=l4,name="g_bn1"))
print l5
#conv2
l6=conv_2dtranspose(input_tensor=l5,name="g_c2dt2",input_dim=512,output_shape=[batch_size,16,16,256])
l7=lrelu(batch_norm(input_tensor=l6,name='g_bn2'))
print l7
#conv3
l8=conv_2dtranspose(input_tensor=l7,name='g_c2dt3',input_dim=256,output_shape=[batch_size,32,32,128])
l9=lrelu(batch_norm(input_tensor=l8,name='g_bn3'))
print l9
#conv4
l10=conv_2dtranspose(input_tensor=l9,name='g_c2dt4',input_dim=128,output_shape=[batch_size,64,64,3])
l11=tf.nn.tanh(l10)
print l11
return l11
def discriminator(images, reuse=False, alpha=0.2):
with tf.variable_scope("discriminator") as scope:
if reuse:
scope.reuse_variables()
#naming of the layers is as per layer number
#h0 conv2d no batch_norm
images = gaussian_noise_layer(images)
l1 = conv_2d(input_tensor=images, input_dim=3, output_dim= 64, name='d_c2d0')
l2 = lrelu(l1,alpha)
#h1 conv2d with batch_norm
l3 = conv_2d(input_tensor=l2, input_dim=64, output_dim=64*2, name='d_c2d1')
l4 = batch_norm(input_tensor=l3,name="d_bn1")
l5 = lrelu(l4,alpha)
#h2 conv2d with batch_norm
l6 = conv_2d(input_tensor=l5, input_dim=64*2, output_dim=64*4, name='d_c2d2')
l7 = batch_norm(input_tensor=l6,name="d_bn2")
l8 = lrelu(l7,alpha)
#h3 conv2d with batch_norm
l9 = conv_2d(input_tensor=l8, input_dim=64*4, output_dim=64*8, name='d_c2d3')
l10 = batch_norm(input_tensor=l9,name="d_bn3")
l11 = lrelu(l10,alpha)
#h4 reshape and linear
l12 = tf.reshape(l11, [-1, 8192]) #l12 = tf.reshape(l11, [32, -1]) #l12 = tf.reshape(l11, [64, -1])
l13 = minibatch_discrimination(l12,name="d_mini",num_kernels=100)
print l13.get_shape()
input_dim_linear = l13.get_shape().as_list()
l14 = linear(input_tensor=l13, input_dim=input_dim_linear[1], output_dim=1, name="d_lin4")
print l14.get_shape().as_list()
#sigmoid
#minibatch discrimination layer
l15 = tf.nn.sigmoid(l14)
print l15
return l15, l14
def merge_images(image_batch, size):
h,w = image_batch.shape[1], image_batch.shape[2]
c = image_batch.shape[3]
img = np.zeros((int(h*size[0]), w*size[1], c))
for idx, im in enumerate(image_batch):
i = idx % size[1]
j = idx // size[1]
img[j*h:j*h+h, i*w:i*w+w,:] = im
return img
def load(checkpoint_dir):
print(" [*] Reading checkpoints...")
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
return True
else:
return False
z = tf.placeholder(tf.float32, [None, 100], name='z')
G = generator(z)
images = tf.placeholder(
tf.float32, [None] + image_shape, name='real_images')
D1, D1_logits = discriminator(images, False, alpha)
D2, D2_logits = discriminator(G, True, alpha)
t_vars=tf.trainable_variables()
discrim_vars = [var for var in t_vars if 'd_' in var.name]
gen_vars = [var for var in t_vars if 'g_' in var.name]
discrim_loss_real_img = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D1_logits, labels=tf.scalar_mul(0.9,tf.ones_like(D1_logits))))
discrim_loss_fake_img = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D2_logits, labels=tf.zeros_like(D2_logits)))
discrim_loss = discrim_loss_real_img + discrim_loss_fake_img
gen_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=D2_logits, labels=tf.ones_like(D2_logits)))
dopt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(discrim_loss, var_list=discrim_vars)
gopt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(gen_loss, var_list=gen_vars)
saver = tf.train.Saver()
sess = tf.InteractiveSession()
isLoaded = load('models/')
mask = tf.placeholder(tf.float32, [None] + image_shape, name='mask')
imp_matrix = tf.placeholder(tf.float32, [None] + image_shape, name='imp_matrix')
contextual_loss = tf.reduce_sum(
tf.contrib.layers.flatten(
tf.multiply(tf.abs(tf.multiply(tf.cast(mask,tf.float32), tf.cast(G,tf.float32)) - tf.multiply(tf.cast(mask,tf.float32), tf.cast(images, tf.float32))),tf.cast(imp_matrix, tf.float32))), 1)
perceptual_loss = gen_loss
complete_loss = contextual_loss + lambda_val*perceptual_loss
grad_complete_loss = tf.gradients(complete_loss, z)
real_images=next(img_input)
batch_images = np.array(real_images).astype(np.float32)
img = (real_images[1,:,:,:] +1.)/2
plt.imshow(img)
plt.axis('on')
plt.show()
config = {}
config['maskType'] = 'center'
config['learning_rate'] = 0.01
config['momentum'] = 0.9
#get mask M
if config['maskType'] == 'random':
fraction_masked = 0.2
mask_ = np.ones(image_shape)
mask_[np.random.random(image_shape[:2]) < fraction_masked] = 0.0
elif config['maskType'] == 'center':
scale = 0.25
#assert(scale <= 0.5)
mask_ = np.ones(image_shape)
sz = image_size
l = int(image_size*scale)
u = int(image_size*(1.0-scale))
mask_[l:u, l:u, :] = 0.0
elif config['maskType'] == 'left':
mask_ = np.ones(image_shape)
c = image_size // 2
mask_[:,:c,:] = 0.0
elif config['maskType'] == 'full':
mask_ = np.ones(image_shape)
else:
assert(False)
#create the importance matrix
a=np.ones((64,64))
n=64
for k in range(1,16):
for i in range(k,n-k):
for j in range(k,n-k):
a[i,j]+=1
scale=0.25
image_size=64
sz = image_size
l = int(image_size*scale)
u = int(image_size*(1.0-scale))
a[l:u, l:u] = 0.0
non_zero_mean = np.sum(a)/(32*32)
importance_matrix = a/32
batch_mask = np.resize(mask_, [batch_size] + image_shape)
imp_mask = np.resize(importance_matrix, [batch_size] + image_shape)
zhats = np.random.uniform(-1, 1, size=(batch_size, 100))
vel = 0
for i in xrange(5000):
fd = {
z: zhats,
imp_matrix: imp_mask,
mask: batch_mask,
images: batch_images,
}
run = [complete_loss, grad_complete_loss, G]
loss, g, G_imgs = sess.run(run, feed_dict=fd)
if (i%500 is 0):
print "loss in iteration: " + str(i) + " is: " + str(np.mean(loss))
prev_vel = np.copy(vel)
vel = config['momentum']*vel - config['learning_rate']*g[0]
zhats += -config['momentum'] * prev_vel + (1+config['momentum'])*vel
zhats = np.clip(zhats, -1, 1)
created_images = (G_imgs + 1.)/2
im = merge_images(created_images, [8,8])
plt.imshow(im)
plt.axis('on')
plt.show()
masked_images = np.multiply(batch_images, batch_mask)
input_images = (masked_images + 1.)/2
im = merge_images(input_images, [8,8])
plt.imshow(im)
plt.axis('on')
plt.show()
inv_mask_ = 1- mask_
inv_batch_mask = np.resize(inv_mask_, [batch_size] + image_shape)
inv_masked_images = np.multiply(batch_images, inv_batch_mask)
inv_input_images = (inv_masked_images + 1.)/2
im_ = merge_images(inv_input_images, [8,8])
plt.imshow(im_)
plt.axis('on')
plt.show()
inv_batch_mask = np.resize(inv_mask_, [batch_size] + image_shape)
inv_masked_images = np.multiply(G_imgs, inv_batch_mask)
Recons_img = inv_masked_images + masked_images
rec_images = (Recons_img + 1.)/2
im_r = merge_images(rec_images, [8,8])
plt.imshow(im_r)
plt.axis('on')
plt.show()
<file_sep>/dcgan.py
#imports
import math
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import time as ti
import csv
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pympler import asizeof
import time as ti
from PIL import Image
import scipy.misc
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
def lrelu(x,alpha):
return tf.maximum(x, alpha*x)
def linear(input_tensor, input_dim, output_dim, name=None):
with tf.variable_scope(name):
weights = tf.get_variable("weights", [input_dim, output_dim], initializer=tf.truncated_normal_initializer(stddev=math.sqrt(3.0 / (input_dim + output_dim))))
bias = tf.get_variable("bias", [output_dim], initializer=tf.constant_initializer(0.0))
return tf.matmul(input_tensor, weights) + bias
def conv_2d(input_tensor, input_dim, output_dim, name=None):
with tf.variable_scope(name):
kernel = tf.get_variable("kernel", [5, 5,input_dim, output_dim], initializer=tf.truncated_normal_initializer(stddev=0.02))
bias = tf.get_variable("bias", [output_dim], initializer=tf.constant_initializer(0.0))
conv = tf.nn.conv2d(input_tensor, kernel, strides=[1, 2, 2, 1],padding='SAME')
return conv+bias
def conv_2dtranspose(input_tensor, input_dim, output_shape,name=None):
output_dim=output_shape[-1]
with tf.variable_scope(name):
kernel = tf.get_variable("kernel", [5, 5, output_dim, input_dim], initializer=tf.truncated_normal_initializer(stddev=0.02))
bias = tf.get_variable("bias", [output_dim], initializer=tf.constant_initializer(0.0))
deconv = tf.nn.conv2d_transpose(input_tensor, kernel, output_shape=output_shape, strides=[1, 2, 2, 1],padding='SAME')
return deconv+bias
def batch_norm(input_tensor,name,is_train=True):
return tf.contrib.layers.batch_norm(input_tensor,decay=0.9, updates_collections=None, epsilon=1e-5, scale=True,
is_training=is_train, scope=name)
def preprocessing(image):
return image/127.5 - 1;
def show_sample(X):
im = X
plt.imshow(im)
plt.axis('on')
plt.show()
batch_size = 64
def generator(z):
l1=linear(input_tensor=z,name="g_lin", input_dim=100, output_dim=1024*4*4)
l2= tf.reshape(l1, [-1, 4, 4, 1024])
l3 = tf.nn.relu(batch_norm(input_tensor=l2,name="g_bn0"))
print l3
#conv1
l4=conv_2dtranspose(input_tensor=l3,name="g_c2dt1",input_dim=1024,output_shape=[batch_size,8,8,512])
l5=tf.nn.relu(batch_norm(input_tensor=l4,name="g_bn1"))
print l5
#conv2
l6=conv_2dtranspose(input_tensor=l5,name="g_c2dt2",input_dim=512,output_shape=[batch_size,16,16,256])
l7=tf.nn.relu(batch_norm(input_tensor=l6,name='g_bn2'))
print l7
#conv3
l8=conv_2dtranspose(input_tensor=l7,name='g_c2dt3',input_dim=256,output_shape=[batch_size,32,32,128])
l9=tf.nn.relu(batch_norm(input_tensor=l8,name='g_bn3'))
print l9
#conv4
l10=conv_2dtranspose(input_tensor=l9,name='g_c2dt4',input_dim=128,output_shape=[batch_size,64,64,3])
l11=tf.nn.tanh(l10)
print l11
return l11
def discriminator(images, reuse=False, alpha=0.2):
with tf.variable_scope("discriminator") as scope:
if reuse:
scope.reuse_variables()
#naming of the layers is as per layer number
#h0 conv2d no batch_norm
l1 = conv_2d(input_tensor=images, input_dim=3, output_dim= 64, name='d_c2d0')
l2 = lrelu(l1,alpha)
#h1 conv2d with batch_norm
l3 = conv_2d(input_tensor=l2, input_dim=64, output_dim=64*2, name='d_c2d1')
l4 = batch_norm(input_tensor=l3,name="d_bn1")
l5 = lrelu(l4,alpha)
#h2 conv2d with batch_norm
l6 = conv_2d(input_tensor=l5, input_dim=64*2, output_dim=64*4, name='d_c2d2')
l7 = batch_norm(input_tensor=l6,name="d_bn2")
l8 = lrelu(l7,alpha)
#h3 conv2d with batch_norm
l9 = conv_2d(input_tensor=l8, input_dim=64*4, output_dim=64*8, name='d_c2d3')
l10 = batch_norm(input_tensor=l9,name="d_bn3")
l11 = lrelu(l10,alpha)
#h4 reshape and linear
l12 = tf.reshape(l11, [-1, 8192]) #l12 = tf.reshape(l11, [32, -1]) #l12 = tf.reshape(l11, [64, -1])
l13 = linear(input_tensor=l12, input_dim=8192, output_dim=1, name="d_lin4")
print l13.get_shape().as_list()
#sigmoid
l14 = tf.nn.sigmoid(l13)
print l14
return l14, l13
#place holders for images and z
z = tf.placeholder(tf.float32, [None, 100], name='z')
G=generator(z)
#placeholder for images
images = tf.placeholder(tf.float32, [None,64,64,3], name='images')
alpha = 0.2
D1, D1_logits = discriminator(images, False, alpha)
D2, D2_logits = discriminator(G, True, alpha)
#create list of discrim and gen vars
t_vars=tf.trainable_variables()
for var in t_vars:
print var.name
discrim_vars = [var for var in t_vars if 'd_' in var.name]
gen_vars = [var for var in t_vars if 'g_' in var.name]
for var in discrim_vars:
print var.name
for var in gen_vars:
print var.name
img_width, img_height = 64, 64
data_dir = './data'
learning_rate= 0.0002
beta1= 0.5
batch_size=64
#LOSS
discrim_loss_real_img = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D1_logits, labels=tf.scalar_mul(0.9,tf.ones_like(D1_logits))))
discrim_loss_fake_img = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D2_logits, labels=tf.zeros_like(D2_logits)))
discrim_loss = discrim_loss_real_img + discrim_loss_fake_img
gen_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=D2_logits, labels=tf.ones_like(D2_logits)))
#optimizers
dopt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(discrim_loss, var_list=discrim_vars)
gopt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(gen_loss, var_list=gen_vars)
load_img_datagen = ImageDataGenerator(preprocessing_function = preprocessing)
img_input = load_img_datagen.flow_from_directory(
data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
d_loss_all=[]
g_loss_all=[]
def merge_images(image_batch, size):
h,w = image_batch.shape[1], image_batch.shape[2]
c = image_batch.shape[3]
img = np.zeros((int(h*size[0]), w*size[1], c))
for idx, im in enumerate(image_batch):
i = idx % size[1]
j = idx // size[1]
img[j*h:j*h+h, i*w:i*w+w,:] = im
return img
def save_image(X, iter, fl):
name = 'Iteration' + str(iter) + 'time' + str(ti.time()) + '.png'
if (fl == False):
name = 'Random'+name
size = [8,8]
X[0] = (X[0] + 1.)/2
im = merge_images(X[0], size)
scipy.misc.imsave(name, im)
def save_sample(X, iter, fl):
im = X
plt.imshow(im)
plt.axis('on')
name = 'Iteration' + str(iter) + 'time' + str(ti.time()) + '.png'
plt.savefig(name)
disp_img_noise = np.random.uniform(-1,1,size=[batch_size,100])
saver = tf.train.Saver()
f = open('train.log', 'w+')
iters = 50000
GEN_LOSS_LIMIT = 150
for i in range(iters):
#train discriminator
real_images=next(img_input)
noise= np.random.uniform(-1,1,size=[batch_size,100])
sess.run([dopt],feed_dict={z:noise,images:real_images})
#train discriminator
real_images=next(img_input)
noise= np.random.uniform(-1,1,size=[batch_size,100])
sess.run([dopt],feed_dict={z:noise,images:real_images})
#gen
noise= np.random.uniform(-1,1,size=[batch_size,100])
sess.run([gopt],feed_dict={z:noise})
if (np.sum(g_loss_all[-100:]) > GEN_LOSS_LIMIT):
#adaptive generator update
noise= np.random.uniform(-1,1,size=[batch_size,100])
sess.run([gopt],feed_dict={z:noise})
f.write('Extra Generator in iteration: ' + str(i) + ' sum of last 100: ' + str(np.sum(g_loss_all[-100:])) + '\n')
print 'Extra Generator in iteration: ' + str(i) + ' sum of last 100: ' + str(np.sum(g_loss_all[-100:]))
#evaluate
noise_tr= np.random.uniform(-1,1,size=[batch_size,100])
real_images=next(img_input)
#train generator
#d_loss_all.append(discrim_loss.eval({z: noise_tr,images:real_images}))
#g_loss_all.append(gen_loss.eval({z: noise_tr}))
d_loss_all.append(sess.run([discrim_loss],feed_dict={z:noise_tr, images:real_images}))
g_loss_all.append(sess.run([gen_loss], feed_dict={z:noise_tr}))
print i, g_loss_all[-1], d_loss_all[-1]
if (i%1000 == 0):
losses_list = [g_loss_all, d_loss_all]
with open('loss.csv', 'w') as loss_file:
writer = csv.writer(loss_file)
writer.writerows(losses_list)
fake_img = sess.run([G],feed_dict={z:disp_img_noise})
save_image(fake_img, i, True)
random_noise = np.random.uniform(-1,1,size=[batch_size,100])
save_image(sess.run([G],feed_dict={z:random_noise}), i, False)
name = 'saved_model.ckpt'
saver.save(sess,name)
log_string = 'iteration: ' + str(i) + ' g_loss:' + str(g_loss_all[-1]) + ' d_loss:' + str(d_loss_all[-1])
f.write(log_string)
f.write('\n')
f.flush()
<file_sep>/Nearest Neighbor Experiments/convert_images_to_numpy.py
import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
import glob
from PIL import Image
image_list = []
f=open('img_processed.log','w+')
for filename in glob.glob('/home/nishant.puri2577/data/jpg2/*'):
im=misc.imread(filename)
image_list.append(im)
print len(image_list)
train=image_list[0].reshape(12288)
for i in range(1,len(image_list)):
if(i%100==0):
f.write('images processed' + str(i))
f.write('\n')
f.flush()
train=np.vstack((train,image_list[i].reshape(12288)))
np.savetxt("train.csv", train, delimiter=",")
|
f3214dc15c853e6d5a3167a740a5013134306eaf
|
[
"Markdown",
"Python",
"Shell"
] | 10 |
Shell
|
xiaoliang008/image-completion-using-GANs
|
b695d34edd1d9478a66e20ce4826964726a5586c
|
806fe375840c610f0c100b055bb158ef01f8d24c
|
refs/heads/master
|
<repo_name>RajashekarAdukaniBlueCloud/node<file_sep>/REST_full_API_Express/app.js
const Joi = require("joi");
const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{id:1, name:'course 1'},
{id:2, name:'course 2'},
{id:3, name:'course 3'},
{id:4, name:'course 4'},
{id:5, name:'course 5'},
{id:6, name:'course 6'},
{id:7, name:'course 7'},
{id:8, name:'course 8'},
{id:9, name:'course 9'},
{id:10, name:'course 10'}
]
app.get('/', (req, res) => {
res.send("Hello wrold");
});
app.get("/api/courses", (req, res) => {
//res.send([1,2,3,4,5,6,7,8,9]);
res.send(courses);
});
app.get('/api/courses/:id', (req, res) => {
// res.send(req.params.id)
const course = courses.find(c => c.id === parseInt(req.params.id));
if(!course) res.status(404).send("the course with given id not found");
res.send(course);
});
app.get('/api/posts/:year/:month', (req, res) => {
res.send(req.query)
});
app.post("/api/courses", (req, res) => {
// const schema = {
// name: Joi.string().min(3).required()
// }
// const result = Joi.validate(req.body, schema);
// if(result.error) {
// res.status(400).send(result.error.details[0].message);
// return
// }
//validate input always don't trust client input data
//400 bad request
// if(!req.body.name || req,body.name.length < 3) {
// res.send(400).send("name is required more then 3 latters");
// return
// }
// object distractring {error}
const { error } = validationCourse(req.body);
if(error) {
res.status(400).send(error.details[0].message)
return
}
const course = {
id: courses.length + 1,
name: req.body.name
}
courses.push(course);
res.send(course)
});
app.put("/api/courses/:id", (req, res) => {
// Look up at the course
const course = courses.find(c => c.id === parseInt(req.params .id));
// if not existing, return 404
if(!course) res.status(404).send("The course with id was not found")
const { error } = validationCourse(req.body);
if(error) {
res.status(400).send(error.details[0].message)
return
}
//update course
course.name = req.body.name;
//return the updated course
res.send(course);
});
app.delete('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if(!course) res.status(400).send("The given id was not in the list");
const index = courses.indexOf(course);
courses.splice(index, 1);
res.send(course)
})
function validationCourse(course) {
//Validate
const schema = {
name: Joi.string().min(3).required()
}
return Joi.validate(course, schema);
}
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening on port ${port}...`))
|
9dc7dc867440981635ac1d8f5017ab16dee22711
|
[
"JavaScript"
] | 1 |
JavaScript
|
RajashekarAdukaniBlueCloud/node
|
d52186a7618f58f64cf6748bed585aa70b7417ba
|
6637f30aed591f12343c5a6dbccf37cbdffb00bb
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import AuthentificationService from '../components/services/AuthentificationService'
import { Alert } from "react-bootstrap"
class Login extends Component {
constructor(props) {
super(props);
this.state = {
cin: "",
password: "",
error: ""
};
}
changeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
doLogin = async (event) => {
event.preventDefault();
AuthentificationService
.signin(this.state.cin,
this.state.password)
.then(
() => {
this.props.history.push('/Profile');
},
error => {
this.props.history.push('/Admin');
}
);
}
render() {
return (
<div>
<div className="outer1">
<div className="inner1">
<h3> Connexion </h3>
<form onSubmit={this.doLogin}>
<div className="form-row">
<div className="form-group col fly">
<label for="cin"><strong>cin</strong></label>
<input autoFocus
type="text"
name="cin" id="cin"
value={this.state.cin}
placeholder="Enter cin"
autoComplete="con"
onChange={this.changeHandler}
className="form-control"
/>
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<label for="password"><strong>Password</strong></label>
<input type="password"
name="password" id="password"
value={this.state.password}
placeholder="Enter Password"
autoComplete="password"
onChange={this.changeHandler}
className="form-control"
/>
</div>
</div>
<button type="submit" variant="primary" size="lg" className="btn btn-primary btn-lg btn-block sub" block>
Sign In
</button>
{
this.state.error && (
<Alert color="danger">
{this.state.error}
</Alert>
)
}
</form>
</div>
</div>
</div>);
}
}
export default Login;<file_sep>import React, { Component } from 'react';
import RendezVousService from '../components/services/RendezVousService';
import profile from '../components/Profile';
class RendezvousComponent extends Component {
constructor(props){
super(props)
this.state={
date :'',
heure:'8h',
id_patient: profile.cin,
id_medecin:'256',
id_centre :'',
etat:'pris'
}
this.changedateHandler=this.changedateHandler.bind(this);
this.changeid_centreHandler=this.changeid_centreHandler.bind(this);
}
saveRDV = (e)=>{
e.preventDefault();
let rendez_vous ={date:this.state.date, heure:this.state.heure, id_medecin:this.state.id_medecin, id_centre:this.state.id_centre, etat:this.state.etat};
console.log('rendez_vous =>'+ JSON.stringify(rendez_vous));
RendezVousService.createRDV(rendez_vous);
alert("Votre rendez-vous est pris avec succès, veuiller imrimer votre fiche de rendez vous!");
}
changedateHandler=(event)=>{
this.setState({date:event.target.value})
}
changeid_centreHandler=(event)=>{
this.setState({id_centre:event.target.value})
}
cancel(){
this.props.history.push('/RendezVous');
}
render() {
return (
<div>
<div className="outer">
<div className="inner2">
<div >
<h1 className="text-center"> Prendre un Rendez-Vous </h1>
<div class="bootstrap-iso">
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<form method="post" className = "">
<div class="form-group ">
<label class="control-label " for="select">
Centre de Vaccination
</label>
<select class="select form-control" id="select" name="id_centre" value={this.state.id_centre} onChange={this.changeid_centreHandler}>
<option value="CHU">
CHU
</option>
<option value="Ibn Tofail">
Ibn Tofail
</option>
<option value="Ibn Sina">
Ibn Sina
</option>
</select>
</div>
<div class="form-group ">
<label class="control-label " for="date">
Date du Rendez Vous
</label>
<div class="input-group">
<input class="form-control" type="date" name="date" dateFormat="YYYY/MM/dd" name='date' value={this.state.date} onChange={this.changedateHandler}/>
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
</div>
</div>
<div class="form-group">
<div>
<button class="btn btn-primary " onClick={this.saveRDV}>
Prendre le rendez vous
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default RendezvousComponent;<file_sep>import axios from "axios";
class AuthentificationService {
signin = (cin, password) => {
return axios.post("http://localhost:8081/api/auth/signin", {cin, password})
.then(response => {
if (response.data.accessToken) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
.catch(err => {
console.log(err);
throw err;
});
}
signOut() {
localStorage.removeItem("user");
}
register = async(nom, prenom, cin, email, password,age,ville,adresse,sexe) => {
return axios.post("http://localhost:8081/api/auth/signup", {
nom,
prenom,
cin,
email,
password,
ville,
adresse,
age,
sexe,
});
}
getCurrentUser() {
return JSON.parse(localStorage.getItem('user'));;
}
getPatient(cin){
return axios.get("http://localhost:8081/api/auth/details/"+cin);
}
getPatientDetails(cin){
return axios.get("http://localhost:8081/api/auth/detailsPatient/"+cin);
}
updateUser(users,cin){
return axios.put("http://localhost:8081/api/auth/User/" + cin,users);
}
}
export default new AuthentificationService();<file_sep>import React, { Component } from 'react';
import AuthenticationService from '../components/services/AuthentificationService';
import jsPDF from 'jspdf'
class MesRendezVous extends Component {
constructor(props) {
super(props)
this.state = {
user: [],
message: null
};
}
pdfGenerate=()=>{
var doc=new jsPDF('p', 'pt', 'a2' );
doc.html(document.querySelector("#content"), {
callback:function(pdf){
pdf.save("mypdf.pdf");
}
});
};
pdfGenerate2=()=>{
var doc=new jsPDF('p', 'pt', 'a2' );
doc.html(document.querySelector("#content2"), {
callback:function(pdf){
pdf.save("mafiche.pdf");
}
});
};
componentDidMount() {
const user = AuthenticationService.getCurrentUser();
this.setState({user: user});
document.body.style.background = "white";
AuthenticationService.getPatientDetails(user.cin).then(
response => {
this.setState({
nom:response.data.nom,
prenom:response.data.prenom,
cin:response.data.cin,
etatDeVaccination:response.data.etatDeVaccination,
dateDePremereDose:response.data.dateDePremereDose,
dateDeuxiemeeDose:response.data.dateDeuxiemeeDose
})
},
);
}
render() {
let userInfo = "";
const user = this.state.user;
return (
<div>
<div className=" rounded" >
<div className="row px-5" >
<div className="outer">
<div className="inner3" >
<form className="rounded msg-form" method="" id="content">
<h3 className="">Rendez vous pour la première dose</h3>
<div className="form-group row">
<div className="col-md-6">
<label for="name" class="h6">Nom</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<p className=" text-primary"></p>
</div> <input type="text" value={this.state.nom} className="form-control border-0"required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" class="h6">Prenom</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<p className=" text-primary"></p>
</div> <input type="text" value={this.state.prenom} className="form-control border-0"required disabled/>
</div> </div>
</div>
<div className="form-group row">
<div className="col-md-6">
<label for="name" className="h6">CIN</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value={this.state.cin} required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" className="h6">Etat de vaccination</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value={this.state.etatDeVaccination} required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" className="h6">Date de la première dose</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value={this.state.dateDePremereDose} required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" className="h6">Centre de vaccination</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value="CHU" required disabled/>
</div>
</div>
</div>
</form>
<button type="button" className="btn" onClick={this.pdfGenerate}>Imprimer ma fiche de rendez-vous</button>
</div>
</div>
</div>
</div>
<div className=" rounded" >
<div className="row px-5">
<div className="outer">
<div className="inner3">
<form className="rounded msg-form" id="content2">
<h3 className="">Rendez vous pour la deuxième dose</h3>
<div className="form-group row">
<div className="col-md-6">
<label for="name" class="h6">Nom</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<p className=" text-primary"></p>
</div> <input type="text" value={this.state.nom} className="form-control border-0"required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" class="h6">Prenom</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<p className=" text-primary"></p>
</div> <input type="text" value={this.state.prenom} className="form-control border-0"required disabled/>
</div> </div>
</div>
<div className="form-group row">
<div className="col-md-6">
<label for="name" className="h6">CIN</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value={this.state.cin} required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" className="h6">Etat de vaccination</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value={this.state.etatDeVaccination} required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" className="h6">Date de la 2ème dose</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value={this.state.dateDeuxiemeeDose} required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" className="h6">Centre de vaccination</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value="CHU" required disabled/>
</div>
</div>
</div>
</form>
<button type="button" className="btn" onClick={this.pdfGenerate2}>Imprimer ma fiche de rendez-vous</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default MesRendezVous;<file_sep>import axios from 'axios';
const MEDECIN_API_BASE_URL = "http://localhost:8081/api/auth/Medecins"
class MedecinService {
getMedecins(){
return axios.get(MEDECIN_API_BASE_URL);
}
createMedecin(medecin){
return axios.post(MEDECIN_API_BASE_URL, medecin);
}
getMedecinById(medecinId){
return axios.get(MEDECIN_API_BASE_URL + '/' +medecinId);
}
updateMedecin(medecin, medecinId){
return axios.put(MEDECIN_API_BASE_URL + '/' + medecinId, medecin);
}
deleteMedecin(medecinId){
return axios.delete(MEDECIN_API_BASE_URL + '/' + medecinId);
}
}
export default new MedecinService();<file_sep>import axios from 'axios'
const PATIENT_API_URL = 'http://localhost:8081/api/auth'
const MEDECIN_API_URL = `${PATIENT_API_URL}/findAllPatients`
class PatientDataService {
retrieveAllPatients() {
return axios.get(`${MEDECIN_API_URL}`);
}
deletePatient(id){
return axios.delete(`${PATIENT_API_URL}/delete/{id}`);
}
createPatient(patient){
return axios.post(`${PATIENT_API_URL}/addPatient`, patient)
}
getPatientById(patientId){
return axios.get(PATIENT_API_URL + '/findAllPatients/' + patientId);
}
fichePatient(patient, patientId){
return axios.put(PATIENT_API_URL + '/patients/' + patientId, patient)
}
}
export default new PatientDataService()<file_sep>import React, { Component } from 'react';
class InfoCampagne extends Component {
render() {
return (
<div>
<h1>Campagne de vaccination contre Covid19</h1>
<div className="container1">
<div class="container-fluid1">
<h2>Nombre de personnes vaccinées:</h2>
<h3>
<script> document.write(new Date().toLocaleDateString()); </script>
</h3>
<div class="row">
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h5 class="card-title"> Dose 1: </h5>
<p class="card-text">5 994 379</p>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h5 class="card-title"> Dose 2: </h5>
<p class="card-text">4 441 667</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default InfoCampagne;<file_sep>import React, { Component } from 'react';
import PatientDataService from '../components/services/PatientDataService';
class ListPatients extends Component {
constructor(props) {
super(props)
this.state = {
patients: [],
message: null
}
this.refreshPatients = this.refreshPatients.bind(this)
this.deletePatientClicked=this.deletePatientClicked.bind(this)
this.addPatient=this.addPatient.bind(this)
this.fichePatient=this.fichePatient.bind(this)
}
fichePatient(id){
this.props.history.push(`/fiche-patient/${id}`);
}
componentDidMount() {
this.refreshPatients();
}
refreshPatients() {
PatientDataService.retrieveAllPatients()//HARDCODED
.then(
response => {
console.log(response);
this.setState({ patients: response.data })
}
)
}
deletePatientClicked(id) {
PatientDataService.deletePatient(id)
.then(
response => {
this.setState({ message: `Delete of patient ${id} Successful` })
this.refreshPatients()
}
)
}
addPatient(){
this.props.history.push('/add-patient')
}
render() {
return (
<div>
<h2 className="text-center">Liste des patients</h2>
<div className="row">
<button className="btn btn-primary" onClick={this.addPatient}>Ajouter patient</button>
</div>
{this.state.message && <div class="alert alert-success">{this.state.message}</div>}
<div className="row">
<table className="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Id</th>
<th>CIN</th>
<th>Nom</th>
<th>Prénom</th>
<th>Age</th>
<th>Sexe</th>
<th>Etat du vaccin </th>
<th>Effets indésirables</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
this.state.patients.map(
patient =>
<tr key={patient.id}>
<td>{patient.id}</td>
<td>{patient.cin}</td>
<td>{patient.nom}</td>
<td>{patient.prenom}</td>
<td>{patient.age}</td>
<td>{patient.sexe}</td>
<td>{patient.etatDeVaccination}</td>
<td>{patient.effetsInds}</td>
<td>
<button onClick= {() => this.fichePatient(patient.id)} className="btn btn-info">Fiche de patient</button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
)
}
}
export default ListPatients<file_sep>import React, { Component } from 'react';
import { Alert } from "react-bootstrap"
import AuthenticationService from '../components/services/AuthentificationService';
const validEmailRegex = RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);
const validateForm = (errors) => {
let valid = true;
Object.values(errors).forEach(
(val) => val.length > 0 && (valid = false)
);
return valid;
}
class EditProfile extends Component {
constructor(props) {
super(props);
this.state = {
nom: "",
prenom: "",
cin: "",
email: "",
user: undefined,
password: "",
age:"",
sexe:"homme",
ville:"",
adresse:"",
message: "",
};
}
onClick = nr => () => {
this.setState({
radio: nr
});
};
updateUser = (e) => {
e.preventDefault();
let users ={nom: this.state.nom, prenom: this.state.prenom, email: this.state.email, adresse: this.state.adresse, ville: this.state.ville};
console.log('users => ' + JSON.stringify(users));
AuthenticationService.updateUser(users,this.state.cin).then( res => {
this.props.history.push('/MyProfile');
});
}
componentDidMount() {
const user = AuthenticationService.getCurrentUser();
this.setState({user: user});
document.body.style.background = "white";
AuthenticationService.getPatient(user.cin).then(
response => {
this.setState({
nom:response.data.nom,
prenom:response.data.prenom,
cin:response.data.cin,
email:response.data.email,
age:response.data.age,
sexe:response.data.sexe,
ville:response.data.ville,
adresse:response.data.adresse,
message: response.data.message,
})
},
);
}
changeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
render() {
const title = <h2>Register User</h2>;
const errors = this.state.errors;
let alert = "";
if(this.state.message){
if(this.state.successful){
alert = (
<Alert variant="success">
{this.state.message}
</Alert>
);
}else{
alert = (
<Alert variant="danger">
{this.state.message}
</Alert>
);
}
}
let userInfo = "";
const user = this.state.user;
return (
<div>
<div className="outer">
<div className="inner">
<form onSubmit={this.signUp}>
<h3>Mes Informations</h3>
<div className="form-row">
<div className="form-group col fly">
<label for="nom">nom</label>
<input
type="text"
placeholder="Enter nom"
name="nom" id="nom"
value={this.state.nom}
autoComplete="nom"
onChange={this.changeHandler}
className="form-control"
/>
</div>
<div className="form-group col fly">
<label for="prenom">prenom</label>
<input
type="text"
placeholder="Enter prenom"
name="prenom" id="prenom"
value={this.state.prenom}
autoComplete="prenom"
onChange={this.changeHandler}
className="form-control"
/>
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<label for="cin">cin</label>
<input
type="text"
placeholder="Enter cin"
name="cin" id="cin"
value={this.state.cin}
autoComplete="cin"
onChange={this.changeHandler}
className="form-control"
disabled
/>
</div>
<div className="form-group col fly">
<label for="email">Email</label>
<input required
type="text"
name="email" id="email"
value={this.state.email}
autoComplete="email"
onChange={this.changeHandler}
className="form-control"
/>
</div>
</div>
<br></br>
<br></br>
<div className="form-row">
<div className="form-group col fly">
<label>Age </label>
<input type="number" name="age" onChange={this.changeHandler} value={this.state.age} autoComplete="off" onChange={this.changeHandler} className="form-control" required/>
</div>
<div className="form-group col fly">
<div className="radio">
<label><input type="radio" value="homme"
checked={this.state.sexe === "homme"}
onChange={this.handleOptionChange} name="optradio" onChange={this.changeHandler} />Homme</label>
</div>
<div className="radio">
<label><input type="radio"
value="femme"
checked={this.state.sexe === "femme"}
onChange={this.handleOptionChange} name="optradio"/>Femme</label>
</div>
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<label>Ville</label>
<input type="text" onChange={this.changeHandler} name="ville" value={this.state.ville} autoComplete="off" className="form-control" required/>
</div>
<div className="form-group col fly">
<label>Adresse</label>
<input type="text" onChange={this.changeHandler} name="adresse" value={this.state.adresse} autoComplete="off" className="form-control" required/>
</div>
</div>
<button onClick = {this.updateUser} type="submit" className="btn btn-primary btn-lg btn-block sub">Modifier</button>
</form>
</div>
</div>
</div>
);
}
}
export default EditProfile;<file_sep>import React, { Component } from 'react';
import './App.css';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import FooterComponent from './components/FooterComponent';
import HeaderComponent from './components/HeaderComponent';
import LissteRdvsComponent from './components/LissteRdvsComponent';
import RendezvousComponent from './components/RendezvousComponent';
import Login from './components/Login'
import AccueilPatient from './components/AccueilPatient';
import Profile from './components/Profile';
import AcceuilComponent from './components/AccueilComponent';
import ListMedecinComponent from './components/ListMedecinComponent';
import CreateMedecinComponent from './components/CreateMedecinComponent';
import UpdateMedecinComponent from './components/UpdateMedecinComponent';
import SignUp from './components/SignUp';
import ListPatients from './components/ListPatients';
import CreatePatientComponent from './components/CreatePatientComponent';
import FicheComponent from './components/FicheComponent'
import Accueil from './components/Accueil';
import Effet from './components/effets_inde';
import MesRendezVous from './components/MesRendezVous'
import editprofile from'./components/editprofile';
import vaccin from './components/vaccinadopte'
import Faq from './components/Faq';
import InfoCampagne from './components/InfoCampagne';
class App extends Component {
render() {
return (
<div>
<Router>
<HeaderComponent/>
<div className ="container">
<switch>
<Route path="/Accueil" component={Accueil}></Route>
<Route path="/editprofile" component={editprofile}></Route>
<Route path="/patients" component = {ListPatients} ></Route>
<Route path="/add-patient" component = {CreatePatientComponent} ></Route>
<Route path="/fiche-patient/:id" component = {FicheComponent} ></Route>
<Route path="/MesRendezVous" component={MesRendezVous}></Route>
<Route path="/effet" component={Effet}></Route>
<Route path="/vaccin" component={vaccin}></Route>
<Route path="/SignUp" component={SignUp}></Route>
<Route path = "/Medecins" component = {ListMedecinComponent} ></Route>
<Route path = "/addMedecin" component = {CreateMedecinComponent} ></Route>
<Route path = "/updateMedecin/:id" component = {UpdateMedecinComponent} ></Route>
<Route path="/Admin" component={AcceuilComponent}></Route>
<Route path="/Login" component={Login}></Route>
<Route path="/MyProfile" component={AccueilPatient}></Route>
<Route path ="/RendezVous" component={RendezvousComponent}></Route>
<Route path ="/rdv" component={LissteRdvsComponent}></Route>
<Route path="/Profile" component={Profile}></Route>
<Route path ="/faq" component={Faq}></Route>
<Route path ="/infos" component ={InfoCampagne} ></Route>
</switch>
</div>
<FooterComponent/>
</Router>
</div>
);
}
}
export default App;<file_sep>import React, { Component } from 'react';
import { Alert } from "react-bootstrap"
import Authentication from '../components/services/AuthentificationService';
const validEmailRegex = RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);
const validateForm = (errors) => {
let valid = true;
Object.values(errors).forEach(
(val) => val.length > 0 && (valid = false)
);
return valid;
}
class SignUp extends Component {
constructor(props) {
super(props);
this.state = {
nom: "",
prenom: "",
cin: "",
email: "",
password: "",
age:"",
sexe:"homme",
ville:"",
adresse:"",
message: "",
successful: false,
validForm: true,
errors: {
nom: '',
prenom: '',
cin: '',
email: '',
password: ''
}
};
}
onClick = nr => () => {
this.setState({
radio: nr
});
};
changeHandler = (event) => {
const { name, value } = event.target;
let errors = this.state.errors;
switch (name) {
case 'nom':
errors.nom =
value.length < 3
? 'le nom doit être de 3 caractères au minimum !'
: '';
break;
case 'prenom':
errors.prenom =
value.length < 3
? 'le nom doit être de 3 caractères au minimum!'
: '';
break;
case 'cin':
errors.cin =
value.length < 5
? 'le nom doit être de 5 caractères au minimum!'
: '';
break;
case 'email':
errors.email =
validEmailRegex.test(value)
? ''
: 'Email is not valid!';
break;
case 'password':
errors.password =
value.length < 8
? 'le nom doit être de 8 caractères au minimum!'
: '';
break;
case 'age':
errors.age =
value.value>18
? 'le nom doit être de 8 caractères au minimum!'
: '';
break;
default:
break;
}
this.setState({errors, [name]: value}, ()=> {
console.log(errors)
})
}
handleOptionChange = changeEvent => {
this.setState({
sexe: changeEvent.target.value
});
};
signUp = (e) => {
e.preventDefault();
const valid = validateForm(this.state.errors);
this.setState({validForm: valid});
if(valid){
Authentication.register(
this.state.nom,
this.state.prenom,
this.state.cin,
this.state.email,
this.state.password,
this.state.age,
this.state.ville,
this.state.adresse,
this.state.sexe
).then(
response => {
this.setState({
message: response.data.message,
successful: true
});
},
error => {
console.log("Fail! Error = " + error.toString());
this.setState({
successful: false,
message: 'ce mail est déja utiliser'
});
}
);
}
}
render() {
const title = <h2>Register User</h2>;
const errors = this.state.errors;
let alert = "";
if(this.state.message){
if(this.state.successful){
alert = (
<Alert variant="success">
{this.state.message}
</Alert>
);
}else{
alert = (
<Alert variant="danger">
{this.state.message}
</Alert>
);
}
}
return (
<div>
<div className="outer">
<div className="inner">
<form onSubmit={this.signUp}>
<h3>Inscription</h3>
<div className="form-row">
<div className="form-group col fly">
<label for="nom">nom</label>
<input
type="text"
placeholder="Enter nom"
name="nom" id="nom"
value={this.state.nom}
autoComplete="nom"
onChange={this.changeHandler}
className="form-control"
/>
{
errors.nom && (
<Alert variant="danger">
{errors.nom}
</Alert>
)
}
</div>
<div className="form-group col fly">
<label for="prenom">prenom</label>
<input
type="text"
placeholder="Enter prenom"
name="prenom" id="prenom"
value={this.state.prenom}
autoComplete="prenom"
onChange={this.changeHandler}
className="form-control"
/>
{
errors.prenom && (
<Alert variant="danger">
{errors.prenom}
</Alert>
)
}
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<label for="cin">cin</label>
<input
type="text"
placeholder="Enter cin"
name="cin" id="cin"
value={this.state.cin}
autoComplete="cin"
onChange={this.changeHandler}
className="form-control"
/>
{
errors.cin && (
<Alert variant="danger">
{errors.cin}
</Alert>
)
}
</div>
<div className="form-group col fly">
<label for="email">Email</label>
<input required
type="text"
placeholder="Enter Email"
name="email" id="email"
value={this.state.email}
autoComplete="email"
onChange={this.changeHandler}
className="form-control"
/>
{
errors.email && (
<Alert variant="danger">
{errors.email}
</Alert>
)
}
</div>
</div>
<br></br>
<br></br>
<div className="form-row">
<div className="form-group col fly">
<label>Age </label>
<input type="number" name="age" value={this.state.age} autoComplete="off" onChange={this.changeHandler} className="form-control" placeholder="age" required/>
{
errors.age && (
<Alert variant="danger">
{errors.age}
</Alert>
)
}
</div>
<div className="form-group col fly">
<div className="radio">
<label><input type="radio" value="homme"
checked={this.state.sexe === "homme"}
onChange={this.handleOptionChange} name="optradio" />Homme</label>
</div>
<div className="radio">
<label><input type="radio"
value="femme"
checked={this.state.sexe === "femme"}
onChange={this.handleOptionChange} name="optradio"/>Femme</label>
</div>
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<label>Ville</label>
<input type="text" name="ville" value={this.state.ville} onChange={this.changeHandler} autoComplete="off" className="form-control" placeholder="ville" required/>
</div>
<div className="form-group col fly">
<label>Adresse</label>
<input type="text" name="adresse" value={this.state.adresse} onChange={this.changeHandler} autoComplete="off" className="form-control" placeholder="adresse" required/>
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<label for="password">Password</label>
<input required
type="password"
placeholder="Enter Password"
name="password" id="password"
value={this.state.password}
autoComplete="password"
onChange={this.changeHandler}
className="form-control"
/>
{
errors.password && (
<Alert key="errorspassword" variant="danger">
{errors.password}
</Alert>
)
}
</div>
</div>
<button type="submit" className="btn btn-primary btn-lg btn-block sub">Register</button>
{
!this.state.validForm && (
<Alert key="validForm" variant="danger">
Please check the inputs again!
</Alert>
)
}
{alert}
<p className="forgot-password text-right">
Already registered <a href=" ">log in?</a>
</p>
</form>
</div>
</div>
</div>
);
}
}
export default SignUp;<file_sep>import React, { Component } from 'react';
class vaccin extends Component {
render() {
return (
<div>
<h2 className="funt " >Vaccin contre le Covid au Maroc: les vaccins adopté par le Maroc</h2>
<br></br>
<p className="funt1 ">𝐋𝐞 𝐑𝐨𝐢 𝐌𝐨𝐡𝐚𝐦𝐦𝐞𝐝 𝐕𝐈 𝐚 𝐨𝐫𝐝𝐨𝐧𝐧é 𝐜𝐞 𝐥𝐮𝐧𝐝𝐢 𝟗 𝐧𝐨𝐯𝐞𝐦𝐛𝐫𝐞, 𝐮𝐧 𝐩𝐫𝐨𝐜𝐡𝐚𝐢𝐧 𝐝é𝐦𝐚𝐫𝐫𝐚𝐠𝐞 𝐝𝐞 𝐥𝐚 𝐯𝐚𝐜𝐜𝐢𝐧𝐚𝐭𝐢𝐨𝐧 𝐚𝐧𝐭𝐢-𝐂𝐨𝐯𝐢𝐝,
𝐪𝐮𝐢 𝐬𝐞𝐫𝐚 𝐮𝐧𝐞 𝐯𝐚𝐜𝐜𝐢𝐧𝐚𝐭𝐢𝐨𝐧 𝐦𝐚𝐬𝐬𝐢𝐯𝐞. 𝐕𝐨𝐢𝐜𝐢 𝐝𝐞𝐬 𝐢𝐧𝐟𝐨𝐫𝐦𝐚𝐭𝐢𝐨𝐧 𝐜𝐨𝐧𝐜𝐞𝐫𝐧𝐚𝐧𝐭 𝐜𝐞𝐭𝐭𝐞 𝐜𝐚𝐦𝐩𝐚𝐠𝐧𝐞 𝐝𝐞 𝐯𝐚𝐜𝐜𝐢𝐧𝐚𝐭𝐢𝐨𝐧. </p>
<br></br>
<br></br>
<div class="row row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-body">
<h5 class="card-title style"> Le vaccin chinois de Sinopharm:</h5>
<p class="card-text">une partie des essais de phase 3 ont eu lieu au Maroc, auprès de 600 volontaires. Selon des sources sûres, « ces essais au Maroc ont montré peu d’effets indésirables et une efficacité très correcte ». Les essais au Maroc seront complètement terminés le 15 novembre. Ce vaccin a été testé sur 50.000 personnes en dehors de la Chine (Maroc, Emirats, Bahreïn, Pérou, Argentine) et près 100.000 personnes en Chine, selon la presse chinoise. Des sources chinoises en contact avec les équipes de test clinique au Maroc indiquent que 1 million de Chinois ont reçu leurs doses, non pas à titre de test mais de vaccin. Des médias chinois
annoncent que plusieurs centaines de milliers de personnes ont reçu le vaccin de Sinopharm« .</p>
</div>
</div>
</div>
<div class="col">
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-body ">
<h5 class="card-title style">Le vaccin AstraZeneca:</h5>
<p class="card-text"> Afin d’assurer une quantité de vaccin anti-Covid suffisante pour la population marocaine, le Maroc a pour l’heure signé deux partenariats. L’un avec Sinopharm et l’autre avec la société « R-Pharm » sous licence du laboratoire suédo-britannique « AstraZeneca ».
Le partenariat entre le Maroc et le laboratoire chinois permet au Royaume d’acquérir 10 millions de doses avant 2020. Tandis que celui avec AstraZeneca prévoit la fourniture de 17 millions de doses avec, en option, 3 millions de doses supplémentaires.</p>
</div>
</div>
</div>
</div>
<br></br>
<br></br>
<div class="row row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-body">
<h5 class="card-title style"> CanSino Bio, Pfizer et Johnson & Johnson:</h5>
<p class="card-text">Le Maroc est également entré en contact avec CanSino Bio, Pfizer et Johnson & Johnson, autres candidats producteurs de vaccins, pour s’approvisionner auprès d’eux. A ce stade,
nous ne savons pas si ces contacts ont abouti</p>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default vaccin;<file_sep>import React, { Component } from 'react';
import docteur from '../components/docteur.jpg';
import patient1 from '../components/patient1.png';
import statistique from '../components/statistique.png';
import rdv from '../components/rdv.jpg';
import { withRouter } from 'react-router-dom';
import { Link } from "react-router-dom";
class AcceuilComponent extends Component {
componentDidMount(){
document.body.style.background = "white";
}
render() {
return (
<div >
<br></br>
<div>
<section id="services" class="services ">
<div class="container">
<div class="section-title">
<h2 className="couleur">Bienvenue sur votre espace Admin</h2>
<p></p>
</div>
<div class="row">
<div class="col-lg-4 col-md-6 d-flex align-items-stretch ">
<div class="icon-box">
<div class="pic"><img src={docteur} class="img-fluid" alt=""></img></div>
<h4 className="couleur" ><a href="/Medecins">Médecins</a></h4>
<p className="couleur">Voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4 mt-md-0">
<div class="icon-box">
<div class="pic"><img src={patient1} class="img-fluid" alt=""></img></div>
<h4 className="couleur"><a href="/rdv">Rendez-vous</a></h4>
<p className="couleur">Visualiser la liste des rendez-vous des patients</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4 mt-lg-0">
<div class="icon-box">
<div class="pic"><img src={statistique} class="img-fluid" alt=""></img></div>
<h4 className="couleur"><a href="">Statistiques et documentation</a></h4>
<p className="couleur">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia</p>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
);
}
}
export default AcceuilComponent;<file_sep>import React, { Component } from 'react';
import { Collapse } from 'antd';
const { Panel } = Collapse;
class Faq extends Component {
render() {
return (
<div>
<section id="hero" class="d-flex align-items-center">
<div class="container">
<h1>F.A.Q</h1>
<h2>Les réponses aux questions fréquentes posées
<br></br>
autour de la vaccination contre la COVID-19</h2>
</div>
</section>
<div class="faq">
<Collapse defaultActiveKey={['1']} >
<Panel Content header="Comment fonctionnent les vaccins ?" key="1">
<p>Les vaccins stimulent les réponses immunitaires protectrices du corps humain de sorte que, si une personne est infectée par un agent pathogène, le système immunitaire peut rapidement empêcher l'infection de se propager dans le corps et de provoquer des maladies. De cette manière, les vaccins imitent une infection naturelle mais sans pour autant provoquer la maladie.
<br></br>
<br></br>
Toutes les personnes infectées par le SRAS-CoV-2 ne développent pas de maladie (Covid-19 est la maladie causée par le virus SARS-CoV-2). Ces personnes ont une infection asymptomatique mais peuvent toujours transmettre le virus à d'autres. La plupart des vaccins n'empêchent pas complètement l'infection, mais empêchent l'infection de se propager dans le corps et de provoquer des maladies. De nombreux vaccins peuvent également empêcher la transmission, conduisant potentiellement à la protection collective grâce à laquelle les personnes non vaccinées sont protégées de l'infection par les personnes vaccinées qui les entourent, car elles ont moins de risque d'être exposées au virus.</p>
</Panel>
<Panel header="Pourquoi une stratégie de vaccination contre le virus de la COVID-19 au Maroc ?" key="2">
<p>A l’instar des autres pays du monde, en dépit des mesures sanitaires établies au Maroc, il a été enregistré des conséquences relatives à la pandémie à COVID-19 touchant les volets sanitaire, économique et social, nécessitant la mise en place de stratégies de lutte additionnelles.
<br></br>
<br></br>
Ainsi, le Maroc, grâce aux Orientations Royales de Sa Majesté le Roi Mohammed VI que Dieu l’assiste, a été parmi les pays qui ont anticipé la planification pour la mise en place d’une stratégie de vaccination contre le virus de la COVID-19 comme intervention puissante de santé publique et a procédé à la signature d’accord pour l’acquisition des vaccins, le transfert de technologie et la participation à la phase III des essais cliniques pour le développement du vaccin.
</p>
</Panel>
<Panel header="Est ce que les vaccins utilisés par le Maroc sont sûrs?" key="3">
<p>Les données sur les vaccins sont réconfortantes. Les essais réalisés n'ont pas suscité de préoccupations en matière de sécurité, bien que de rares effets indésirables, bénins à modérés (douleurs au site d’injection, réaction cutanée, maux de tête, une légère fébricule) ont été notifiés chez quelques participants aux essais cliniques au Maroc. Les résultats de ces derniers ont confirmé que ces effets indésirables étaient transitoires, comparables à d’autres vaccins de même type et qu’aucun événement indésirable grave n'a été signalé.</p>
</Panel>
<Panel header="Quelles sont les contre-indications du vaccin anti-covids-19?" key="4">
<p>Toutes les personnes âgées de 17 ans et plus peuvent être vaccinées par le vaccin anti-Covid-19, quel que soit la maladie ou le traitement en cours, à l’exception des situations suivantes :
<br></br>
<br></br>
Les femmes enceintes.
<br></br>
<br></br>
Les femmes allaitantes.
<br></br>
<br></br>
Les personnes ayant présenté une réaction allergique suite à la première dose de ce vaccin.
</p>
</Panel>
</Collapse>
</div>
</div>
);
}
}
export default Faq;<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import MedecinService from '../components/services/MedecinService';
import { confirmAlert } from 'react-confirm-alert'; // Import
import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css
class ListMedecinComponent extends Component {
constructor(props) {
super(props);
this.state = {
medecin: []
}
this.addMedecin = this.addMedecin.bind(this);
this.editMedecin = this.editMedecin.bind(this);
this.deleteMedecin = this.deleteMedecin.bind(this);
}
deleteMedecin(id){
confirmAlert({
message: 'Êtes-vous sûr de vouloir supprimer?',
buttons: [
{
label: 'Oui',
onClick: () => MedecinService.deleteMedecin(id).then ( res => {
this.setState({medecin: this.state.medecin.filter(medecin => medecin.id !== id)});
})
},
{
label: 'Non',
onClick: () => this.props.history.push('/Medecins')
}
]
});
}
editMedecin(id){
this.props.history.push(`/updateMedecin/${id}`);
}
componentDidMount(){
MedecinService.getMedecins().then((res) => {
this.setState({ medecin: res.data});
});
}
addMedecin(){
this.props.history.push('/addMedecin');
}
render() {
return (
<div>
<h2 className="text-center" >Liste des medecins</h2>
<div className= "row">
<button className="btn btn-primary" onClick={this.addMedecin} >Ajouter un médecin</button>
</div>
<div className = "row">
<table className = "table table-striped table-bordered">
<thead>
<tr>
<th> Nom Médecin</th>
<th> <NAME></th>
<th> CNI</th>
<th> Email</th>
<th> Password</th>
<th> Centre de vaccination</th>
<th> Actions</th>
</tr>
</thead>
<tbody>
{
this.state.medecin.map(
medecin =>
<tr key = {medecin.id}>
<td> {medecin.nom} </td>
<td> {medecin.prenom} </td>
<td> {medecin.cni} </td>
<td> {medecin.email} </td>
<td> {medecin.password} </td>
<td> {medecin.centre_vaccination} </td>
<td>
<button onClick = { () =>this.editMedecin(medecin.id)} className="btn btn-info" >Modifier</button>
<button style = {{marginLeft: "10px"}} onClick = { () =>this.deleteMedecin(medecin.id)} className="btn btn-danger" >Supprimer</button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
);
}
}
export default ListMedecinComponent;<file_sep>import React, { Component } from 'react';
import PatientDataService from '../components/services/PatientDataService';
const options = [
{ label: "Hypertension artérielle", value: "Hypertension artérielle" },
{ label: "Valvulopathie", value: "Valvulopathie" },
{ label: "Cardiomypathies", value: "Cardiomypathies" },
{ label: "Asthmes", value: "Asthmes" },
{ label: "Diabète type1", value: "Diabète type1" },
{ label: "Diabète type2", value: "Diabète type2" },
{ label: "Cancer", value: "Cancer" }
];
class FicheComponent extends Component {
constructor(props){
super(props)
this.state={
id: this.props.match.params.id,
cin:'',
nom:'',
prenom:'',
age: '',
sexe: '',
adresse:'',
email:'',
tel:'',
atcds:'',
etatDeVaccination:'',
dateDePremereDose:'',
dateDeuxiemeeDose:'',
effetsInds:'',
observations:''
}
this.changeCinHandler=this.changeCinHandler.bind(this);
this.changeNomHandler=this.changeNomHandler.bind(this);
this.changePrenomHandler=this.changePrenomHandler.bind(this);
this.changeAgeHandler=this.changeAgeHandler.bind(this);
this.changeSexeHandler=this.changeSexeHandler.bind(this);
this.changeAdresseHandler=this.changeAdresseHandler.bind(this);
this.changeEmailHandler=this.changeEmailHandler.bind(this);
this.changeTelHandler=this.changeTelHandler.bind(this);
this.changeATCDHandler=this.changeATCDHandler.bind(this);
this.changeEtatHandler=this.changeEtatHandler.bind(this);
this.changePremiereHandler=this.changePremiereHandler.bind(this);
this.changeDeuxiemeHandler=this.changeDeuxiemeHandler.bind(this);
this.changeEffetHandler=this.changeEffetHandler.bind(this);
this.changeObservationsHandler=this.changeObservationsHandler.bind(this);
this.fichePatient=this.fichePatient.bind(this);
}
componentDidMount(){
PatientDataService.getPatientById(this.state.id).then((res) =>{
let patient=res.data;
this.setState({
cin:patient.cin,
nom:patient.nom,
prenom:patient.prenom,
age:patient.age,
sexe:patient.sexe,
adresse:patient.adresse,
email:patient.email,
tel:patient.tel,
atcds:patient.atcds,
etatDeVaccination:patient.etatDeVaccination,
dateDePremereDose:patient.dateDePremereDose,
dateDeuxiemeeDose:patient.dateDeuxiemeeDose,
effetsInds:patient.effetsInds,
observations:patient.observations,
});
});
}
fichePatient= (e)=>{
e.preventDefault();
let patient={cin:this.state.cin, nom:this.state.nom, prenom:this.state.prenom, age:this.state.age, sexe:this.state.sexe,adresse:this.state.adresse,email:this.state.email,tel:this.state.tel ,atcds:this.state.atcds ,etatDeVaccination:this.state.etatDeVaccination ,dateDePremereDose:this.state.dateDePremereDose ,dateDeuxiemeeDose:this.state.dateDeuxiemeeDose ,effetsInds:this.state.effetsInds ,observations:this.state.observations};
console.log('patient=>'+ JSON.stringify(patient));
PatientDataService.fichePatient(patient, this.state.id).then(res =>{
this.props.history.push('/patients');
});
}
changeCinHandler=(event)=>{
this.setState({cin:event.target.value})
}
changeNomHandler=(event)=>{
this.setState({nom:event.target.value})
}
changePrenomHandler=(event)=>{
this.setState({prenom:event.target.value})
}
changeAgeHandler=(event)=>{
this.setState({age:event.target.value})
}
changeSexeHandler=(event)=>{
this.setState({sexe:event.target.value})
}
changeAdresseHandler=(event)=>{
this.setState({adresse:event.target.value})
}
changeEmailHandler=(event)=>{
this.setState({email:event.target.value})
}
changeTelHandler=(event)=>{
this.setState({tel:event.target.value})
}
changeATCDHandler=(event)=>{
this.setState({atcds:event.target.value})
}
changeEtatHandler=(event)=>{
this.setState({etatDeVaccination:event.target.value})
}
changePremiereHandler=(event)=>{
this.setState({dateDePremereDose:event.target.value})
}
changeDeuxiemeHandler=(event)=>{
this.setState({dateDeuxiemeeDose:event.target.value})
}
changeEffetHandler=(event)=>{
this.setState({effetsInds:event.target.value})
}
changeObservationsHandler=(event)=>{
this.setState({observations:event.target.value})
}
cancel(){
this.props.history.push('/patients');
}
render() {
return (
<div className="outer">
<div className="inner">
<form className="" action="">
<h3 classNam="text-center">Fiche de patient </h3>
<div className="form-row">
<div className="form-group col fly">
<input placeholder="CIN" name="cin" className="form-control" value={this.state.cin} onChange={this.changeCinHandler} />
</div>
<div className="form-group col fly">
<input placeholder="Nom" name="nom" className="form-control" value={this.state.nom} onChange={this.changeNomHandler} />
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<input placeholder="Prenom" name="prenom" className="form-control" value={this.state.prenom} onChange={this.changePrenomHandler} />
</div>
<div className="form-group col fly">
<input placeholder="Age" name="age" className="form-control" value={this.state.age} onChange={this.changeAgeHandler} />
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<input placeholder="Sexe" name="sexe" className="form-control" value={this.state.sexe} onChange={this.changeSexeHandler} />
</div>
<div className="form-group col fly">
<input placeholder="Adresse" name="adresse" className="form-control" value={this.state.adresse} onChange={this.changeAdresseHandler} />
</div>
</div>
<div className="form-row">
<div className="form-group col fly">
<input placeholder="E-mail" name="email" className="form-control" value={this.state.email} onChange={this.changeEmailHandler} />
</div>
<div className="form-group col fly">
<input placeholder="Numero du télephone" name="tel" className="form-control" value={this.state.tel} onChange={this.changeTelHandler} />
</div>
</div>
<div className="form-group">
<input placeholder="ATCDs" class=" form-control" name="ATCDs" className="form-control" value={this.state.atcds} onChange={this.changeATCDHandler}/>
</div>
<div className="form-group">
<input placeholder="Etat de vaccination" name="etatDeVaccination" className="form-control" value={this.state.etatDeVaccination} onChange={this.changeEtatHandler} />
</div>
<div className="form-group">
<input type="date" dateFormat="yyyy/MM/dd" name="dateDePremereDose" className="form-control" value={this.state.dateDePremereDose} onChange={this.changePremiereHandler} />
</div>
<div className="form-group">
<input type="date" dateFormat="yyyy/MM/dd" name="dateDeuxiemeDose" className="form-control" value={this.state.dateDeuxiemeeDose} onChange={this.changeDeuxiemeHandler} />
</div>
<div className="form-group">
<input placeholder="Effets indésirables" name="effetsInds" className="form-control" value={this.state.effetsInds} onChange={this.changeEffetHandler} />
</div>
<div className="form-group">
<textarea type="textarea" placeholder="Observations" name="observations" className="form-control" rows="3" value={this.state.observations} onChange={this.changeObservationsHandler}></textarea>
</div>
<button className="btn btn-success" onClick={this.fichePatient}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} styme={{margingLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
);
}
}
export default FicheComponent;<file_sep>import React, { Component } from 'react';
import RendezVousService from './services/RendezVousService';
import PatientDataService from '../components/services/PatientDataService';
class LissteRdvsComponent extends Component {
constructor(props){
super(props)
this.state={
patients: []
}
}
componentDidMount(){
PatientDataService.retrieveAllPatients().then((res)=>{
this.setState({patients: res.data});
});
}
render() {
return (
<div>
<h2 className="text-center">Liste des Rendez Vous</h2>
<div className= "row">
<table className="table table-striped table-borded">
<thead>
<tr>
<th>CIN</th>
<th>Nom</th>
<th>Prénom</th>
<th>Date 1ére dose</th>
<th>Date 2éme dose</th>
</tr>
</thead>
<tbody>
{
this.state.patients.map(
patients=>
<tr key ={patients.id}>
<td>{patients.cin}</td>
<td>{patients.nom}</td>
<td>{patients.prenom}</td>
<td>{patients.dateDePremereDose}</td>
<td>{patients.dateDeuxiemeeDose}</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
);
}
}
export default LissteRdvsComponent;<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Alert } from "react-bootstrap"
import { Link } from "react-router-dom";
import MedecinService from '../components/services/MedecinService';
const validEmailRegex = RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);
const validateForm = (errors) => {
let valid = true;
Object.values(errors).forEach(
(val) => val.length > 0 && (valid = false)
);
return valid;
}
class CreateMedecinComponent extends Component {
constructor(props) {
super(props);
this.state ={
nom: '',
prenom: '',
cni: "",
email: "",
password: "",
centre_vaccination: "",
successful: false,
validForm: true,
errors: {
nom: '',
prenom: '',
cni: '',
email: '',
password: ''
}
}
this.saveMedecin = this.saveMedecin.bind(this);
this.changeHandler = this.changeHandler.bind(this);
}
saveMedecin = (e) => {
e.preventDefault();
const valid = validateForm(this.state.errors);
this.setState({validForm: valid});
if(valid){
let medecin ={nom: this.state.nom, prenom: this.state.prenom,cni: this.state.cni, email: this.state.email, password: this.state.password, centre_vaccination: this.state.centre_vaccination};
console.log('medecin => ' + JSON.stringify(medecin));
MedecinService.createMedecin(medecin).then(res =>{
this.props.history.push('/Medecins');
});
}
}
changeHandler = (event) => {
const { name, value } = event.target;
let errors = this.state.errors;
switch (name) {
case 'nom':
errors.nom =
value.length < 3
? 'Le nom doit contenir 3 carctères au minimum'
: '';
break;
case 'prenom':
errors.prenom =
value.length < 3
? 'Le prenom doit contenir 3 carctères au minimum'
: '';
break;
case 'cni':
errors.cni =
value.length < 5
? 'La CIN doit avoit 5 carctères au minimum'
: '';
break;
case 'email':
errors.email =
validEmailRegex.test(value)
? ''
: 'le mail n est pas valide';
break;
case 'password':
errors.password =
value.length < 8
? 'Le mot de passe doit avoir 8 carctères au minimum'
: '';
break;
default:
break;
}
this.setState({errors, [name]: value}, ()=> {
console.log(errors)
})
}
cancel(){
this.props.history.push('/Medecins');
}
render() {
const errors = this.state.errors;
let alert = "";
if(this.state.message){
if(this.state.successful){
alert = (
<Alert variant="success">
{this.state.message}
</Alert>
);
}else{
alert = (
<Alert variant="danger">
{this.state.message}
</Alert>
);
}
}
return (
<div>
<div className = 'container'>
<div className = 'row'>
<div className = 'card col-md-6 offset-md-3 offset-md-3'>
<h3 className = "text-center">Ajouter un médecin</h3>
<div className = "cart-body ">
<form onSubmit={this.saveMedecin}>
<div className = "form-group">
<label> Nom Médecin:</label>
<input placeholder="<NAME>" name="nom" id="nom" className="form-control" value={this.state.nom} onChange={this.changeHandler} required/>
{
errors.nom && (
<Alert variant="danger">
{errors.nom}
</Alert>
)
}
</div>
<div className = "form-group">
<label> Pré<NAME>:</label>
<input placeholder="<NAME>" name="prenom" id="prenom" className="form-control" value={this.state.prenom} onChange={this.changeHandler} required/>
{
errors.prenom && (
<Alert variant="danger">
{errors.prenom}
</Alert>
)
}
</div>
<div className = "form-group">
<label> CNI:</label>
<input placeholder="CNI" name="cni" id="cni" className="form-control" value={this.state.cni} onChange={this.changeHandler} required/>
{
errors.cni && (
<Alert variant="danger">
{errors.cni}
</Alert>
)
}
</div>
<div className = "form-group">
<label> Email:</label>
<input placeholder="Email" name="email" id="email" className="form-control" type="email" value={this.state.email} onChange={this.changeHandler} required/>
{
errors.email && (
<Alert variant="danger">
{errors.email}
</Alert>
)
}
</div>
<div className = "form-group">
<label> Password:</label>
<input placeholder="<PASSWORD>" name="password" id="password" className="form-control" type="password" value={this.state.password} onChange={this.changeHandler} required minLength="6" maxLength="20"/>
{
errors.password && (
<Alert key="errorspassword" variant="danger">
{errors.password}
</Alert>
)
}
</div>
<div className = "form-group">
<label> Centre de vaccination:</label>
<select class="select form-control" name="centre_vaccination" value={this.state.centre_vaccination} onChange={this.changeHandler} required>
<option value="CHU">
CHU
</option>
<option value="Ibn Tofail">
Ibn Tofail
</option>
<option value="Ibn Sina">
Ibn Sina
</option>
<option value="Rabat_Agdal">
Rabat_Agdal
</option>
<option value="Rabat_Riad">
Rabat Riad
</option>
<option value="Tanger_ville">
Tanger_ville
</option>
<option value="Kenitra">
Kenitra
</option>
<option value="Fes">
Fes
</option>
<option value="Marrakech">
Marrakech
</option>
<option value="Meknes">
Meknes
</option>
</select>
</div>
<button className="btn btn-success" onClick={this.saveMedecin}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
{
!this.state.validForm && (
<Alert key="validForm" variant="danger">
Veuillez vérifier les champs entrés
</Alert>
)
}
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default CreateMedecinComponent;<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import MedecinService from '../components/services/MedecinService';
class UpdateMedecinComponent extends Component {
constructor(props) {
super(props);
this.state ={
id: this.props.match.params.id,
nom: '',
prenom: '',
cni: "",
email: "",
password: "",
centre_vaccination: "",
}
this.changeNomMedecinHandler = this.changeNomMedecinHandler.bind(this);
this.changePrenomMedecinHandler = this.changePrenomMedecinHandler.bind(this);
this.updateMedecin = this.updateMedecin.bind(this);
}
componentDidMount(){
MedecinService.getMedecinById(this.state.id).then( (res) =>{
let medecin =res.data;
this.setState({nom: medecin.nom,
prenom: medecin.prenom,
cni: medecin.cni,
email: medecin.email,
password: <PASSWORD>,
centre_vaccination: medecin.centre_vaccination,
});
});
}
updateMedecin = (e) => {
e.preventDefault();
let medecin ={nom: this.state.nom, prenom: this.state.prenom,cni: this.state.cni, email: this.state.email, password: <PASSWORD>, centre_vaccination: this.state.centre_vaccination};
console.log('medecin => ' + JSON.stringify(medecin));
MedecinService.updateMedecin(medecin, this.state.id).then( res => {
this.props.history.push('/Medecins');
});
}
changeNomMedecinHandler= (event) => {
this.setState({nom: event.target.value});
}
changePrenomMedecinHandler= (event) => {
this.setState({prenom: event.target.value});
}
changeCniMedecinHandler= (event) => {
this.setState({cni: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({email: event.target.value});
}
changePasswordHandler= (event) => {
this.setState({password: event.target.value});
}
changecentreHandler= (event) => {
this.setState({centre_vaccination: event.target.value});
}
cancel(){
this.props.history.push('/Medecins');
}
render() {
return (
<div>
<div className = 'container'>
<div className = 'row'>
<div className = 'card col-md-6 offset-md-3 offset-md-3'>
<h3 className = "text-center">Modifier les informations d'un médecin</h3>
<div className = "cart-body ">
<form>
<div className = "form-group">
<label> Nom Médecin:</label>
<input placeholder="<NAME>" name="nom" className="form-control" value={this.state.nom} onChange={this.changeNomMedecinHandler}/>
</div>
<div className = "form-group">
<label> Prénom Médecin:</label>
<input placeholder="<NAME>" name="prenom" className="form-control" value={this.state.prenom} onChange={this.changePrenomMedecinHandler}/>
</div>
<div className = "form-group">
<label> CNI:</label>
<input placeholder="CNI" name="cni" className="form-control" value={this.state.cni} onChange={this.changeCniMedecinHandler}/>
</div>
<div className = "form-group">
<label> Email:</label>
<input placeholder="Email" name="email" className="form-control" value={this.state.email} onChange={this.changeEmailHandler}/>
</div>
<div className = "form-group">
<label> Password:</label>
<input placeholder="<PASSWORD>" name="password" className="form-control" type="<PASSWORD>" value={this.state.password} onChange={this.changePasswordHandler}/>
</div>
<div className = "form-group">
<label> Centre de vaccination:</label>
<input placeholder="Centre de vaccination" name="centre_vaccination" className="form-control" value={this.state.centre_vaccination} onChange={this.changecentreHandler}/>
</div>
<button className="btn btn-success" onClick={this.updateMedecin}>Enregistrer</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default UpdateMedecinComponent;<file_sep>import React, { Component } from 'react';
import Royaume from './Royaume.jpeg';
class HeaderComponent extends Component {
constructor(props){
super(props)
this.state={
}
}
render() {
return (
<div>
<header>
<div class="header">
<img src={Royaume} width="650" height="100" alt="Hello" ></img>
<a href="/Accueil" class="logo md-3">Vaccination COVID19</a>
<div class="header-right">
<a href="/editprofile">Profil</a>
</div>
<nav id="navbar" class="navbar order-last order-lg-0">
<ul >
<li><a class="nav-link scrollto " href="/Accueil">Home</a></li>
<li><a class="nav-link scrollto " href="/vaccin">Informations sur le vaccin</a></li>
<li><a class="nav-link scrollto " href="/faq">F.A.Q</a></li>
<li><a class="nav-link scrollto " href="/infos">Statistiques vaccination</a></li>
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav>
</div>
</header>
</div>
);
}
}
export default HeaderComponent;<file_sep>import React, { Component } from 'react';
import AuthenticationService from '../components/services/AuthentificationService';
import { Alert } from "react-bootstrap"
import { Link } from "react-router-dom";
import declarationservice from '../components/services/declarationservice';
import { Form } from 'react-bootstrap';
import Select from 'react-select';
import { getElementError } from '@testing-library/dom';
import {Helmet} from "react-helmet";
import $ from 'jquery';
class effets extends Component {
constructor(props) {
super(props);
this.state = {
nom: "",
prenom: "",
cin: "",
effets: "",
autre:"",
user: undefined,
message: "",
successful: false,
selectedOption: null,
};
}
/*componentDidMount() {
}*/
componentDidMount() {
const user = AuthenticationService.getCurrentUser();
this.setState({user: user});
document.body.style.background = "white";
AuthenticationService.getPatient(user.cin).then(
response => {
this.setState({
nom:response.data.nom,
prenom:response.data.prenom,
cin:response.data.cin
})
},
);
}
Effets = (e) => {
e.preventDefault();
declarationservice.declaration(
this.state.cin,
this.state.effets,
this.state.autre,
).then(
response => {
this.setState({
message: "Déclaration envoyée avec succès",
successful: true
});
},
error => {
console.log("Fail! Error = " + error.toString());
}
);
}
changeeffetHandler=(event)=>{
this.setState({effets:event.target.value})
}
changeautreHandler=(event)=>{
this.setState({autre:event.target.value})
}
render() {
const { selectedOption } = this.state;
let alert = "";
if(this.state.message){
if(this.state.successful){
alert = (
<Alert variant="success">
{this.state.message}
</Alert>
);
}else{
alert = (
<Alert variant="danger">
{this.state.message}
</Alert>
);
}
}
let userInfo = "";
const user = this.state.user;
return (
<div>
<div className="container-fluid rounded">
<div className="row px-5">
<div className="col-sm-6">
<div>
<h3 className="text-white">Événements indésirables après vaccination</h3>
<p className="text-secondary">Suivez votre état de santé vaccinale et déclarez tout évènement observé après vaccination contre le virus de la covid-19 sur le site</p>
</div>
<div className="links" id="bordering"> <a href=" " className="btn rounded text-white p-3">
<i className="fa fa-phone icon text-primary pr-3"></i>0800000147</a>
<a href=" " className="btn rounded text-white p-3"><i className="fa fa-envelope icon text-primary pr-3">
</i><EMAIL></a> <a href=" " className="btn rounded text-white p-3">
<i className="fa fa-map-marker icon text-primary pr-3"></i>102 street 2714 Don</a> </div>
<div className="pt-lg-4 d-flex flex-row justify-content-start">
<div className="pad-icon"> <a className="fa fa-facebook text-white" href=" "></a> </div>
<div className="pad-icon"> <a className="fa fa-twitter text-white" href=" "></a> </div>
<div className="pad-icon"> <a className="fa fa-instagram text-white" href=" "></a> </div>
</div>
</div>
<div className="col-sm-6 pad">
<form className="rounded msg-form" onSubmit={this.Effets}>
<div className="form-group row">
<div className="col-md-6">
<label for="name" class="h6">Nom</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<p className=" text-primary"></p>
</div> <input type="text" value={this.state.nom} className="form-control border-0"required disabled/>
</div>
</div>
<div className="col-md-6">
<label for="name" class="h6">Prenom</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<p className=" text-primary"></p>
</div> <input type="text" value={this.state.prenom} className="form-control border-0"required disabled/>
</div> </div>
</div>
<div className="form-group row">
<div className="col-md-6">
<label for="name" className="h6">CIN</label>
<div className="input-group border rounded">
<div className="input-group-addon px-2 pt-1">
<i class="text-primary"></i> </div> <input type="text" class="form-control border-0" value={this.state.cin} required disabled/>
</div>
</div>
<div className="col-md-6">
<div className="form-group"> <label for="form_need">Selectectioner l'effet*</label> <select id="form_need" name="need" value={this.state.effets}
onChange={this.changeeffetHandler} className="form-control" required="required" data-error="Please specify your need.">
<option selected>Choisir...</option>
<option value="fatigue">fatigue</option>
<option value="maux de tête">maux de tête</option>
<option value="douleurs articulaires">douleurs articulaires</option>
<option value="frissons, fièvre">frissons, fièvre</option>
<option value="rougeur au site d'injection">rougeur au site d'injection</option>
<option value="nausées">nausées</option>
<option value="gonflement des ganglions lymphatiques">gonflement des ganglions lymphatiques</option>
<option value="sensation de malaise">sensation de malaise</option>
<option value="douleur dans les membres">douleur dans les membres</option>
<option value="insomnies">insomnies</option>
<option>Autre</option>
</select> </div>
</div>
</div>
<div className="form-group"> <label for="msg" className="h6">Autre</label>
<textarea name="message" value={this.state.autre} onChange={this.changeautreHandler} id="msgus" cols="10" rows="5" className="form-control bg-light" placeholder="Message">
</textarea> </div>
<div className="form-group d-flex justify-content-end">
<input type="submit" className="btn btn-primary text-white" value="envoyer la delaration"/> </div>
{alert}
</form>
</div>
</div>
</div>
</div>
);
}
}
export default effets;<file_sep>import userEvent from "@testing-library/user-event";
import axios from "axios";
class declarationservice {
declaration = async( cin, effets,autres) => {
return axios.post("http://localhost:8081/api/auth/declarations", {
cin,
effets,
autres
});
}
}
export default new declarationservice();
|
160ffd787b4240013d55f310f546e30639e0bdb5
|
[
"JavaScript"
] | 22 |
JavaScript
|
fadwab-hp/Vaccination-Covid19
|
7155d1970dd6545ed5b64c5c05bf18acf5ca7b27
|
082b8187dfb76c10a8f7104aa1a82c66d571bc4f
|
refs/heads/master
|
<file_sep>
identity = '지구인'
number_of_leg = 4
print('안녕! 나는', identity, '이야. 나는 다리가 ', number_of_leg , '개 있어.')
identity = '한국인'
number_of_leg = 2
#number_of_leg = 3
print('안녕! 나는', identity, '이야. 나는 다리가 ', number_of_leg , '개 있어.')
"""
identity = '한국인'
number_of_leg = 2
#number_of_leg = 3
print('안녕! 나는', identity, '이야. 나는 다리가 ', number_of_leg , '개 있어.')
identity = '한국인'
number_of_leg = 2
#number_of_leg = 3
print('안녕! 나는', identity, '이야. 나는 다리가 ', number_of_leg , '개 있어.')
identity = '한국인'
number_of_leg = 2
#number_of_leg = 3
print('안녕! 나는', identity, '이야. 나는 다리가 ', number_of_leg , '개 있어.')
"""<file_sep>
my_name = 'Python' #문자열 (사람을 위한 텍스트를 프로그래머가 부르는 방법)
my_age = 2019 - 1994 #숫자
print(my_name, '<NAME>', my_age, '살')
my_next_age = my_age + 1
print('내년에는', my_next_age, '살')
multiply = 9 * 9 # = 81
divide = 30 / 5 # = 6
power = 2 ** 10 # = 1024
reminder = 15 % 4 # = 3
print(multiply, divide, power, reminder)
text = '2015' + '1999'
number = 2015 + 1999
print(text, number)<file_sep>
identity = '지구인'
number_of_leg = 4
print('안녕! 나는', identity, '이야. 나는 다리가 ', number_of_leg , '개 있어.')
identity = '한국인'
number_of_leg = 2
print('안녕! 나는', identity, '이야. 나는 다리가 ', number_of_leg , '개 있어.')
|
a379654f7982e0727f558be1de04861946375861
|
[
"Python"
] | 3 |
Python
|
Ryuseo/Python_Edu
|
82690e43f5703576909e5dcb7900c6485c7716cb
|
cd0d59efcbdab78ba3e289c038503ca695fbe6f6
|
refs/heads/master
|
<repo_name>styras/Gaggle<file_sep>/components/Signin/Signin.js
import React, { Component } from 'react';
import { Alert, View, Image } from 'react-native';
import { Container, Header, Footer, Content, Form, Item, Input, Icon, Button, Text } from 'native-base';
import { firebaseRef, firebaseDB } from '../../firebase/firebaseHelpers';
import GroupView from './../../components/GroupView/GroupView';
import * as Animatable from 'react-native-animatable';
const styles = {
marginBottom: {
marginBottom: 10,
},
};
export default class Signin extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
showSignUp: true,
};
this._authChangeListener();
this._handleChangePage = this._handleChangePage.bind(this);
this.signup = this.signup.bind(this);
this.signin = this.signin.bind(this);
this.logout = this.logout.bind(this);
}
_authChangeListener() {
this.unsubscribe = firebaseRef.auth().onAuthStateChanged((user) => {
if (user) {
setTimeout(() => {
firebaseDB.ref(`users/${user.uid}`).once('value')
.then((snapshot) => { this._handleChangePage(snapshot.val()); });
}, 1000);
}
});
}
_sendSignInAlert(error) {
Alert.alert(
'Oooops',
`\nLooks like there was a problem. Are you already a member? Double check your inputs, and please try your request again.\n\n${error}`,
{ cancelable: false },
);
}
_sendLogOutAlert(error) {
Alert.alert(
'Log Out Failure',
`\nThere was an error with logging you out.\n\n${error}`,
{ cancelable: false },
);
}
_handleChangePage(user) {
// Unsubscribe from auth listener
this.unsubscribe();
this.props.navigator.push({
component: GroupView,
title: 'Your Groups',
leftButtonTitle: 'Log Out',
onLeftButtonPress: () => {
this.logout();
},
passProps: {
user,
},
});
}
signup() {
firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(() => {
const user = firebaseRef.auth().currentUser;
const displayName = user.email.split('@')[0];
user.updateProfile({
displayName,
})
.then(() => {
const newUserObj = {
displayName: user.displayName,
email: user.email,
location: {
coords: {
accuracy: 5,
altitude: 0,
altitudeAccuracy: -1,
heading: -1,
latitude: 33.812092,
longitude: -117.918974,
speed: -1,
},
},
uid: user.uid,
};
firebaseDB.ref(`users/${user.uid}`).set(newUserObj);
}, (error) => { this._sendSignInAlert(error); });
})
.catch((error) => { this._sendSignInAlert(error); });
}
signin() {
firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
.catch((error) => { this._sendSignInAlert(error); });
}
logout() {
firebaseRef.auth().signOut().then(() => {
this.setState({
email: '',
password: '',
});
this.props.navigator.pop();
this._authChangeListener();
}, (error) => { this._sendLogOutAlert(error); });
}
render() {
return (
<Container style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Header />
<Content style={{ padding: 10 }}>
<View style={{ width: 350 }}>
<Animatable.View
style={{
justifyContent: 'center',
alignItems: 'center',
}}
animation={'fadeIn'}
duration={2000}
>
<Image
source={require('../../images/logo.png')}
style={{
width: 200,
height: 200,
}}
/>
<Text
style={{
paddingTop: 10,
fontSize: 20,
}}
>
Keep track of <Text style={{ fontStyle: 'italic', fontSize: 20, }}>your</Text> flock!
</Text>
</Animatable.View>
<Form style={{}}>
<Animatable.View animation={'fadeInUp'} duration={500}>
<Item style={styles.marginBottom} regular>
<Input
ref={(component) => { this._emailInput = component; }}
onChangeText={(text) => { this.setState({ email: text }); }}
placeholder={'Email'}
autoCapitalize={'none'}
value={this.state.email}
/>
{/.+@.+\..+/i.test(this.state.email) && <Icon name={'checkmark-circle'} style={{ color: 'green' }} />}
</Item>
</Animatable.View>
<Animatable.View animation={'fadeInUp'} delay={200} duration={500}>
<Item regular>
<Input
ref={(component) => { this._passwordInput = component; }}
onChangeText={(text) => { this.setState({ password: text }); }}
placeholder={'Password 6+ <PASSWORD>'}
autoCapitalize={'none'}
value={this.state.password}
secureTextEntry
/>
{this.state.password.length >= 6 && <Icon name={'checkmark-circle'} style={{ color: 'green' }} />}
{this.state.password.length <= 5 && this.state.password.length > 0 && <Icon name={'close-circle'} style={{ color: 'red' }} />}
</Item>
</Animatable.View>
</Form>
<Animatable.View animation={'fadeInUp'} delay={400} duration={500}>
{this.state.showSignUp ?
<Button
style={{ padding: 5, alignSelf: 'center' }}
onPress={() => this.setState({ showSignUp: false })}
transparent
>
<Text>Already registered?</Text>
</Button> :
<Button
style={{ padding: 5, alignSelf: 'center' }}
onPress={() => this.setState({ showSignUp: true })}
transparent
>
<Text>{'Don\'t have an account?'}</Text>
</Button>
}
</Animatable.View>
<Animatable.View animation={'fadeInUp'} delay={600} duration={500}>
{this.state.showSignUp ?
<Button
disabled={this.state.password.length < 6}
onPress={this.signup}
style={{ width: 350 }}
>
<View style={{ flex: 1 }}>
<Text style={{ textAlign: 'center' }}>Sign up</Text>
</View>
</Button> :
<Button
disabled={this.state.password.length < 6}
onPress={this.signin}
style={{ width: 350 }}
>
<View style={{ flex: 1 }}>
<Text style={{ textAlign: 'center' }}>Sign in</Text>
</View>
</Button>
}
</Animatable.View>
</View>
</Content>
<Footer />
</Container>
);
}
}
Signin.propTypes = {
navigator: React.PropTypes.object.isRequired,
};
<file_sep>/uber/config.example.js
export const clientID = 'UBER_CLIENT_ID';
<file_sep>/components/GroupMapChat/GroupMapChat.js
import React, { Component } from 'react';
import { Container, Content, Tab, Tabs, TabHeading, Icon, Text, Header } from 'native-base';
import Chat from '../Chat/Chat';
import MapDisplay from '../MapDisplay/MapDisplay';
import PollList from '../Polls/PollList';
export default class GroupMapChat extends Component {
constructor(props) {
super(props);
this.state = {
user: this.props.user,
};
}
render() {
return (
<Container>
<Header hasTabs />
<Content scrollEnabled={false}>
<Tabs>
<Tab heading={<TabHeading><Icon name="compass" /><Text>Map</Text></TabHeading>}>
<MapDisplay
user={this.props.user}
groupName={this.props.groupName ? this.props.groupName : 'Default'}
navigator={this.props.navigator}
/>
</Tab>
<Tab heading={<TabHeading><Icon name="chatboxes" /><Text>Chat</Text></TabHeading>}>
<Chat user={this.state.user} groupName={this.props.groupName ? this.props.groupName : 'Default'} />
</Tab>
<Tab heading={<TabHeading><Icon name="checkbox" /><Text>Polls</Text></TabHeading>}>
<PollList navigator={this.props.navigator} user={this.state.user} groupName={this.props.groupName ? this.props.groupName : 'Default'} />
</Tab>
</Tabs>
</Content>
</Container>
);
}
}
GroupMapChat.propTypes = {
user: React.PropTypes.object.isRequired,
groupName: React.PropTypes.string.isRequired,
navigator: React.PropTypes.object.isRequired,
};
<file_sep>/components/Search/Stars.js
import React from 'react';
import { View } from 'react-native';
import { Icon } from 'native-base';
import times from 'lodash/times';
const Stars = (props) => {
let counter = -1;
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
{times(props.stars, () => {
counter += 1;
return (<Icon key={counter} active name={'star'} style={{ color: '#FEBF00', fontSize: 20 }} />);
})}
</View>
);
};
Stars.propTypes = {
stars: React.PropTypes.number.isRequired,
};
export default Stars;
<file_sep>/__tests__/CategoryButton.js
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import CategoryButton from '../components/Search/CategoryButton';
describe('CategoryButton', () => {
it('renders correctly', () => {
const tree = renderer.create(
<CategoryButton category={'Fun'} getSuggestions={() => {}} />,
);
expect(tree).toMatchSnapshot();
});
});
<file_sep>/components/Search/Minimap.js
import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import MapView from 'react-native-maps';
import { getUserLocation } from '../../location/locationHelpers';
export default class Minimap extends Component {
constructor(props) {
super(props);
this.state = {
myLocation: [0, 0],
};
getUserLocation().then((myLocation) => {
this.setState({ myLocation });
});
setTimeout(() => {
if (this.refs.map) {
this.refs.map.fitToElements(true);
}
}, 2000);
}
render() {
return (
<MapView
ref='map'
style={{ height: 150, width: Dimensions.get('window').width }}
region={{
latitude: this.props.coords[0],
longitude: this.props.coords[1],
latitudeDelta: 0.2,
longitudeDelta: 0.2,
}}
showsUserLocation
>
<MapView.Marker
coordinate={{ latitude: this.props.coords[0], longitude: this.props.coords[1] }}
title={this.props.placeName}
/>
</MapView>
);
}
}
Minimap.propTypes = {
coords: React.PropTypes.array.isRequired,
placeName: React.PropTypes.string.isRequired,
};
<file_sep>/components/Quiz/Quiz.js
import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import { Container, Content, Header, DeckSwiper, Card, CardItem, Body, Text, Button, Icon, H3 } from 'native-base';
import * as he from 'he';
import getTriviaQuestions from '../../opentdb/opentdbHelpers';
const styles = {
answerButton: {
height: 40,
width: Dimensions.get('window').width - 35,
justifyContent: 'flex-start',
}
};
export default class Quiz extends Component {
constructor(props) {
super(props);
this.state = {
questions: [],
};
}
componentDidMount() {
this.getNewQuestions(10);
}
getNewQuestions = (num) => {
getTriviaQuestions(num)
.then(questions => {
const questionsCopy = questions.slice();
questionsCopy.forEach((obj, index) => {
// Replace HTML entities
obj.question = he.decode(obj.question);
obj.correct_answer = he.decode(obj.correct_answer);
obj.incorrect_answers = obj.incorrect_answers.map(answer => he.decode(answer));
// Store array index for answer lookup
obj.index = index;
// Shuffle all answers for user display
obj.shuffled = obj.incorrect_answers.concat(obj.correct_answer);
this._shuffle(obj.shuffled);
// Add variables to show incorrect or correct
obj.showCorrect = false;
obj.showIncorrect = false;
});
this.setState({ questions: questionsCopy });
});
}
checkAnswer = (index, answer) => {
const currentQuestion = this.state.questions[index];
if (currentQuestion.answered) { return; }
if (currentQuestion.correct_answer === answer) {
currentQuestion.showCorrect = true;
currentQuestion.answered = true;
} else {
currentQuestion.showIncorrect = true;
currentQuestion.answered = true;
}
// Trigger rerender in a suboptimal way
this.setState({ questions: this.state.questions });
}
_shuffle(a) {
for (let i = a.length; i; i--) {
let j = Math.floor(Math.random() * i);
[a[i - 1], a[j]] = [a[j], a[i - 1]];
}
}
render() {
return (
<Container>
<Header />
<Content scrollEnabled={false}>
{this.state.questions.length > 0 &&
<DeckSwiper
dataSource={this.state.questions}
renderItem={question =>
<Card style={{ height: Dimensions.get('window').height - 75 }}>
<CardItem>
<Body>
<H3 style={{ marginTop: 10, marginBottom: 10 }}>{question.category}</H3>
<Text>{question.question.replace(/"/ig, '"')}</Text>
</Body>
</CardItem>
<CardItem>
{question.showCorrect && <Text>Correct</Text>}
{question.showIncorrect && <Text>Incorrect, the correct answer was: {question.correct_answer}</Text>}
</CardItem>
{question.shuffled.map(answer => (
<CardItem key={answer}>
<Button
style={styles.answerButton}
onPress={() => this.checkAnswer(question.index, answer)}
>
<Text>{answer}</Text>
</Button>
</CardItem>
))}
{question.index === 0 &&
<CardItem>
<Text>Swipe for more questions!</Text>
</CardItem>}
</Card>
}
/>
}
</Content>
</Container>
);
}
}
<file_sep>/google/googlePlaces.js
import GOOGLE_API_KEY from './config';
export const categories = ['Restaurants', 'Museums', 'Cafes', 'Shopping', 'Bars', 'Movies', 'Games', 'Recreation', 'Art', 'Music', 'Shows', 'Theaters', 'Skydiving'];
export const getResultsFromKeyword = (locationArray, keyword, radius) => {
const latitude = locationArray[0];
const longitude = locationArray[1];
const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=${radius}&keyword=${keyword}&key=${GOOGLE_API_KEY}`;
return new Promise((resolve, reject) => {
fetch(url)
.then(response => response.json())
.then(responseJson => resolve(responseJson))
.catch(error => reject(error));
});
};
export const getPlaceDetails = (placeId) => {
const url = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${placeId}&key=${GOOGLE_API_KEY}`;
return new Promise((resolve, reject) => {
fetch(url)
.then(response => response.json())
.then(responseJson => resolve(responseJson))
.catch(error => reject(error));
});
};
export const getPlacePhoto = (photoreference) => {
const url = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${photoreference}&key=${GOOGLE_API_KEY}`;
return new Promise((resolve, reject) => {
fetch(url)
.then((response) => { resolve(response.url); })
.catch(error => reject(error));
});
};
<file_sep>/giphy/giphyHelpers.js
export const isValidGiphyCommand = (string) => {
let giphyStringSplit;
// Check string exists and /giphy is first part
if (string && string.indexOf('/giphy') === 0) {
// Check if there is a space between command and keywords and keywords exist
giphyStringSplit = string.split(' ');
if (giphyStringSplit[0] === '/giphy' && giphyStringSplit[1]) {
return true;
}
}
return false;
};
export const parseGiphyCommand = (string) => {
const giphyStringSplit = string.split(' ');
return giphyStringSplit.slice(1).join(' ');
};
export const getGiphyResultFromKeyword = (keyword) => {
const url = `https://api.giphy.com/v1/gifs/random?api_key=<KEY>&tag=${keyword}`;
return new Promise((resolve, reject) => {
fetch(url)
.then(response => response.json())
.then(responseJSON => resolve(responseJSON.data))
.catch(error => reject(error));
});
};
export const replaceHTTPwithHTTPS = link => link.replace(/^http:\/\//i, 'https://');
<file_sep>/google/config.example.js
// Remember to enable Google Places API Web Service in the developer console!
export default 'GOOGLE_API_KEY';
<file_sep>/components/MapDisplay/MapDisplay.js
import React, { Component } from 'react';
import { View, Dimensions, Alert } from 'react-native';
import MapView from 'react-native-maps';
import { Fab, Icon, Button } from 'native-base';
import { firebaseDB, updateUserLocation } from '../../firebase/firebaseHelpers';
import { getUserLocation } from '../../location/locationHelpers';
import duckYellow from '../../images/duck_emoji_smaller.png';
import duckBlue from '../../images/duck_emoji_smaller_blue.png';
import duckGreen from '../../images/duck_emoji_smaller_green.png';
import duckPurple from '../../images/duck_emoji_smaller_purple.png';
import duckRed from '../../images/duck_emoji_smaller_red.png';
import Search from '../Search/Search';
export default class MapDisplay extends Component {
constructor(props) {
super(props);
this.state = {
currLoc: '',
markersArray: [],
user: props.user,
chirping: props.chirping,
userLocation: props.userLocation,
active: false,
};
this.goToSearch = this.goToSearch.bind(this);
this.playChirp = this.playChirp.bind(this);
this.chirp = this.chirp.bind(this);
}
componentWillMount() {
this.getMemberLocations(this.props.groupName);
getUserLocation().then((response) => {
this.setState({
currLoc: response,
});
});
}
componentDidMount() {
const map = this.refs.mymap;
const context = this;
this._fitToSuppliedMarkers = setTimeout(() => {
const markers = context.state.markersArray.map(marker => marker.displayName);
map.fitToSuppliedMarkers(markers, true);
}, 2500);
this._updateUserLocation = setInterval(() => {
updateUserLocation(this.props.groupName);
}, 15000);
this._updateMemberLocations = setInterval(() => {
this.getMemberLocations(this.props.groupName);
}, 10000);
}
componentWillUnmount() {
clearInterval(this._updateUserLocation);
clearInterval(this._updateMemberLocations);
clearTimeout(this._fitToSuppliedMarkers);
}
getMemberLocations(activeGroup) {
const markersArray = [];
firebaseDB.ref(`groups/${activeGroup}/members/`).once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
// if a member is chirping, call chirp function
if (childSnapshot.val().chirp === true) {
this.playChirp(childSnapshot.val().displayName, childSnapshot.val().location.coords);
}
markersArray.push({ coordinate: {
latitude: childSnapshot.val().location.coords.latitude,
longitude: childSnapshot.val().location.coords.longitude,
},
displayName: childSnapshot.val().displayName,
});
});
this.setState({ markersArray });
});
}
goToSearch() {
this.props.navigator.push({
component: Search,
title: 'Explore',
passProps: {
groupName: this.props.groupName,
},
});
}
chirp() {
const userId = this.state.user.uid;
const activeGroup = this.props.groupName;
const member = firebaseDB.ref(`groups/${activeGroup}/members/${userId}`);
member.update({
chirp: true,
})
.then(Alert.alert('Chirp sent!'))
.catch((error) => { console.log(`error ${error}`); });
setTimeout(() => {
member.update({
chirp: false,
})
.catch((error) => { console.log(`error ${error}`); });
}, 10000);
}
goToChirp(memberLocation) {
console.log('GO TO CHIRP CALLED');
const map = this.refs.mymap;
map.animateToCoordinate(memberLocation, 2);
}
playChirp(memberName, memberLocation) {
if (memberName != this.state.user.displayName) {
Alert.alert(
'Chirp!',
`${memberName} is chirping!`,
[
{ text: `Go to ${memberName}`,
onPress: () => {
this.goToChirp(memberLocation);
console.log('gotoChirp send');
},
},
{ text: 'Dismiss' },
],
);
}
}
render() {
console.log('RENDER CALLED');
const { width, height } = Dimensions.get('window');
const emojis = [duckYellow, duckBlue, duckGreen, duckPurple, duckRed];
return (
<View>
<MapView
ref="mymap"
style={{ width, height: height - 114 }}
initialRegion={{
latitude: this.state.currLoc ? this.state.currLoc[0] : 50,
longitude: this.state.currLoc ? this.state.currLoc[1] : -135,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
showsUserLocation
>
{this.state.markersArray.map((marker, i) => (
<MapView.Marker
key={i}
title={marker.displayName}
identifier={marker.displayName}
coordinate={{ latitude: marker.coordinate.latitude,
longitude: marker.coordinate.longitude }}
image={emojis[(5 + i) % 5]}
/>
),
)
}
</MapView>
<Fab
position={'bottomRight'}
active={this.state.active}
style={{ backgroundColor: '#DD5144' }}
direction={'left'}
onPress={() => { this.setState({ active: !this.state.active }); }}
>
<Icon name={'add'} />
<Button
style={{ backgroundColor: '#0066cc' }}
onPress={this.goToSearch}
>
<Icon name={'search'} />
</Button>
<Button
style={{ backgroundColor: '#ff9900' }}
onPress={this.chirp}
>
<Icon name={'ios-megaphone'} />
</Button>
</Fab>
</View>
);
}
}
MapDisplay.propTypes = {
groupName: React.PropTypes.string.isRequired,
navigator: React.PropTypes.object.isRequired,
};
<file_sep>/components/GroupView/GroupList.js
import React from 'react';
import { TouchableOpacity, View, Dimensions } from 'react-native';
import { Text, Icon } from 'native-base';
import stringToColor from './colorGenerator';
const GroupList = ({ _handleChangePage, userGroups, deleteGroup, uid }) => {
return (
<View
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
flexWrap: 'wrap',
}}
>
{userGroups.map((group, i) => {
return (
<View
key={i}
style={{
shadowColor: 'black',
shadowOpacity: 0.7,
shadowRadius: 3,
shadowOffset: {
height: 0,
width: 0,
},
backgroundColor: stringToColor(group),
marginTop: 20,
justifyContent: 'space-between',
width: Dimensions.get('window').width*.48,
height: Dimensions.get('window').height*.20,
padding: 13,
}}
>
<TouchableOpacity
onPress={() => _handleChangePage(group || '')}
>
<Text
style={{
fontSize: 25,
fontWeight: '600',
}}
>{group}</Text>
</TouchableOpacity>
<View
style={{
position: 'absolute',
bottom: 13,
right: 13,
width: 50,
height: 50,
borderRadius: 50,
backgroundColor: 'white',
}}
>
<Icon
name={'trash'}
style={{
color: 'red',
position: 'absolute',
bottom: 7,
right: 16,
}}
onPress={() => deleteGroup(uid, group)}
/>
</View>
</View>
);
},
)
}
</View>
);
};
GroupList.propTypes = {
_handleChangePage: React.PropTypes.func.isRequired,
userGroups: React.PropTypes.array.isRequired,
deleteGroup: React.PropTypes.func.isRequired,
uid: React.PropTypes.string.isRequired,
};
export default GroupList;
<file_sep>/README.md
# Gaggle
Have you ever gone on a group trip, whether with friends or family, and wanted to keep everyone on the same page? With Gaggle, you can easily interact with members of your group either by chatting directly, or viewing their locations. You can even set up a poll for suggestions on what to do and see around your area, using the powerful map view.
Gaggle, the best way to keep track of *your* flock!
### Installing
Start off by installing the dependencies with npm.
```
npm install
```
Next, you'll need to make a Firebase project and get your project details for the app. Reference config.example.js and make your own config.js in the same folder, replacing the empty strings with the values from Firebase.
```
export default {
apiKey: '',
authDomain: '',
databaseURL: '',
storageBucket: '',
messagingSenderId: '',
};
```
Similar to setting up the Firebase config file, you will need to do the same for the google and uber config files. Navigate to the google and uber directories, and make your own config.js in their respective directories, replacing the empty strings with the appropriate keys.
Google:
```
export default 'GOOGLE_API_KEY';
```
Uber:
```
export const clientID = 'UBER_CLIENT_ID';
```
Then, start up the application with the simulator.
```
react-native run-ios
```
And there you have it! You should see your simulator up with the application running.
## Running the tests
To run the tests, call the test script from the package.json.
```
npm test
```
## Details of the Application
Starting out, you will be prompted to sign in using your email and password. You will notice that both your email and password need to match specific criteria for the sign-in/sign-up button to fill in. Specifically, your password must be 6 characters, or more.
<img src=screenshots/signin-example.png height=700 />
Once you successfully log in, you are brought to your list of groups. You are able to create or join any group, and later remove yourself from them, by clicking the trash can.
Please note, ANYONE can join your group, as long as they have the exact same spelling as your group. For example, if I create a group named 'Disney Group', and someone learns that I've named my group that, they can also join my group by joining 'Disney Group'. We leave this as an open issue for anyone who would like to take it on.
<img src=screenshots/group-view.png height=700 />
Clicking the name of your group will take you first to the map view. Here, you'll see all your group members' locations. Click on an icon to see the person's name.
The yellow Chirp button sends an alert to everyone in your group letting them click straight to your location. This is a great tool to show small children or others who may get lost!
<img src=screenshots/map-view.png height=700 />
The Search button in the lower right lets you search for attractions and amenities, while the Chat and Polls tabs will let you discuss options with your group.
## Built With
* [React Native](https://facebook.github.io/react-native/) - iOS native framework, using React.
* [Firebase](https://firebase.google.com/) - Authentication, Realtime Database, and overall backend.
* [Native Base](http://nativebase.io/) - For consistent styling and interactions.
## Authors
* **<NAME>**
* **<NAME>**
* **<NAME>**
* **<NAME>**
<file_sep>/components/Search/Search.js
import React, { Component } from 'react';
import { View } from 'react-native';
import { Container, Header, Content, Text, Icon, Item, Input, Button, Spinner, Thumbnail, Card, CardItem, Body } from 'native-base';
import { getGroupMemberLocations, logSearch, firebaseDB } from '../../firebase/firebaseHelpers';
import { getUserLocation, findCentroidFromArray } from '../../location/locationHelpers';
import { getResultsFromKeyword, categories, getPlacePhoto } from '../../google/googlePlaces';
import Results from '../Search/Results';
import CategoryButton from '../Search/CategoryButton';
import userLocationImage from '../../images/user-location.png';
import groupLocationImage from '../../images/group-location.png';
const styles = {
searchBar: {
position: 'relative',
top: -15,
},
searchTypeButton: {
padding: 0,
marginRight: 5,
},
};
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchInput: '',
searchForMeOrGroup: true,
showInstructions: true,
myLocation: [],
groupLocation: [],
results: [],
topSearches: [],
category: null,
loading: false,
};
this.handleSearchType = this.handleSearchType.bind(this);
this.handleSearch = this.handleSearch.bind(this);
this.getRandomCategory = this.getRandomCategory.bind(this);
this.getPhotoProps = this.getPhotoProps.bind(this);
this.groupsSearches = firebaseDB.ref(`groups/${this.props.groupName}/searches`);
this.groupsSearches.orderByValue().limitToLast(3).on('value', (snapshot) => {
const searchesSnapshot = snapshot.val();
const topThreeSearches = [];
for (let key in searchesSnapshot) {
topThreeSearches.push(key);
}
this.setState({
topSearches: topThreeSearches,
});
});
}
componentWillMount() {
this._getUserLocation();
this._getGroupCentroid();
}
componentWillUnmount() {
this.groupsSearches.off();
// If a timeout is set but the callback hasn't been invoked yet:
if (this.sortResults) {
clearTimeout(this.sortResults);
}
}
getRandomCategory() {
let randomCategory = categories[Math.floor(Math.random() * categories.length)];
while (this.state.category === randomCategory) {
randomCategory = categories[Math.floor(Math.random() * categories.length)];
}
this.setState({ category: randomCategory });
return randomCategory;
}
getPhotoProps() {
const newResults = [];
this.state.results.forEach((result, index) => {
const photoref = result.photos ? result.photos[0].photo_reference : 'no_photo';
const newResult = result;
newResult.order = index;
// photoURL for results with no photoreference set to "photo not found" image
if (photoref === 'no_photo') {
newResult.photoURL = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQuDbG_i4uiHR5rOBuCttQTZ7TU-QBVcsHRu5PtqWeVvLDwRkkQlA';
newResults.push(newResult);
} else {
getPlacePhoto(photoref)
.then((response) => {
newResult.photoURL = response;
newResults.push(newResult);
});
}
});
this.sortResults = setTimeout(() => {
newResults.sort((a, b) => a.order - b.order);
this.setState({ results: newResults });
}, 3000);
}
handleSearchType(type) {
if (type === 'me') {
this.setState({ searchForMeOrGroup: true });
} else if (type === 'group') {
this.setState({ searchForMeOrGroup: false });
}
}
handlePopularSearch(searchTerm) {
const searchLocation = this.state.searchForMeOrGroup ?
this.state.myLocation : this.state.groupLocation;
const radius = this.state.searchForMeOrGroup ? 7500 : 30000;
logSearch(this.props.groupName, searchTerm);
this.setState({ loading: true });
getResultsFromKeyword(searchLocation, searchTerm, radius)
.then((data) => {
this.setState({ results: data.results, showInstructions: false, loading: false });
this.getPhotoProps();
});
}
handleSearch(feelingLucky) {
const searchLocation = this.state.searchForMeOrGroup ?
this.state.myLocation : this.state.groupLocation;
const searchTerm = feelingLucky ? this.getRandomCategory() : this.state.searchInput;
const radius = this.state.searchForMeOrGroup ? 7500 : 30000;
logSearch(this.props.groupName, searchTerm);
this.setState({ loading: true });
getResultsFromKeyword(searchLocation, searchTerm, radius)
.then((data) => {
this.setState({ results: data.results, showInstructions: false, loading: false });
this.getPhotoProps();
});
}
_getUserLocation() {
getUserLocation()
.then((position) => {
this.setState({ myLocation: [position[0], position[1]] });
});
}
_getGroupCentroid() {
getGroupMemberLocations(this.props.groupName)
.then(locations => this.setState({ groupLocation: findCentroidFromArray(locations) }));
}
render() {
return (
<Container>
<Header />
<Content>
<Header style={styles.searchBar} searchBar rounded>
<Item>
<Icon name="search" />
<Input
placeholder="Search"
value={this.state.searchInput}
onChangeText={t => this.setState({ searchInput: t })}
onFocus={() => this.setState({ searchInput: '' })}
onSubmitEditing={() => this.handleSearch(false)}
/>
<Button
onPress={() => this.handleSearchType('me')}
style={styles.searchTypeButton}
small
icon
transparent
>
<Icon active={this.state.searchForMeOrGroup} name="person" />
</Button>
<Button
onPress={() => this.handleSearchType('group')}
style={styles.searchTypeButton}
small
icon
transparent
>
<Icon active={!this.state.searchForMeOrGroup} name="people" />
</Button>
</Item>
<Button onPress={() => this.handleSearch(false)} transparent>
<Text>Search</Text>
</Button>
</Header>
<View style={{ position: 'relative', top: -15 }}>
<CategoryButton
category={'I\'m Feeling Lucky' + (this.state.category ? `: ${this.state.category}` : '')}
getSuggestions={() => this.handleSearch(true)}
/>
<View
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
margin: 5,
}}
>
{this.state.topSearches.map(searchValue => (
<Button
key={searchValue}
rounded
info
small
onPress={() => {
this.handlePopularSearch(searchValue);
}}
>
<Text>{searchValue}</Text>
</Button>
))}
</View>
{this.state.showInstructions &&
<Card>
<CardItem>
<Body>
<Text>{'Search for places around your location or your group\'s!'}</Text>
</Body>
</CardItem>
<CardItem>
<Body>
<Thumbnail square style={{ height: 25, width: 25 }} source={userLocationImage} />
<Text>Press the USER location icon to search around your own location</Text>
</Body>
</CardItem>
<CardItem>
<Body>
<Thumbnail square style={{ height: 25, width: 25 }} source={groupLocationImage} />
<Text>{'Press the GROUP location icon to search the midpoint of your GROUP\'s locations'}</Text>
</Body>
</CardItem>
<CardItem>
<Body>
<Text>{'Type in a keyword and press Search!'}</Text>
</Body>
</CardItem>
</Card>}
{this.state.loading && <Spinner />}
<Results navigator={this.props.navigator} results={this.state.results} />
</View>
</Content>
</Container>
);
}
}
Search.propTypes = {
groupName: React.PropTypes.string.isRequired,
navigator: React.PropTypes.object.isRequired,
};
<file_sep>/components/GroupView/GroupView.js
import React, { Component } from 'react';
import { Alert, Text } from 'react-native';
import { Container, Header, Content } from 'native-base';
import { firebaseDB, updateUserLocation, removeUserFromGroup } from '../../firebase/firebaseHelpers';
import GroupMapChat from '../GroupMapChat/GroupMapChat';
import CreateJoinGroup from './CreateJoinGroup';
import GroupList from './GroupList';
import Quiz from '../Quiz/Quiz';
export default class GroupView extends Component {
constructor(props, context) {
super(props, context);
this.state = {
user: this.props.user,
users: [],
groups: [],
activeGroup: 'Default',
};
// set up listener to groups path for syncing state with db
this.firebaseGroupsRef = firebaseDB.ref(`users/${this.props.user.uid}/groups`);
this.firebaseGroupsRef.on('value', (snapshot) => {
const groupsObj = snapshot.val();
const arrayOfGroups = [];
for (let key in groupsObj) {
arrayOfGroups.push(groupsObj[key]);
}
this.setState({ groups: arrayOfGroups });
},
(error) => { console.log(`Error getting groups ${error}`); }
);
this.usersRef = firebaseDB.ref('/users');
this._handleChangePage = this._handleChangePage.bind(this);
this.deleteGroup = this.deleteGroup.bind(this);
}
componentWillMount() {
this._usersListener();
}
componentWillUnmount() {
this.usersRef.off('value');
this.firebaseGroupsRef.off();
}
_handleChangePage(name) {
this.setState({
activeGroup: name,
}, () => {
updateUserLocation(this.state.activeGroup);
});
this.props.navigator.push({
component: GroupMapChat,
title: `${name} Group`,
passProps: {
user: this.props.user,
groupName: name,
},
rightButtonTitle: 'Quiz',
onRightButtonPress: () => this.props.navigator.push({
component: Quiz,
title: 'While You Wait...',
}),
});
}
deleteGroup(uid, groupName) {
Alert.alert(
'Delete Group',
`Are you sure you want to remove yourself from ${groupName}?`,
[
{ text: 'Cancel', onPress: () => console.log('Cancel pressed') },
{ text: 'Yes', onPress: () => removeUserFromGroup(uid, groupName), style: 'destructive' },
],
);
}
_usersListener() {
this.usersRef.on('value', (snapshot) => {
const usersArray = [];
snapshot.forEach((childSnapshot) => {
usersArray.push(childSnapshot.val());
});
this.setState({ users: usersArray });
}).bind(this);
}
render() {
return (
<Container>
<Header />
<Content>
{this.state.groups.length === 0 &&
<Text
style={{
color: 'grey',
textAlign: 'center',
marginVertical: 10,
}}
>To join a group, just type in the name, and click Join!</Text>}
<CreateJoinGroup user={this.state.user} />
<GroupList
_handleChangePage={this._handleChangePage}
userGroups={this.state.groups}
deleteGroup={this.deleteGroup}
uid={this.state.user.uid}
/>
</Content>
</Container>
);
}
}
GroupView.propTypes = {
navigator: React.PropTypes.object.isRequired,
user: React.PropTypes.object.isRequired,
};
<file_sep>/components/Polls/Option.js
import React, { Component } from 'react';
import { View, Animated } from 'react-native';
import { ListItem, Body, Text, CheckBox, Icon } from 'native-base';
import { getCurrentUserId } from '../../firebase/firebaseHelpers';
export default class Option extends Component {
constructor(props) {
super(props);
this.state = {
text: this.props.text,
votes: this.props.votes,
totalVotes: this.props.totalVotes || 1,
id: this.props.id,
responses: this.props.responses,
checked: this.props.responses[getCurrentUserId()] || false,
};
this._width = new Animated.Value(0);
}
toggleChecked() {
this.setState({
checked: !this.state.checked,
}, () => {
if (this.state.checked) {
this.setState({
votes: this.state.votes + 1,
}, () => {
this.props.updateOption({
text: this.state.text,
votes: this.state.votes,
id: this.state.id,
});
});
} else {
this.setState({
votes: this.state.votes - 1,
}, () => {
this.props.updateOption({
text: this.state.text,
votes: this.state.votes,
id: this.state.id,
});
});
}
});
}
componentDidMount() {
Animated.timing(this._width, {
toValue: this.state.votes,
}).start();
}
// Set so you can click the ListItem OR the CheckBox
render() {
//console.log('WIDTH', this.state.votes, this.state.totalVotes, Math.floor((this.state.votes / this.state.totalVotes) * 100));
return (
<View
style={{
flexGrow: 1,
}}
>
<Animated.View
onPress={() => this.toggleChecked()}
style={{
backgroundColor: 'orange',
height: 20,
width: Math.floor((this.state.votes / this.state.totalVotes) * 100)* 3,
borderTopRightRadius: 4,
borderBottomRightRadius: 4,
padding: 5,
margin: 1,
}}
/>
<ListItem value={this.state.votes} onPress={() => this.toggleChecked()}>
<Body
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
}}
>
<CheckBox checked={this.state.checked} onPress={() => this.toggleChecked()} />
<Text
style={{
flex: 4,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
fontSize: 16,
}}
>
{this.state.text}
</Text>
<Text
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
fontSize: 20,
fontWeight: '600',
}}
>
{this.state.votes}
</Text>
<Icon
name={'trash'}
style={{ color: 'red' }}
onPress={() => this.props.removeOption({
text: this.state.text,
id: this.state.id,
})}
/>
</Body>
</ListItem>
</View>
);
}
}
Option.propTypes = {
text: React.PropTypes.string.isRequired,
votes: React.PropTypes.number.isRequired,
id: React.PropTypes.string.isRequired,
responses: React.PropTypes.object.isRequired,
};
<file_sep>/components/UberButton/uberLinks.js
import { clientID } from '../../uber/config';
export const getUberDeepLink = (pickupLatitude, pickupLongitude, dropoffLatitude, dropoffLongitude) => (
`uber://?client_id=${clientID}
&action=setPickup
&pickup[latitude]=${pickupLatitude}
&pickup[longitude]=${pickupLongitude}
&dropoff[latitude]=${dropoffLatitude}
&dropoff[longitude]=${dropoffLongitude}
&link_text=Gaggle%20App%20`
);
export const getUberUniversalLink = (pickupLatitude, pickupLongitude, dropoffLatitude, dropoffLongitude) =>
(
`https://m.uber.com/ul/?client_id=${clientID}
&action=setPickup
&pickup[latitude]=${pickupLatitude}
&pickup[longitude]=${pickupLongitude}
&dropoff[latitude]=${dropoffLatitude}
&dropoff[longitude]=${dropoffLongitude}
&link_text=Gaggle%20App`
);
<file_sep>/components/UberButton/UberButton.js
import React, { Component } from 'react';
import { Linking, Image } from 'react-native';
import { Button, Text } from 'native-base';
import { getUberDeepLink, getUberUniversalLink } from './uberLinks';
import uberLogo from './uberLogo.png';
import { getUserLocation } from '../../location/locationHelpers';
const styles = {
uberButton: {
width: 215,
height: 40,
backgroundColor: 'black',
position: 'relative',
top: 5,
marginBottom: 10,
justifyContent: 'flex-end',
},
};
export default class UberButton extends Component {
constructor(props) {
super(props);
this.state = {
currentLatitude: 0,
currentLongitude: 0,
};
this._getUserLocation();
this.handleClick = this.handleClick.bind(this);
}
_getUserLocation() {
getUserLocation().then((position) => {
this.setState({
currentLatitude: position[0],
currentLongitude: position[1],
});
});
}
handleClick() {
console.log(this.props);
const deepLink = getUberDeepLink(
this.currentLatitude,
this.currentLongitude,
this.props.destination[0],
this.props.destination[1],
);
const universalLink = getUberUniversalLink(
this.currentLatitude,
this.currentLongitude,
this.props.destination[0],
this.props.destination[1],
);
Linking.canOpenURL(deepLink).then((supported) => {
if (supported) {
Linking.openURL(deepLink);
} else {
Linking.openURL(universalLink);
}
});
}
render() {
return (
<Button
style={styles.uberButton}
onPress={this.handleClick}
>
<Image
source={uberLogo}
/>
<Text style={{ color: 'white' }}>Ride There With Uber</Text>
</Button>
);
}
}
UberButton.propTypes = {
destination: React.PropTypes.array.isRequired,
};
<file_sep>/__tests__/opentdbHelpers.js
import getTriviaQuestions from '../opentdb/opentdbHelpers';
global.fetch = require('node-fetch');
describe('getTriviaQuestions', () => {
it('is a function', () => {
expect(typeof getTriviaQuestions).toBe('function');
});
it('accepts number of questions and difficulty arguments', () => {
// ES6 Default Params don't add length apparently
expect(getTriviaQuestions.length).toEqual(1);
});
it('returns an object with a category, question, and answers', () => {
return getTriviaQuestions(1, 'easy')
.then((results) => {
expect(results[0].category).toBeDefined();
expect(results[0].question).toBeDefined();
expect(results[0].correct_answer).toBeDefined();
expect(results[0].incorrect_answers).toBeDefined();
});
});
it('returns an easy question when no difficulty is provided', () => {
return getTriviaQuestions(1)
.then((results) => {
expect(results[0].difficulty).toBe('easy');
});
});
it('returns a medium difficulty question with a medium difficulty argument', () => {
return getTriviaQuestions(1, 'medium')
.then((results) => {
expect(results[0].difficulty).toBe('medium');
});
});
it('returns a hard difficulty question with a hard difficulty argument', () => {
return getTriviaQuestions(1, 'hard')
.then((results) => {
expect(results[0].difficulty).toBe('hard');
});
});
it('returns multiple questions depending on the first argument', () => {
return getTriviaQuestions(4)
.then((results) => {
expect(results.length).toBe(4);
});
});
});
<file_sep>/__tests__/firebaseHelpers.js
import { addUserToGroup, getAllUsersInGroup, getCurrentUser, getCurrentUserId, updateUserLocation, getGroupMemberLocations } from '../firebase/firebaseHelpers';
describe('addUserToGroup', () => {
it('should be a function', () => {
expect(typeof addUserToGroup).toBe('function');
});
});
describe('getAllUsersInGroup', () => {
it('should be a function', () => {
expect(typeof getAllUsersInGroup).toBe('function');
});
});
describe('getCurrentUser', () => {
it('should be a function', () => {
expect(typeof getCurrentUser).toBe('function');
});
});
describe('getCurrentUserId', () => {
it('should be a function', () => {
expect(typeof getCurrentUserId).toBe('function');
});
});
describe('updateUserLocation', () => {
it('should be a function', () => {
expect(typeof updateUserLocation).toBe('function');
});
});
describe('getGroupMemberLocations', () => {
it('should be a function', () => {
expect(typeof getGroupMemberLocations).toBe('function');
});
it('should accept a group name', () => {
expect(getGroupMemberLocations.length).toEqual(1);
});
it('should return a promise', () => {
expect(typeof getGroupMemberLocations('Default')).toBe('object');
});
});
<file_sep>/components/Search/Results.js
import React, { Component } from 'react';
import { Image } from 'react-native';
import { List, ListItem, Text } from 'native-base';
import { Col, Grid } from 'react-native-easy-grid';
import ResultDetails from './ResultDetails';
import { getUserLocation, findDistanceBetweenCoords } from '../../location/locationHelpers';
export default class Results extends Component {
constructor(props) {
super(props);
this.state = {
myLocation: [],
};
this._getUserLocation();
this.goToResultDetails = this.goToResultDetails.bind(this);
}
goToResultDetails(details) {
this.props.navigator.push({
component: ResultDetails,
title: details.name,
passProps: { placeId: details.place_id },
});
}
_getUserLocation() {
getUserLocation().then((position) => {
this.setState({ myLocation: [position[0], position[1]] });
});
}
render() {
return (
<List>
{this.props.results.map(result => (
<ListItem
key={result.id}
onPress={() => this.goToResultDetails(result)}
>
<Grid>
<Col size={1.5}>
<Image
source={{ uri: result.photoURL }}
style={{ width: 50, height: 50, resizeMode: 'contain' }}
/>
</Col>
<Col size={4}>
<Text>{result.name}</Text>
</Col>
<Col size={1}>
<Text>
{findDistanceBetweenCoords(
this.state.myLocation,
[result.geometry.location.lat, result.geometry.location.lng],
).toFixed(2)} mi
</Text>
</Col>
</Grid>
</ListItem>
))}
</List>
);
}
}
Results.propTypes = {
results: React.PropTypes.array.isRequired,
navigator: React.PropTypes.object.isRequired,
};
<file_sep>/__tests__/googlePlaces.js
import { getResultsFromKeyword, categories, getPlaceDetails } from '../google/googlePlaces';
describe('getResultsFromKeyword', () => {
it('is a function', () => {
expect(typeof getResultsFromKeyword).toBe('function');
});
it('accepts a location, keyword, and radius', () => {
expect(getResultsFromKeyword.length).toBe(3);
});
it('returns a promise', () => {
expect(typeof getResultsFromKeyword([0, 0], 'Fun')).toBe('object');
});
});
describe('categories', () => {
it('is an array', () => {
expect(Array.isArray(categories)).toBe(true);
});
it('contains more than one element', () => {
expect(categories.length).not.toBeLessThan(1);
});
it('contains relevant categories for search', () => {
expect(categories).toContain('Restaurants');
});
});
describe('getPlaceDetails', () => {
it('is a function', () => {
expect(typeof getPlaceDetails).toBe('function');
});
it('accepts a placeId as an argument', () => {
expect(getPlaceDetails.length).toBe(1);
});
it('returns a promise', () => {
expect(typeof getPlaceDetails()).toBe('object');
});
});
<file_sep>/components/Chat/Chat.js
import React, { Component } from 'react';
import { StyleSheet, View, TextInput, ListView, Image, Dimensions } from 'react-native';
import { Button, ListItem, Text, Icon } from 'native-base';
import InvertibleScrollView from 'react-native-invertible-scroll-view';
import moment from 'moment';
import Autolink from 'react-native-autolink';
import { firebaseDB } from '../../firebase/firebaseHelpers';
import { isValidGiphyCommand, parseGiphyCommand, getGiphyResultFromKeyword, replaceHTTPwithHTTPS } from '../../giphy/giphyHelpers';
const styles = StyleSheet.create({
textInput: {
flex: 1,
borderColor: 'grey',
borderWidth: 1,
paddingTop: 2,
paddingLeft: 5,
margin: 10,
},
chatInput: {
flex: 1,
flexDirection: 'row',
borderTopWidth: 1,
borderTopColor: 'lightgrey',
},
sendMessage: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
marginTop: 10,
},
giphy: {
width: 150,
height: 80,
resizeMode: 'contain',
marginTop: 5,
},
});
const nativeBaseStyles = {
messageAuthor: {
fontWeight: '600',
fontSize: 13,
},
};
export default class Chat extends Component {
constructor(props, context) {
super(props, context);
this.database = firebaseDB;
this.state = {
username: this.props.user ? this.props.user.displayName : 'Anonymous',
input: '',
group: this.props.groupName ? this.props.groupName : 'Default',
messages: [],
image: '',
};
this.height = Dimensions.get('window').height;
this.width = Dimensions.get('window').width;
this._ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this._chatList = {};
this.messagesRef = this.database.ref(`messages/${this.state.group}`);
this.sendMessage = this.sendMessage.bind(this);
}
componentDidMount() {
this.messagesListener();
}
componentDidUpdate() {
this._chatList.scrollTo({ y: 0 });
}
componentWillUnmount() {
this.messagesRef.off('value');
}
messagesListener() {
this.messagesRef.on('value', (snapshot) => {
// Handle no messages created yet...
if (snapshot.val() === null) {
this.setState({ messages: [] });
} else {
this.setState({ messages: snapshot.val().reverse() });
}
});
}
sendMessage() {
let message = this.state.input;
const _sendMessage = () => {
// Write a message into database
// Transaction will allow firebase to queue the requests
// so messages aren't written at the same time
this.messagesRef.transaction((messages) => {
const groupMessages = messages || [];
groupMessages.push({
name: this.state.username,
message,
timestamp: new Date().getTime(),
});
// Clear TextInput
this.setState({ input: '' });
return groupMessages;
});
};
if (isValidGiphyCommand(message)) {
const parsedKeyword = parseGiphyCommand(message);
getGiphyResultFromKeyword(parsedKeyword)
.then((result) => {
console.log('result: ', result);
const imageUrl = replaceHTTPwithHTTPS(result.image_url);
message = imageUrl;
_sendMessage();
});
} else {
_sendMessage();
}
}
render() {
return (
<View>
<View style={{ height: this.height - 166, marginLeft: -15 }}>
<ListView
enableEmptySections
renderScrollComponent={props => <InvertibleScrollView {...props} inverted />}
ref={(chatList) => { this._chatList = chatList; }}
dataSource={this._ds.cloneWithRows(this.state.messages)}
renderRow={obj =>
<ListItem>
<View style={{ flex: 1, flexDirection: 'column', alignItems: 'flex-start', marginLeft: 10 }}>
<View style={{ flex: 1 }}>
<Text style={nativeBaseStyles.messageAuthor}>
{obj.name} ({moment(obj.timestamp).fromNow()}):
</Text>
</View>
<View style={{ flex: 1 }}>
<Autolink text={obj.message} />
</View>
{obj.message.toLowerCase().indexOf('.giphy.com/') > -1 &&
<Image
style={styles.giphy}
source={{ uri: obj.message }}
/>}
</View>
</ListItem>
}
/>
</View>
<View style={styles.chatInput}>
<View style={{ flex: 3, height: 50 }}>
<TextInput
style={styles.textInput}
value={this.state.input}
onChangeText={t => this.setState({ input: t })}
onSubmitEditing={() => {
if (this.state.input.length) {
this.sendMessage();
}
}}
/>
</View>
<View style={styles.sendMessage}>
<Button small onPress={this.sendMessage} disabled={this.state.input.length < 1}>
<Text style={{ color: 'white' }}>Send</Text>
</Button>
</View>
</View>
</View>
);
}
}
Chat.propTypes = {
user: React.PropTypes.object.isRequired,
groupName: React.PropTypes.string.isRequired,
};
<file_sep>/components/Polls/Poll.js
import React, { Component } from 'react';
import { ListView, View, TextInput, Alert, Dimensions } from 'react-native';
import { Container, Content, Text, Button, Icon } from 'native-base';
import { firebaseDB, getCurrentUserId } from '../../firebase/firebaseHelpers';
import Option from './Option';
export default class Poll extends Component {
constructor(props) {
super(props);
this.state = {
group: this.props.groupName ? this.props.groupName : 'Default',
pollID: this.props.pollID,
pollTxt: this.props.pollTxt,
input: '',
options: [],
totalVotes: 0,
};
this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.addOption = this.addOption.bind(this);
this.updateOption = this.updateOption.bind(this);
this.removeOption = this.removeOption.bind(this);
this.optionRef = firebaseDB.ref(`/groups/${this.state.group}/polls/${this.state.pollID}/options/`);
}
componentDidMount() {
this.getOptions();
}
componentWillUnmount() {
this.optionRef.off();
}
getOptions() {
this.optionRef.on('value', (snapshot) => {
if (snapshot.exists()) {
let total = 0;
snapshot.forEach((opt) => {
total += opt.child('votes').val();
});
this.setState({
options: snapshot.val(),
totalVotes: total,
}, () => {
console.log('STATE votes', this.state.totalVotes);
});
} else {
this.setState({
options: [],
});
}
});
}
addOption() {
const optRef = this.optionRef.push();
let options = this.state.options;
let unique = true;
for (var opt in options) {
if(options[opt]['text'].toLowerCase() === this.state.input.toLowerCase()) {
unique = false;
}
}
if (unique) {
optRef.set({
text: this.state.input,
votes: 0,
id: optRef.key,
responses: { 'dummy': 'data' },
}, (error) => {
if (error) {
console.log('Transaction failed abnormally!', error);
}
}).then(() => {
this.setState({
input: '',
});
});
} else {
console.log('Sorry, no duplicate entries!');
Alert.alert(
'Oops!',
`Sorry, no duplicate entries!`,
[
{ text: 'Dismiss' },
],
);
}
}
updateOption(optionObj) {
const userID = getCurrentUserId();
this.optionRef.child(optionObj.id).transaction((opt) => {
// if(!opt.responses.exists()) {
// opt.responses[userID] = false; //make sure it exists before changing
// }
if (opt) {
if (opt.text.toLowerCase() === optionObj.text.toLowerCase()) {
if (opt.responses[userID]) {
opt.responses[userID] = null;
} else {
opt.responses[userID] = true;
}
opt.votes = optionObj.votes;
//update totalVotes count
if (opt.votes < optionObj.votes) {
this.setState({
totalVotes: this.state.totalVotes + 1,
});
} else {
this.setState({
totalVotes: this.state.totalVotes - 1,
});
}
}
} else {
console.log('option is null');
}
return opt;
}, (error, committed, snapshot) => {
if (error) {
console.log('Transaction failed abnormally!', error);
}
console.log('UpdateOption Committed: ', committed, 'Option data: ', snapshot.val());
});
}
removeOption(optionObj) {
this.optionRef.child(optionObj.id).remove()
.then(() => {
console.log('Remove succeeded.');
})
.catch((error) => {
console.log('Remove failed: ' + error.message);
});
}
render() {
return (
<Container>
<Content>
<View style={{ flex: 1, paddingTop: 80, height: Dimensions.get('window').height - 50, marginLeft: -10 }}>
{ this.state.options.length === 0 &&
<View>
<Text
style={{
color: 'grey',
textAlign: 'center',
marginVertical: 10,
}}
>
{'Enter options to choose from!'}
</Text>
<Icon
name={'ios-arrow-down'}
style={{
color: 'orange',
flexDirection: 'row',
textAlign: 'center',
}}
/>
<Icon
name={'ios-arrow-down'}
style={{
color: 'orange',
flexDirection: 'row',
textAlign: 'center',
}}
/>
<Icon
name={'ios-arrow-down'}
style={{
color: 'orange',
flexDirection: 'row',
textAlign: 'center',
}}
/>
<Icon
name={'ios-arrow-down'}
style={{
color: 'orange',
flexDirection: 'row',
textAlign: 'center',
}}
/>
<Icon
name={'ios-arrow-down'}
style={{
color: 'orange',
flexDirection: 'row',
textAlign: 'center',
}}
/>
<Icon
name={'ios-arrow-down'}
style={{
color: 'orange',
flexDirection: 'row',
textAlign: 'center',
}}
/>
</View>
}
<ListView
enableEmptySections
dataSource={this.ds.cloneWithRows(this.state.options)}
renderRow={(rowData) =>
<Option
id={rowData.id}
text={rowData.text}
votes={rowData.votes}
totalVotes={this.state.totalVotes}
responses={rowData.responses}
updateOption={this.updateOption}
removeOption={this.removeOption}
/>
}
/>
</View>
<View
style={{
flex: 1,
flexDirection: 'row',
borderTopWidth: 1,
borderTopColor: 'lightgrey',
}}
>
<View style={{ flex: 3, height: 50 }}>
<TextInput
style={{
flex: 1,
borderColor: 'grey',
borderWidth: 1,
paddingLeft: 10,
margin: 10,
}}
placeholder="Enter a new option"
value={this.state.input}
onChangeText={(t) => this.setState({ input: t })}
/>
</View>
<View
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
marginTop: 10,
}}
>
<Button small onPress={this.addOption} disabled={this.state.input.length < 1}>
<Text style={{ color: 'white' }}>Add</Text>
</Button>
</View>
</View>
</Content>
</Container>
);
}
}
Poll.propTypes = {
groupName: React.PropTypes.string.isRequired,
pollID: React.PropTypes.string.isRequired,
pollTxt: React.PropTypes.string.isRequired,
};
<file_sep>/components/GroupView/CreateJoinGroup.js
import React, { Component } from 'react';
import { Input, Button, Text, Item } from 'native-base';
import { addUserToGroup } from '../../firebase/firebaseHelpers';
export default class CreateJoinGroup extends Component {
constructor(props) {
super(props);
this.state = {
user: this.props.user,
};
}
render() {
return (
<Item>
<Input
ref={(component) => { this._groupInput = component; }}
style={{ marginLeft: 10, height: 40 }}
placeholder="Group Name"
autoCapitalize={'none'}
onSubmitEditing={() => {
addUserToGroup(this.state.user, this._groupInput._root._lastNativeText);
this._groupInput._root.setNativeProps({ text: '' });
}}
/>
<Button
full
style={{ justifyContent: 'center', paddingRight: 15, height: 40, position: 'relative', top: 1 }}
onPress={
() => {
addUserToGroup(this.state.user, this._groupInput._root._lastNativeText);
this._groupInput._root.setNativeProps({ text: '' });
}
}
>
<Text>Join</Text>
</Button>
</Item>
);
}
}
CreateJoinGroup.propTypes = {
user: React.PropTypes.object.isRequired,
};
|
f801422e59817775dc3792627db7cb59e1c37e3c
|
[
"JavaScript",
"Markdown"
] | 25 |
JavaScript
|
styras/Gaggle
|
fc55bf6260107f578fd5e5c830ce808fe0f9038f
|
f5291e0b53f95104c29aa8b3944a211ee07087a8
|
refs/heads/master
|
<file_sep>package com.liuan.robot.base.exception;
import java.io.IOException;
@SuppressWarnings("serial")
public class NestedIOException extends IOException {
/**
* Construct a {@code NestedIOException} with the specified detail message.
* @param msg the detail message
*/
public NestedIOException(String msg) {
super(msg);
}
/**
* Construct a {@code NestedIOException} with the specified detail message
* and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
public NestedIOException(String msg, Throwable cause) {
super(msg, cause);
}
}
<file_sep>package com.liu.robot.bean;
/**
* @author 作者 :ANLIU
* @version 创建时间:2016年7月2日
* 类说明
*/
public class ResultMessage <T>
{
private int retCode;
private String retErrorMsg;
private T data;
public int getRetCode()
{
return retCode;
}
public void setRetCode(int retCode)
{
this.retCode = retCode;
}
public String getRetErrorMsg()
{
return retErrorMsg;
}
public void setRetErrorMsg(String retErrorMsg)
{
this.retErrorMsg = retErrorMsg;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
}
<file_sep>package com.liuan.robot.weixin.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.liuan.robot.weixin.bean.Message;
/**
* 和message表相关的数据库操作
*
* @author LIUAN
*
*/
public interface MessageDao
{
/**
* 根据条件查询消息列表
* @return
*/
public List<Message> queryMessageList(@Param("command")String command, @Param("description")String description);
}
<file_sep>package com.liu.robot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.liu.robot.bean.Message;
import com.liu.robot.bean.ResultMessage;
import com.liu.robot.service.MessageService;
/**
* @author 作者 :ANLIU
* @version 创建时间:2016年4月17日
* spring mvc 基本测试类
*/
@Controller
@ImportResource({ "classpath:spring-context.xml"})
@RequestMapping(value="basetest")
public class BaseTestController
{
@Autowired
private MessageService messageService ;
@RequestMapping(value = "/test1")
@ResponseBody
public String Test1()
{
System.out.println("ok");
return "hello";
}
@RequestMapping(value = "/test2")
@ResponseBody
public ResultMessage<?> Test2()
{
ResultMessage<List<Message>> msg = new ResultMessage<List<Message>>();
System.out.println("ok");
List<Message> list = messageService.queryMessageList(null, null);
msg.setRetCode(0);
msg.setRetErrorMsg("query messages success");
msg.setData(list);
return msg;
}
}
<file_sep><?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.liu</groupId>
<artifactId>robot-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.liu</groupId>
<artifactId>robot-controller</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>robot-controller</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.3.RELEASE</spring.version>
<log4j2.version>2.3</log4j2.version>
<slf4j.version>1.7.7</slf4j.version>
<commons-logging.version>1.2</commons-logging.version>
<jackson.version>2.5.1</jackson.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-io.version>1.3.2</commons-io.version>
<commons-beanutils.version>1.9.2</commons-beanutils.version>
</properties>
<dependencies>
<dependency>
<groupId>com.liu</groupId>
<artifactId>robot-service-interface</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.liu</groupId>
<artifactId>robot-domain</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.3.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</dependency>
</dependencies>
</project>
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.anliu.rotbot</groupId>
<artifactId>robot.interface</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>robot.interface Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
<spring.version>4.2.3.RELEASE</spring.version>
<log4j2.version>2.3</log4j2.version>
<slf4j.version>1.7.7</slf4j.version>
<commons-logging.version>1.2</commons-logging.version>
<jackson.version>2.5.1</jackson.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-io.version>1.3.2</commons-io.version>
<commons-beanutils.version>1.9.2</commons-beanutils.version>
<guava.version>18.0</guava.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jr</groupId>
<artifactId>jackson-jr-objects</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk7</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.3.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>
<build>
<finalName>robot.interface</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/resource</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.3.3.RELEASE</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<classesDirectory>target/classes</classesDirectory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/*.txt</exclude>
<exclude>**/*.list</exclude>
</excludes>
<archive>
<addMavenDescription>false</addMavenDescription>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.1</version>
<extensions>true</extensions>
</plugin>
</plugins>
</build>
</project>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liu</groupId>
<artifactId>robot-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>parent-root</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons-logging.version>1.2</commons-logging.version>
<dubbo-version>2.5.3</dubbo-version>
<zookeeper-version>3.4.6</zookeeper-version>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo-version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper-version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>robot-dao</module>
<module>robot-service-interface</module>
<module>robot-service</module>
<module>robot-controller</module>
<module>robot-domain</module>
<module>robot-common</module>
</modules>
</project><file_sep>jdbc.url=jdbc:mysql://127.0.0.1:3306/robot?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=<PASSWORD>
jdbc.driver.className=com.mysql.jdbc.Driver
jdbc.maxActive=20
jdbc.initialSize=5
jdbc.maxWait=60000
jdbc.minIdle=3
jdbc.removeAbandonedTimeout=180
mybatis.configfile=conf.xml
|
b8527a1f2dad4a1e99243fa961c18cd9d3badd7e
|
[
"Java",
"Maven POM",
"INI"
] | 8 |
Java
|
woshiliuan/javacode
|
4b3e1766f7e2985d8a2990ca249bb1f4cd92f2db
|
667703b78d1cea6cd64666d40bb606fc92251bc1
|
refs/heads/master
|
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jul 20, 2018 at 11:23 AM
-- Server version: 10.1.33-MariaDB
-- PHP Version: 7.2.6
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `employees_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `city`
--
CREATE TABLE `city` (
`id` int(10) UNSIGNED NOT NULL,
`state_id` int(11) NOT NULL,
`name` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `city`
--
INSERT INTO `city` (`id`, `state_id`, `name`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 1, 'sohaj', '2018-07-17 18:27:01', '2018-07-17 18:27:01', NULL),
(2, 1, 'cairo', '2018-07-17 18:27:15', '2018-07-17 18:27:15', NULL),
(3, 2, 'luxor', '2018-07-17 18:30:52', '2018-07-17 18:30:52', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `country`
--
CREATE TABLE `country` (
`id` int(10) UNSIGNED NOT NULL,
`country_code` varchar(3) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `country`
--
INSERT INTO `country` (`id`, `country_code`, `name`, `created_at`, `updated_at`, `deleted_at`) VALUES
(3, '123', 'cairo', '2018-07-17 18:26:19', '2018-07-17 18:26:19', NULL),
(2, '124', 'alex', '2018-07-17 18:23:32', '2018-07-17 18:23:32', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `department`
--
CREATE TABLE `department` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `department`
--
INSERT INTO `department` (`id`, `name`, `created_at`, `updated_at`, `deleted_at`) VALUES
(2, 'soda', '2018-07-18 07:18:34', '2018-07-18 07:18:34', NULL),
(3, 'cairo', '2018-07-19 14:04:55', '2018-07-19 14:04:55', NULL),
(4, 'sohaj', '2018-07-19 14:05:03', '2018-07-19 14:05:03', NULL),
(5, 'luxor', '2018-07-19 14:05:09', '2018-07-19 14:05:09', NULL),
(6, '2ana', '2018-07-19 14:05:20', '2018-07-19 14:05:20', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `division`
--
CREATE TABLE `division` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `division`
--
INSERT INTO `division` (`id`, `name`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'managment', '2018-07-17 18:20:45', '2018-07-17 18:20:45', NULL),
(2, 'counting', '2018-07-17 18:21:37', '2018-07-17 18:21:37', NULL),
(3, 'IT', '2018-07-17 18:21:52', '2018-07-17 18:21:52', NULL),
(4, 'testes', '2018-07-17 18:22:27', '2018-07-17 18:22:27', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `employees`
--
CREATE TABLE `employees` (
`id` int(10) UNSIGNED NOT NULL,
`lastname` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`firstname` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` varchar(120) COLLATE utf8mb4_unicode_ci NOT NULL,
`city_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`country_id` int(11) NOT NULL,
`zip` char(10) COLLATE utf8mb4_unicode_ci NOT NULL,
`age` int(11) NOT NULL,
`birthdate` date NOT NULL,
`date_hired` date NOT NULL,
`department_id` int(11) NOT NULL,
`division_id` int(11) NOT NULL,
`company_id` int(11) NOT NULL,
`picture` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `employees`
--
INSERT INTO `employees` (`id`, `lastname`, `firstname`, `email`, `address`, `city_id`, `state_id`, `country_id`, `zip`, `age`, `birthdate`, `date_hired`, `department_id`, `division_id`, `company_id`, `picture`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'fathi', 'zeyad', '<EMAIL>', 'altjmmoa elaoul', 2, 1, 2, '80000', 21, '1994-10-10', '2018-07-03', 2, 2, 0, 'avatars/9wtDpk7Ab9qUsPeuuuDMBfk3P9e0xBhPg9rwX4Kk.jpeg', '2018-07-18 05:26:43', '2018-07-18 07:44:06', NULL),
(2, 'farouk', 'hala', '<EMAIL>', 'altjmmoa elaoul', 3, 2, 3, '80000', 23, '1994-05-17', '2018-07-11', 2, 2, 0, 'avatars/C3peTwk9DR7eqGKlNK01Vq6HzN2fgn5gLfV2mmxA.jpeg', '2018-07-18 05:28:20', '2018-07-18 08:07:53', NULL),
(4, 'anas', 'mohmed', '<EMAIL>', 'pla pla', 3, 2, 3, '80000', 25, '1994-07-22', '2018-07-03', 2, 1, 0, 'avatars/2HZnZNetTHAAnPpwEPRzQafEya0KvXJNq7IGYPZt.jpeg', '2018-07-18 06:12:31', '2018-07-18 08:08:07', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `employee_salary`
--
CREATE TABLE `employee_salary` (
`id` int(10) UNSIGNED NOT NULL,
`employee_id` int(11) NOT NULL,
`salary` decimal(16,2) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(9, '2014_10_12_000000_create_users_table', 1),
(10, '2017_03_17_163141_create_employees_table', 1),
(11, '2017_03_18_001905_create_employee_salary_table', 1),
(12, '2017_03_18_003431_create_department_table', 1),
(13, '2017_03_18_004142_create_division_table', 1),
(14, '2017_03_18_004326_create_country_table', 1),
(15, '2017_03_18_005005_create_state_table', 1),
(16, '2017_03_18_005241_create_city_table', 1);
-- --------------------------------------------------------
--
-- Table structure for table `state`
--
CREATE TABLE `state` (
`id` int(10) UNSIGNED NOT NULL,
`country_id` int(11) NOT NULL,
`name` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `state`
--
INSERT INTO `state` (`id`, `country_id`, `name`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 2, 'egypt', '2018-07-17 18:24:45', '2018-07-17 18:24:45', NULL),
(2, 3, 'masr', '2018-07-17 18:26:42', '2018-07-17 18:26:42', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`username` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`lastname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`firstname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `email`, `password`, `lastname`, `firstname`, `remember_token`, `deleted_at`, `created_at`, `updated_at`) VALUES
(1, 'Zeyad', '<EMAIL>', <PASSWORD>', 'ENG', 'Zeyad', 'nhq9TxnDsG', NULL, '2017-03-25 18:43:48', '2018-07-19 14:28:48'),
(2, 'ZEX', '<EMAIL>', <PASSWORD>', 'Mr', 'Zeyad', 'O<PASSWORD>Yr<PASSWORD>HN<PASSWORD>', NULL, '2018-07-17 18:01:43', '2018-07-19 14:29:00');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `city`
--
ALTER TABLE `city`
ADD PRIMARY KEY (`id`),
ADD KEY `city_state_id_foreign` (`state_id`);
--
-- Indexes for table `country`
--
ALTER TABLE `country`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `department`
--
ALTER TABLE `department`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `division`
--
ALTER TABLE `division`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `employees`
--
ALTER TABLE `employees`
ADD PRIMARY KEY (`id`),
ADD KEY `employees_city_id_foreign` (`city_id`),
ADD KEY `employees_state_id_foreign` (`state_id`),
ADD KEY `employees_country_id_foreign` (`country_id`),
ADD KEY `employees_department_id_foreign` (`department_id`),
ADD KEY `employees_division_id_foreign` (`division_id`),
ADD KEY `employees_company_id_foreign` (`company_id`);
--
-- Indexes for table `employee_salary`
--
ALTER TABLE `employee_salary`
ADD PRIMARY KEY (`id`),
ADD KEY `employee_salary_employee_id_foreign` (`employee_id`);
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `state`
--
ALTER TABLE `state`
ADD PRIMARY KEY (`id`),
ADD KEY `state_country_id_foreign` (`country_id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `country`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `department`
--
ALTER TABLE `department`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `division`
--
ALTER TABLE `division`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `employees`
--
ALTER TABLE `employees`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `employee_salary`
--
ALTER TABLE `employee_salary`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT for table `state`
--
ALTER TABLE `state`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
e8cf8f1889151c07908d31fa07c6787783479f47
|
[
"SQL"
] | 1 |
SQL
|
ZeyadFathy/empl
|
98c18f95bb58f7343cf4bb5fe8fb9a7ff7742738
|
e2896f496f0322ac52ac2e9809ed0a72c65f4558
|
refs/heads/master
|
<file_sep>package 代理模式.Cglib代理.code;
/**
* @description:
* @author: zhangys
* @create: 2020-08-21 15:11
**/
public class ProxyFactory{
}
<file_sep>package 命令模式.code.command.impl.TV;
import 命令模式.code.command.Command;
import 命令模式.code.entity.TVEntity;
/**
* @description: 电视音量增大命令
* @author: zhangys
* @create: 2020-08-14 16:19
**/
public class TVUpVolumeCommand implements Command {
private final TVEntity tvEntity;
public TVUpVolumeCommand(TVEntity tvEntity) {
this.tvEntity = tvEntity;
}
@Override
public void execute() {
this.tvEntity.turnUpVolume();
}
@Override
public void undo() {
this.tvEntity.turnDownVolume();
}
}
<file_sep>##定义:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。<file_sep>package 迭代器与组合模式.code;
/**
* @description:
* @author: zhangys
* @create: 2020-08-19 15:28
**/
public interface Iterator {
Boolean hasNext();
Object next();
}
<file_sep>策略模式:定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。
<file_sep>package 工厂模式.抽象工厂模式.code.controller.impl.android;
import 工厂模式.抽象工厂模式.code.controller.UIController;
/**
* @author zhangys
*/
public class AndroidUIController implements UIController {
@Override
public void display() {
System.out.println("AndroidInterfaceController");
}
}<file_sep>



<file_sep>package 代理模式.静态代理.code;
/**
* @description:
* @author: zhangys
* @create: 2020-08-21 14:14
**/
public class UserDaoProxy implements IUserDao{
private final IUserDao target;
public UserDaoProxy(IUserDao target) {
this.target = target;
}
@Override
public void save() {
System.out.println("开始事物");
target.save();
System.out.println("提交事物");
}
}
<file_sep>package 状态模式.code.state.impl;
import 状态模式.code.context.Context;
import 状态模式.code.state.State;
/**
* @description: 售罄状态
* @author: zhangys
* @create: 2020-08-20 15:57
**/
public class NullGoodsState extends State {
public NullGoodsState(Context context) {
super(context);
}
@Override
public void pay() {
Integer goodsCount = context.getGoodsCount();
if (goodsCount != 0){
System.out.println("付钱中");
this.context.setState(new PayedState(this.context));
}else {
System.out.println("已售罄");
}
}
@Override
public void make() {
System.out.println("未付钱");
}
@Override
public void give() {
System.out.println("未付钱");
}
@Override
public void reback() {
System.out.println("未付钱");
}
}
<file_sep>package 工厂模式.抽象工厂模式.test;
import 工厂模式.抽象工厂模式.code.controller.OperationController;
import 工厂模式.抽象工厂模式.code.controller.UIController;
import 工厂模式.抽象工厂模式.code.factory.SystemFactory;
import 工厂模式.抽象工厂模式.code.factory.impl.WpFactory;
/**
* @description:
* @author: zhangys
* @create: 2020-08-12 14:13
**/
public class Main {
public static void main(String[] args) {
SystemFactory wpFactory = new WpFactory();
UIController interfaceController = wpFactory.createInterfaceController();
OperationController operationController = wpFactory.createOperationController();
interfaceController.display();
operationController.control();
}
}
<file_sep>package 工厂模式.抽象工厂模式.code.factory;
import 工厂模式.抽象工厂模式.code.controller.OperationController;
import 工厂模式.抽象工厂模式.code.controller.UIController;
/**
* @author zhangys
*/
public interface SystemFactory {
public OperationController createOperationController();
public UIController createInterfaceController();
}<file_sep>package 工厂模式.抽象工厂模式.code.factory.impl;
import 工厂模式.抽象工厂模式.code.controller.OperationController;
import 工厂模式.抽象工厂模式.code.controller.UIController;
import 工厂模式.抽象工厂模式.code.controller.impl.wp.WpOperationController;
import 工厂模式.抽象工厂模式.code.controller.impl.wp.WpUIController;
import 工厂模式.抽象工厂模式.code.factory.SystemFactory;
public class WpFactory implements SystemFactory {
@Override
public OperationController createOperationController() {
return new WpOperationController();
}
@Override
public UIController createInterfaceController() {
return new WpUIController();
}
}<file_sep>package 策略模式.test.duck;
import 策略模式.code.Duck;
import 策略模式.test.behavior.fly.NoWayFly;
import 策略模式.test.behavior.quack.SQuack;
/**
* @description: 橡皮鸭子
* @author: zhangys
* @create: 2020-08-04 15:58
**/
public class RubberDuck extends Duck {
@Override
public void display() {
System.out.println("这是一只橡皮鸭子");
}
public RubberDuck() {
super.flyBehavior = new NoWayFly();
super.quackBehavior = new SQuack();
}
}
<file_sep>package 工厂模式.抽象工厂模式.code.controller.impl.ios;
import 工厂模式.抽象工厂模式.code.controller.UIController;
/**
* @author zhangys
*/
public class IosUIController implements UIController {
@Override
public void display() {
System.out.println("IosInterfaceController");
}
}<file_sep>package 工厂模式.抽象工厂模式.code.controller.impl.ios;
import 工厂模式.抽象工厂模式.code.controller.OperationController;
/**
* @author zhangys
*/
public class IosOperationController implements OperationController {
@Override
public void control() {
System.out.println("IosOperationController");
}
}<file_sep>package 策略模式.code;
import 策略模式.code.behavior.FlyBehavior;
import 策略模式.code.behavior.QuackBehavior;
/**
* @description: 鸭子模型
* @author: zhangys
* @create: 2020-08-04 15:33
**/
public abstract class Duck {
/**
* 飞行行为
*/
public FlyBehavior flyBehavior;
/**
* 呱呱叫行为
*/
public QuackBehavior quackBehavior;
/**
* 飞行
*/
public void perfomFly(){
this.flyBehavior.fly();
}
/**
* 呱呱叫
*/
public void performQuack(){
this.quackBehavior.quack();
}
/**
* 游泳行为
*/
public void swim(){
System.out.println("游泳ing");
}
/**
* 模样
*/
public abstract void display();
public void setFlyBehavior(FlyBehavior flyBehavior){
this.flyBehavior = flyBehavior;
}
public void setQuackBehavior(QuackBehavior quackBehavior){
this.quackBehavior = quackBehavior;
}
}
<file_sep>package 工厂模式.工厂方法模式.test;
import 工厂模式.工厂方法模式.code.factory.Factory;
import 工厂模式.工厂方法模式.code.factory.impl.JpgFactory;
import 工厂模式.工厂方法模式.code.reader.Reader;
/**
* @description:
* @author: zhangys
* @create: 2020-08-12 11:17
**/
public class Main {
public static void main(String[] args) {
Factory jpgFactory=new JpgFactory();
Reader reader=jpgFactory.getReader();
reader.read();
}
}
<file_sep>package 命令模式.code.entity;
import 命令模式.code.enums.State;
/**
* @description: 灯
* @author: zhangys
* @create: 2020-08-14 15:20
**/
public class LightEntity {
private final String name;
private State state;
public LightEntity(String name) {
this.name = name;
this.state = State.OFF;
}
public void on(){
state = State.ON;
System.out.println(name + ":" + state.des);
}
public void off(){
state = State.OFF;
System.out.println(name + ":" + state.des);
}
}
<file_sep>##定义:
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。<file_sep>##蝇量模式(享元模式)
如想让某个类的一个实例能用来提供许多“虚拟实例”,就使用蝇量模式
运用共享技术有效地支持大量细粒度的对象。<file_sep>

<file_sep>
Java里边共有23种设计模式而工厂模式就有三种,它们分别是简单工厂模式(并不在23中模式之中),工厂方法模式以及抽象工厂模式,其中我们通常所说的工厂模式指的是工厂方法模式,工厂方法模式是日常开发中使用频率最高的一种设计模式,甚至在Android的源码中也是随处可见。
**简单工厂模式**
简单工厂模式其实并不算是一种设计模式,更多的时候是一种编程习惯。
**定义:**
定义一个工厂类,根据传入的参数不同返回不同的实例,被创建的实例具有共同的父类或接口。
**工厂方法模式**
工厂方法模式是简单工厂的仅一步深化, 在工厂方法模式中,我们不再提供一个统一的工厂类来创建所有的对象,而是针对不同的对象提供不同的工厂。也就是说每个对象都有一个与之对应的工厂。
**定义:**
定义一个用于创建对象的接口,让子类决定将哪一个类实例化。工厂方法模式让一个类的实例化延迟到其子类。
这次我们先用实例详细解释一下这个定义,最后在总结它的使用场景。
**抽象工厂模式**
这个模式最不好理解,而且在实际应用中局限性也蛮大的,因为这个模式并不符合开闭原则。实际开发还需要做好权衡。
抽象工厂模式是工厂方法的仅一步深化,在这个模式中的工厂类不单单可以创建一个对象,而是可以创建一组对象。这是和工厂方法最大的不同点。
**定义:**
提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。( 在抽象工厂模式中,每一个具体工厂都提供了多个工厂方法用于产生多种不同类型的对象)
<file_sep>
<file_sep>##定义:
主要将数据结构与数据操作分离。<file_sep>##定义:
用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。<file_sep>package 工厂模式.工厂方法模式.code.factory.impl;
import 工厂模式.工厂方法模式.code.factory.Factory;
import 工厂模式.工厂方法模式.code.reader.Reader;
import 工厂模式.工厂方法模式.code.reader.impl.GifReader;
/**
* @author zhangys
*/
public class GifReaderFactory implements Factory {
@Override
public Reader getReader() {
return new GifReader();
}
}<file_sep>##定义:
给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。<file_sep>package 观察者模式Observer.code.自己实现观察者模式.myInterface;
import java.util.ArrayList;
import java.util.List;
/**
* @description: 我的被观察者抽象类
* @author: zhangys
* @create: 2020-08-06 14:24
**/
public abstract class MyObservable {
private boolean changed = false;
private List<MyObserver> observerList;
public MyObservable(){
observerList = new ArrayList<>();
}
public synchronized void addObServer(MyObserver observer){
if (observer == null){
throw new NullPointerException();
}
if (!observerList.contains(observer)){
observerList.add(observer);
}
}
public synchronized void deleteObserver(MyObserver observer){
observerList.remove(observer);
}
public void notifyObservers(Object arg){
synchronized (this){
if (!changed){
return;
}
}
observerList.forEach(observer -> observer.update(this,arg));
}
public void notifyObservers(){
this.notifyObservers(null);
}
public synchronized void setChanged(){
this.changed = true;
}
public synchronized void clearChanged(){
this.changed = false;
}
}
<file_sep>package 生成器模式.test;
import 生成器模式.code.Company;
import 生成器模式.code.CompanyBuilder;
/**
* @description:
* @author: zhangys
* @create: 2020-08-24 16:44
**/
public class Main {
public static void main(String[] args) {
CompanyBuilder companyBuilder1 = new CompanyBuilder("公司", "北京", "010 2222222");
Company company1 = companyBuilder1.setVary("图书").setPostcode("1111111").build();
Company company2 = companyBuilder1.setVary("图书").setPostcode("2222222").build();
Company company3 = companyBuilder1.setVary("图书").setPostcode("3333333").build();
CompanyBuilder companyBuilder2 = new CompanyBuilder("公司", "上海", "010 1111111");
Company company11 = companyBuilder2.setVary("图书").setPostcode("1111111").build();
Company company12 = companyBuilder2.setVary("图书").setPostcode("2222222").build();
Company company13 = companyBuilder2.setVary("图书").setPostcode("3333333").build();
System.out.println(company1.toString());
System.out.println(company2.toString());
System.out.println(company3.toString());
System.out.println(company11.toString());
System.out.println(company12.toString());
System.out.println(company13.toString());
}
}
<file_sep>package 桥接模式.test;
import 桥接模式.code.draw.impl.GreenCircle;
import 桥接模式.code.draw.impl.GreenRect;
import 桥接模式.code.draw.impl.RedCircle;
import 桥接模式.code.shape.Shape;
import 桥接模式.code.shape.impl.Circle;
import 桥接模式.code.shape.impl.Rect;
/**
* @description:
* @author: zhangys
* @create: 2020-08-24 16:15
**/
public class Main {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
Shape greenRect = new Rect(100,100, 10, new GreenRect());
redCircle.draw();
greenCircle.draw();
greenRect.draw();
}
}
<file_sep>package 状态模式.code.state.impl;
import 状态模式.code.context.Context;
import 状态模式.code.state.State;
/**
* @description: 已付钱状态
* @author: zhangys
* @create: 2020-08-20 15:56
**/
public class PayedState extends State {
public PayedState(Context context) {
super(context);
}
@Override
public void pay() {
System.out.println("已经付过钱了");
}
@Override
public void make() {
Integer goodsCount = context.getGoodsCount();
if (goodsCount != 0){
System.out.println("制作中");
context.setGoodsCount(goodsCount - 1);
this.context.setState(new MadeState(this.context));
}else {
System.out.println("已售罄");
}
}
@Override
public void give() {
System.out.println("还未做好");
}
@Override
public void reback() {
Integer goodsCount = context.getGoodsCount();
System.out.println("退款中");
if (goodsCount != 0) {
this.context.setState(new NoPayState(this.context));
}else {
this.context.setState(new NullGoodsState(this.context));
}
}
}
<file_sep>package 代理模式.动态代理.test;
import 代理模式.动态代理.code.IUserDao;
import 代理模式.动态代理.code.ProxyFactory;
import 代理模式.动态代理.code.UserDao;
/**
* @description:
* @author: zhangys
* @create: 2020-08-21 14:10
**/
public class Main {
public static void main(String[] args) {
IUserDao target= new UserDao();
ProxyFactory proxyFactory = new ProxyFactory(target);
IUserDao proxyInstance = (IUserDao) proxyFactory.getProxyInstance();
proxyInstance.save();
proxyInstance.update();
}
}
<file_sep>##定义:
桥接模式将抽象部分与它实现的部分分离,使它们都可以独立地变化。
桥接模式是使用组合的方式,将某些部分解耦,使得可独立修改,而不影响双方。<file_sep>package 工厂模式.抽象工厂模式.code.controller.impl.wp;
import 工厂模式.抽象工厂模式.code.controller.OperationController;
public class WpOperationController implements OperationController {
@Override
public void control() {
System.out.println("WpOperationController");
}
}<file_sep>package 适配器模式与外观模式.外观模式.code.shape.impl;
import 适配器模式与外观模式.外观模式.code.shape.Shape;
/**
* @description:
* @author: zhangys
* @create: 2020-08-17 13:35
**/
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}
<file_sep>package 适配器模式与外观模式.外观模式.code.shape;
/**
* @description:
* @author: zhangys
* @create: 2020-08-17 13:33
**/
public interface Shape {
void draw();
}
<file_sep>package 模板方法模式.code.impl;
import 模板方法模式.code.Beverage;
/**
* @description:
* @author: zhangys
* @create: 2020-08-18 11:26
**/
public class Tea extends Beverage {
@Override
public void prepareIngredients() {
System.out.println("准备茶叶");
}
@Override
public void filter() {
System.out.println("过滤");
}
@Override
public void doUp() {
System.out.println("包装茶");
}
}
<file_sep>package 适配器模式与外观模式.适配器模式.test;
import 适配器模式与外观模式.适配器模式.code.adapter.IteratorEnumeration;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
/**
* @description:
* @author: zhangys
* @create: 2020-08-17 13:09
**/
public class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
Iterator<Integer> iterator = list.iterator();
Enumeration iteratorEnumeration = new IteratorEnumeration<>(iterator);
System.out.println(iteratorEnumeration.nextElement());
System.out.println(iteratorEnumeration.nextElement());
System.out.println(iteratorEnumeration.nextElement());
System.out.println(iteratorEnumeration.nextElement());
System.out.println(iteratorEnumeration.nextElement());
System.out.println(iteratorEnumeration.nextElement());
}
}
<file_sep>package 状态模式.test;
import 状态模式.code.context.Context;
/**
* @description:
* @author: zhangys
* @create: 2020-08-20 15:05
**/
public class Main {
public static void main(String[] args) {
Context context = new Context(2);
context.pay();
context.make();
context.give();
context.pay();
context.make();
context.give();
context.pay();
context.make();
context.give();
}
}
<file_sep>package 工厂模式.工厂方法模式.code.reader.impl;
import 工厂模式.工厂方法模式.code.reader.Reader;
public class GifReader implements Reader {
@Override
public void read() {
System.out.print("read gif");
}
}<file_sep>package 桥接模式.code.shape.impl;
import 桥接模式.code.draw.DrawAPI;
import 桥接模式.code.shape.Shape;
/**
* @description:
* @author: zhangys
* @create: 2020-08-24 16:36
**/
public class Rect extends Shape {
private int x, y, radius;
public Rect(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
<file_sep>package 适配器模式与外观模式.适配器模式.code.adapter;
import java.util.Enumeration;
import java.util.Iterator;
/**
* @description:
* @author: zhangys
* @create: 2020-08-17 13:20
**/
public class IteratorEnumeration<T> implements Enumeration {
Iterator<T> iterator;
public IteratorEnumeration(Iterator<T> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
public T nextElement() {
return iterator.next();
}
}
<file_sep>##生成器模式(Builder Pattern)
或称建造者模式,它封装了一个产品的构造过程,并允许按步骤构造。
##与其它模式的区别
会有一个建造者(builder)或者指挥者(director)提供了一个建造的方法build()用来产生最终要生成的对象。
与工厂模式的不同是建造对象的步骤是多步的,包含有多个组成部分。
与模板方法不同之处在于,模板方法定义的不一定是创建对象,而更多的是一个方法流程,这个方法流程的某个步骤是由子类来实现。<file_sep>package 工厂模式.抽象工厂模式.code.controller.impl.android;
import 工厂模式.抽象工厂模式.code.controller.OperationController;
/**
* @author zhangys
*/
public class AndroidOperationController implements OperationController {
@Override
public void control() {
System.out.println("AndroidOperationController");
}
}
<file_sep>##定义:
避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。
<file_sep>package 工厂模式.简单工厂模式.code;
import 工厂模式.简单工厂模式.code.shape.Shape;
import 工厂模式.简单工厂模式.code.shape.impl.CircleShape;
import 工厂模式.简单工厂模式.code.shape.impl.RectShape;
import 工厂模式.简单工厂模式.code.shape.impl.TriangleShape;
/**
* @description: 工厂类
* @author: zhangys
* @create: 2020-08-12 09:57
**/
public class ShapeFactory {
public static Shape getShape(String type){
Shape shape = null;
if ("circle".equalsIgnoreCase(type)){
shape = new CircleShape();
} else if ("rect".equalsIgnoreCase(type)){
shape = new RectShape();
} else if ("triangle".equalsIgnoreCase(type)){
shape = new TriangleShape();
}
return shape;
}
}
<file_sep>##定义:
复合模式结合两个或以上的模式,组成一个解决方案,解决一再发生的一般性问题。<file_sep>

<file_sep>package 命令模式.code.enums;
/**
* @description: 开关
* @author zhangys
*/
public enum State{
ON("打开"),
OFF("关闭");
public String des;
State(String des) {
this.des = des;
}
}<file_sep>package 观察者模式Observer.test;
import 观察者模式Observer.code.自己实现观察者模式.布告板实现.CurrentConditionsDisplay;
import 观察者模式Observer.code.自己实现观察者模式.布告板实现.ForecastDisplay;
import 观察者模式Observer.code.自己实现观察者模式.气象站实现.WeatherData;
/**
* @description:
* @author: zhangys
* @create: 2020-08-06 15:18
**/
public class Main {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
weatherData.setMeasurements(1,1,1);
weatherData.setMeasurements(2,2,2);
}
}
<file_sep>package 访问者模式.test;
import 访问者模式.code.Computer;
import 访问者模式.code.ComputerPart;
import 访问者模式.code.ComputerPartDisplayVisitor;
/**
* @description:
* @author: zhangys
* @create: 2020-08-25 10:26
**/
public class Main {
public static void main(String[] args) {
ComputerPart computer = new Computer();
computer.accept(new ComputerPartDisplayVisitor());
}
}
<file_sep>
<file_sep>package 代理模式.静态代理.test;
import 代理模式.静态代理.code.IUserDao;
import 代理模式.静态代理.code.UserDao;
import 代理模式.静态代理.code.UserDaoProxy;
/**
* @description:
* @author: zhangys
* @create: 2020-08-21 14:10
**/
public class Main {
public static void main(String[] args) {
IUserDao userDao = new UserDao();
IUserDao userDaoProxy = new UserDaoProxy(userDao);
userDaoProxy.save();
}
}
<file_sep>package 策略模式.test.behavior.fly;
import 策略模式.code.behavior.FlyBehavior;
/**
* @description: 不会飞行
* @author: zhangys
* @create: 2020-08-04 15:53
**/
public class NoWayFly implements FlyBehavior {
@Override
public void fly() {
System.out.println("不会飞行");
}
}
<file_sep>package 装饰者模式.code.decorator;
import 装饰者模式.code.Beverage;
import 装饰者模式.code.CondimentDecorator;
import java.util.List;
/**
* @description: 摩卡调料类
* @author: zhangys
* @create: 2020-08-07 14:46
**/
public class Mocha extends CondimentDecorator {
private Beverage beverage;
public Mocha(Beverage beverage) {
beverage.getDescriptions().add("摩卡");
this.beverage = beverage;
}
@Override
public List<String> getDescriptions() {
return beverage.getDescriptions();
}
@Override
public double cost() {
return beverage.cost() + 0.20;
}
}
<file_sep>
<file_sep>package 工厂模式.简单工厂模式.code.shape.impl;
import 工厂模式.简单工厂模式.code.shape.Shape;
/**
* @description:
* @author: zhangys
* @create: 2020-08-12 09:52
**/
public class CircleShape implements Shape {
public CircleShape() {
System.out.println( "CircleShape: created");
}
@Override
public void draw() {
System.out.println( "draw: CircleShape");
}
}
<file_sep>package 命令模式.code.enums;
public enum Volume {
HIGH(100,"高"),
MIDDLE(60,"中"),
DOWN(20,"低");
public Integer num;
public String des;
Volume(Integer num, String des){
this.num = num;
this.des = des;
}
public static Volume getHighVolume(Volume volume){
switch (volume.num){
case 100:
case 60:
return Volume.HIGH;
case 20:
return Volume.MIDDLE;
}
return null;
}
public static Volume getLowVolume(Volume volume){
switch (volume.num){
case 100:
return Volume.MIDDLE;
case 60:
case 20:
return Volume.DOWN;
}
return null;
}
}
<file_sep>package 状态模式.code.state.impl;
import 状态模式.code.context.Context;
import 状态模式.code.state.State;
/**
* @description: 已制作
* @author: zhangys
* @create: 2020-08-20 16:15
**/
public class MadeState extends State {
public MadeState(Context context) {
super(context);
}
@Override
public void pay() {
System.out.println("已付钱");
}
@Override
public void make() {
System.out.println("已制作");
}
@Override
public void give() {
System.out.println("交付中");
this.context.setState(new NoPayState(this.context));
}
@Override
public void reback() {
System.out.println("已制作完毕,不可退款");
}
}
<file_sep>package 装饰者模式.test;
import 装饰者模式.code.Beverage;
import 装饰者模式.code.beverage.Espresso;
import 装饰者模式.code.beverage.HouseBlend;
import 装饰者模式.code.decorator.Mike;
import 装饰者模式.code.decorator.Mocha;
/**
* @description:
* @author: zhangys
* @create: 2020-08-07 15:03
**/
public class main {
public static void main(String[] args) {
Beverage espresso = new Espresso();
System.out.println("点了一杯:" + espresso.getDescriptions() + ",$ " + espresso.cost());
Beverage houseBlend = new HouseBlend();
houseBlend = new Mocha(houseBlend);
houseBlend = new Mike(houseBlend);
houseBlend = new Mike(houseBlend);
System.out.println("点了一杯:" + houseBlend.getDescriptions() + ",$ " + houseBlend.cost());
}
}
|
85c98acdfd0698092fcb7d7bd54ee1ce28e83163
|
[
"Markdown",
"Java"
] | 60 |
Java
|
743551828/Design-Patterns-Java
|
5e2d7653e7ae6c5a43d3510985dcffebf16c7c28
|
195f420c166ae2d6be23d04ea3dba4346f869538
|
refs/heads/master
|
<file_sep># cool-rad-hip-map
Here is my cool new map.
All you have to do is search for your favorite restaurant,
click one of the icons on the map,
and then information about number of foursquare checkins,
health rating from the nyc health office,
foursquare rating,
and if you can reserve a table online from opentable will be displayed on the left side.
On the right side, you can see the address of the restaurant,
along with a button to add it to your favorites list.
You can register or login to save your favorites.
For this project, I used jQuery, Bootstrap, Bootstrap Material Design, Vue JS, VueFire, and Firebase.
<file_sep>//Google Map
var map;
// markers
var markers = [];
var restaurantsList = [];
//firebase
var config = {
apiKey: "<KEY>",
authDomain: "cool-rad-hip-map.firebaseapp.com",
databaseURL: "https://cool-rad-hip-map.firebaseio.com",
storageBucket: "cool-rad-hip-map.appspot.com",
};
firebase.initializeApp(config);
var db = firebase.database();
var user;
//vue
var vm;
//Vue.config.debug = true;
//jquery ready function
$(function(){
var styles = [];
var options = {
center: {lat: 40.712943, lng: -74.012881}, //NYC coordinates
zoom: 11,
styles: styles
};
// get DOM node in which map will be instantiated
var canvas = $("#map-canvas").get(0);
// instantiate map
map = new google.maps.Map(canvas, options);
//make the map appear inside a bootstrap column
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 60; // Calculate the top offset
$('#map-canvas').css('height', (h - offsetTop));
}).resize();
//send the search query to get data from foursquare
$("#form-search").submit(function(evt) {
evt.preventDefault();
var query = $("#form-search input[name=query]").val();
restaurants(query);
});
//register
$("#registerModal").submit(function(evt){
evt.preventDefault();
var email = $("#registerModal input[name=username]").val() + "@unknown.com";
var password = $("#registerModal input[name=password]").val();
var credential = firebase.auth.EmailAuthProvider.credential(email, password);
firebase.auth().currentUser.link(credential)
.then(function(result) {
//success
console.log(result);
$("#registerModal .modal-footer").empty();
$("<div></div>")
.addClass("alert alert-success text-center")
.attr("role", "alert")
.text("Congrats! You've claimed " + $("#registerModal input[name=username]").val() + " as your username.")
.appendTo("#registerModal .modal-footer");
vm.anon = false;
setTimeout(function(){
$("form[name='form-register']").trigger("reset");
$("#registerModal .modal-footer").empty();
$("#registerModal").modal('hide');
}, 3000);
}, function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
if (errorCode == "auth/email-already-in-use") {
$("#registerModal .modal-footer").empty();
$("<div></div>")
.addClass("alert alert-danger text-center")
.attr("role", "alert")
.text("Sorry. That username is already in use. Please choose another.")
.appendTo("#registerModal .modal-footer");
}
});
});
//login
$("#loginModal").submit(function(evt){
evt.preventDefault();
var username = $("#loginModal input[name=username]").val();
var email = username + "@unknown.com";
var password = $("#loginModal input[name=password]").val();
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(data){
console.log(data);
$("#loginModal .modal-footer").empty();
$("<div></div>")
.addClass("alert alert-success text-center")
.attr("role", "alert")
.text("Congrats! You're logged in as " + username + ".")
.appendTo("#loginModal .modal-footer");
setTimeout(function(){
$("form[name='form-login']").trigger("reset");
$("#loginModal .modal-footer").empty();
$("#loginModal").modal('hide');
}, 3000);
}, function(error){
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
$("#loginModal .modal-footer").empty();
$("<div></div>")
.addClass("alert alert-danger text-center")
.attr("role", "alert")
.text("Sorry. Username or password is incorrect. Try again.")
.appendTo("#loginModal .modal-footer");
});
});
//logout
$("#logout").click(function(){
firebase.auth().signOut();
});
//login anonymously
firebase.auth().onAuthStateChanged(function(userid) {
if (userid) {
// User is signed in.
var isAnonymous = userid.isAnonymous;
vm.anon = isAnonymous;
user = userid.uid;
console.log(user);
vm.$bindAsArray("list", db.ref("users/" + user + "/list/"));
// ...
} else {
// User is signed out.
// ... then log back in anonymously
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
}
// ...
});
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
vueStart();
//material design
$.material.init();
});
function restaurants(input) {
var sw = map.getBounds().getSouthWest().toJSON();
var ne = map.getBounds().getNorthEast().toJSON();
var parameters = {
client_id: "WGWS12ZMNIMCPUEBTOTMSZGZZKRQKI2P121UPO1SQKGA1WGD",
client_secret: "<KEY>",
v: "20160830",
intent: "browse",
sw: sw.lat + "," + sw.lng,
ne: ne.lat + "," + ne.lng,
query: input,
limit: 10,
categoryId: "4d4b7105d754a06374d81259"
};
$.getJSON("https://api.foursquare.com/v2/venues/search", parameters)
.done(function(data, textStatus, jqXHR){
//remove markers
markers.forEach(function(i){
i.setMap(null);
});
markers = [];
//remove restaurants
restaurantsList = [];
//add restaurants
restaurantsList = data.response.venues;
//add marker to markers
data.response.venues.forEach(function(i, index){
var position = new google.maps.LatLng(i.location.lat,i.location.lng);
var image = i.categories[0].icon.prefix + "bg_32" + i.categories[0].icon.suffix;
var name = i.name;
var marker = new google.maps.Marker({
position: position,
icon: image,
title: name,
index: index
});
marker.addListener('click', function(){
health(restaurantsList[index]);
checkins(restaurantsList[index]);
reserve(restaurantsList[index]);
rating(restaurantsList[index]);
info(restaurantsList[index]);
});
markers.push(marker);
});
//display markers
markers.forEach(function(i){
i.setMap(map);
});
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log(errorThrown.toString());
});
}
function health(rest){
if(rest.contact.phone == undefined){
$("#grade").text("No Grade. Can't find it.");
//change panel color
$("#grade").parent().parent().removeClass().addClass("panel panel-primary");
}
else{
var parameters = {
"$$app_token": "<KEY>",
"phone": rest.contact.phone,
"$select": "dba,grade,grade_date",
"$order": "grade_date DESC",
"$where": "grade IS NOT NULL",
"$limit": 50
};
$.getJSON("https://data.cityofnewyork.us/resource/9w7m-hzhe.json", parameters)
.done(function(data, textStatus, jqXHR){
if(data.length == 0){
$("#grade").text("No Grade at all.");
//change panel color
$("#grade").parent().parent().removeClass().addClass("panel panel-primary");
}
else{
$("#grade").text(data[0].grade);
//change panel color
if (data[0].grade == "A"){
$("#grade").parent().parent().removeClass().addClass("panel panel-success");
} else if (data[0].grade == "B") {
$("#grade").parent().parent().removeClass().addClass("panel panel-warning");
} else if (data[0].grade == "C") {
$("#grade").parent().parent().removeClass().addClass("panel panel-danger");
} else {
$("#grade").parent().parent().removeClass().addClass("panel panel-primary");
}
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log(errorThrown.toString());
});
}
}
function checkins(rest) {
$("#checkins").text(rest.stats.checkinsCount);
}
function reserve(rest){
if(rest.location.address == undefined){
$("#reserve").text("Can't reserve because no address.");
//change panel color
$("#reserve").parent().parent().removeClass().addClass("panel panel-primary");
}
else{
var parameters = {
address: rest.location.address
};
$.getJSON("https://opentable.herokuapp.com/api/restaurants", parameters)
.done(function(data, textStatus, jqXHR){
console.log(data);
if(data.total_entries == 0){
$("#reserve").text("No Reservations.");
$("#reserve").parent().parent().removeClass().addClass("panel panel-info");
}
else{
$("#reserve").html($("<a></a>")
.attr("href", data.restaurants[0].reserve_url)
.attr("target", "_blank")
.text("Click here to reserve."));
$("#reserve").parent().parent().removeClass().addClass("panel panel-success");
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log(errorThrown.toString());
});
}
}
function rating(rest){
var url = "https://api.foursquare.com/v2/venues/" + rest.id + "/";
var parameters = {
client_id: "WGWS12ZMNIMCPUEBTOTMSZGZZKRQKI2P121UPO1SQKGA1WGD",
client_secret: "<KEY>",
v: "20160830"
};
$.getJSON(url, parameters)
.done(function(data, textStatus, jqXHR){
console.log(data);
if (data.response.venue.rating == undefined){
$("#rating").text("No rating available.");
$("#rating").parent().parent().removeClass().addClass("panel panel-primary");
$("#rating").parent().siblings(".panel-heading").removeAttr("style");
}
else {
$("#rating").text(data.response.venue.rating);
$("#rating").parent().siblings(".panel-heading").attr("style", "background-color: #" + data.response.venue.ratingColor);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log(errorThrown.toString());
});
}
function info(rest){
$("#info").empty();
var content = rest.name + "<br>" + rest.location.address + "<br>" + rest.location.formattedAddress[1];
$("#info").html(content);
if($("#addButton").attr("disabled")!=undefined){
$("#addButton").attr("disabled", false);
}
$("#addButton").off("click");
$("#addButton").click(function(){
vm.add(rest.name);
});
}
function vueStart(){
vm = new Vue({
el: '#fav',
data: {
anon: true
},
firebase: {
list: db.ref("users/" + user + "/list/")
},
methods: {
remove: function (key) {
db.ref("users/" + user + "/list/").child(key).remove();
},
add: function(name) {
db.ref("users/" + user + "/list/").push(name);
}
}
});
console.log(user);
}
|
40fe55d9530f9e96d6cc213c5f31b4f5e56b23be
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
jedawson/cool-rad-hip-map
|
f001efe26f7afd08d0088fbae0e9b3b6ed2beb6c
|
867a25c6e7149ef6fb655298c3eb9da6d43770fe
|
refs/heads/master
|
<repo_name>aqfort/integrator<file_sep>/README.md
# Integrator
## NetBeans Project
Interface -- java
Calculations (parallel) -- C++ with omp
Simpson's rule is used to find the integral
jfreechart-1.0.19 is required

<file_sep>/makefile
do:
javah -o JNIDemoJava.h -classpath JNIDemoJava/build/classes jnidemojava.Main
mv JNIDemoJava.h JNIDemoCdl/JNIDemoJava.h
<file_sep>/JNIDemoCdl/JNIDemoCPP.cpp
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include <jni.h>
#include <iostream>
#include "JNIDemoJava.h"
#include <vector>
#include <iomanip>
#include <algorithm>
#include <math.h>
#include <cmath>
#include <omp.h>
using namespace std;
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
jdouble* C;
typedef double (*pointFunc) (double);
double f(double x) {
return (C[0] * pow(x,4) +
C[1] * pow(x,3) +
C[2] * pow(x,2) +
C[3] * x +
C[4] * sin(x) +
C[5] * cos(x) +
C[6] * exp(x) +
C[7]);
}
double simpson_integral(pointFunc f, double a, double b, int n) {
int i = 0;
const double h = (b - a) / n;
double k1 = 0, k2 = 0;
///////////////// parallel sum
#pragma omp parallel for reduction(+: k1, k2)
for(i = 1; i < n; i += 2) {
k1 += f(a + i * h);
k2 += f(a + (i + 1) * h);
}
return h / 3 * (f(a) + 4 * k1 + 2 * k2);
}
JNIEXPORT void JNICALL Java_jnidemojava_Main_nativePrintCPP
(JNIEnv *env, jobject obj) {
cout << "\nHello from C++!\n";
}
JNIEXPORT jint JNICALL Java_jnidemojava_Main_00024JNIFunction_multiply
(JNIEnv *, jobject, jint a, jint b) {
return a * b;
}
/*JNIEXPORT jdouble JNICALL Java_jnidemojava_Main_00024JNIFunction_nativeIntegrate
(JNIEnv *, jobject, jdouble ja, jdouble jb, jdouble jc0,
jdouble jc1,
jdouble jc2,
jdouble jc3,
jdouble jc4,
jdouble jc5,
jdouble jc6,
jdouble jc7) {*/
JNIEXPORT jdouble JNICALL Java_jnidemojava_Main_00024JNIFunction_nativeIntegrate
(JNIEnv *env, jobject obj,
jdouble ja,
jdouble jb,
jdoubleArray jC,
jdoubleArray jXY) {
double a = ja;
double b = jb;
double eps = 0.001;
double s1, s;
int n = 1; // steps number
///////// java format -> c/c++ format
C = env->GetDoubleArrayElements(jC, JNI_FALSE);
double *XY = env->GetDoubleArrayElements(jXY, JNI_FALSE);
///////////////////////////////////////////////////////
s1 = simpson_integral(f, a, b, n); // first approximation
do {
s = s1; // second approx
n = 2 * n; // increase number of steps two times
s1 = simpson_integral(f, a, b, n);
}
while (fabs(s1 - s) > eps); // to make proper accuracy eps
ja = s1;
///////////////////////////////////////////////////////
jsize SIZE = env->GetArrayLength(jXY);
const double h = (b - a) / SIZE;
s = 0;
for (int i = 0; i < SIZE; i++) {
XY[i] = f(s);
s += h;
}
///////// c/c++ format -> java format
//env->SetDoubleArrayRegion(RESULT, 0, size, C);
///////// clear (release) the space allocated for c/c++ array C
env->ReleaseDoubleArrayElements(jC, C, 0);
env->ReleaseDoubleArrayElements(jXY, XY, 0);
///////////////////////////////////////////////////////
return ja;
//return RESULT;
}
|
f91214b80abe689df4955982401709117c0fbd2b
|
[
"Markdown",
"Makefile",
"C++"
] | 3 |
Markdown
|
aqfort/integrator
|
e1db22124bb30ca17a37ab0c9663ce888e95539f
|
632ad8c6f4b510499a04e132194f532fe1b5e24c
|
refs/heads/master
|
<repo_name>cloud9ers/c9twitter<file_sep>/apps/crawler/routing.py
APP_ROOT = '/crawler'
def router(map):
#map.connect('master', '/{controller}/{action}') # master app example
with map.submapper(path_prefix=APP_ROOT) as m:
# m.connect("home", "/", controller="main", action="index")
m.connect(None, "/", controller='C9Twitter', action='search')
# ADD CUSTOM ROUTES HERE
#m.connect(None, "/error/{action}/{id}", controller="error")
<file_sep>/apps/crawler/tasks/asynch.py
from celery.task import task
import httplib
import urllib
import json
import socket
SEARCH_HOST="search.twitter.com"
SEARCH_PATH="/search.json"
@task
def query(tag):
'''
Executes a GET request to search twitter API for the passed tags
Returns a tuple (tag, number of results')
'''
c = httplib.HTTPConnection(SEARCH_HOST)
params = {'q' : tag}
path = "%s?%s" %(SEARCH_PATH, urllib.urlencode(params))
try:
c.request('GET', path)
r = c.getresponse()
data = r.read()
c.close()
try:
result = json.loads(data)
except ValueError:
print 'Error in parsing the retrieved data'
return (tag, 0)
if 'results' not in result or not result['results']:
print 'No results in the retrieved data'
return (tag, 0)
return (tag, len(result['results']))
except (httplib.HTTPException, socket.error, socket.timeout), e:
print "search() error: %s" %(e)
return (tag, 0)<file_sep>/server.ini
[main]
applications = ['apps.crawler']
excluded_applications_from_worker = []
ip = 0.0.0.0
is_subdomain_aware = True
mode = DEV
port = 8800
project_name = c9twitter
[session]
secret = 2e32b2f77026475bae58a874df55a4a82a816ce8d419452697ab87142a972bd6
secure = False
timeout = 600
url = mongodb://localhost:27017/c9#session
[store]
auto_create_collections = None
db_name = c9_c9twitter
ip = 127.0.0.1
<file_sep>/README.md
c9twitter
=========
Python/J25 minimal tutorial shows the distributed processing with J25 horizontally scaleble workers
Installation
------------
Prerequisites:
-------------
* Python 2.7
* RabbitMQ
* Python-PyPI
Prepare your development environment:
Create a virtualenv:
arefaey@arefaey-Ideapad:~/workspace$ virtualenv c9devel --distribute --extra-search-dir=/usr/local/lib/python2.7/dist-packages/
From your created virtualenv, activate the virtualenv:
arefaey@arefaey-Ideapad:~/workspace/c9devel$ source bin/activate
Prompt should now be turned into:
(c9devel)arefaey@arefaey-Ideapad:
install J25 framework
(c9devel)arefaey@arefaey-Ideapad:~/workspace/c9devel/c9twitter$ pip install -v j25framework
Installation of J25 will automatically download and install all J25 dependencies
Test your successful installation by the command j25 with no options:
(c9devel)arefaey@arefaey-Ideapad:~/workspace/c9devel$ j25
No command is given
Possible commands: ['run-worker', 'dump-config', 'run-server', 'new-project', 'new-app', 'install-app']
Create a new project:
(c9devel)arefaey@arefaey-Ideapad:~/workspace/c9devel$ j25 new-project c9twitter
Creating project: c9twitter
2012-06-06 16:26:47,914 - root - INFO - dumping configuration into file c9twitter/server.ini
From your project directory, add a new app to your project:
arefaey@arefaey-Ideapad:~/workspace/c9devel/c9twitter$ j25 new-app crawler
2012-06-06 16:36:36,710 - root - INFO - loading configuration from file server.ini
2012-06-06 16:36:36,730 - root - INFO - dumping configuration into file server.ini
2012-06-06 16:36:36,731 - j25 - INFO - Application crawler has been created. Current project has been configured.
You now will notice like most MVC framework, you have a new app directory “crawler” under project/apps/ “c9devel/apps/”:
arefaey@arefaey-Ideapad:~/workspace/c9devel/c9twitter$ cd apps/crawler/
arefaey@arefaey-Ideapad:~/workspace/c9devel/c9twitter/apps/crawler$ ls
config.py controllers __init__.py lib model routing.py static tasks templates tests tmp
Scenario
--------
Our scenario will be very simple, we will create a web controller responds to a specific URL requests and accepts a twitter search query as an array of tags, which will fire set of tasks to run asynchronously, each will grab the results of a tag.
We will notice the time consumed to execute these search processes decrease proportionally with the increase of the number of workers.
This is to endorse the idea of viral asynchronous tasks invocation and workers scalability.
Test
-------
Now you are ready to run your project, start the server:
(c9devel)arefaey@arefaey-Ideapad:~/workspace/c9devel/c9twitter$ j25 run-server -l INFO
Start a worker in another shell:
(c9devel)arefaey@arefaey-Ideapad:~/workspace/c9devel/c9twitter$ j25 run-worker -l INFO
From your browser request this URL passing your favorite tag array to search twitter for:
http://127.0.0.1:8800/crawler/?tag=montaro23&tag=cloud9ers&tag=j25&tag=tahrir&tag=invalidtag
You should get some results in the browser like this:
Your search results:
montaro23
has 15 tweets
cloud9ers
has 5 tweets
j25
has 15 tweets
tahrir
has 15 tweets
invalidtag
has 0 tweets
All search queries consumed in: 239.180707932 ms.
Start now 2 additional workers in 2 separate shells, hit the same link and watch the difference in the time consumed:
Your search results:
montaro23
has 15 tweets
cloud9ers
has 5 tweets
j25
has 15 tweets
tahrir
has 15 tweets
invalidtag
has 0 tweets
All search queries consumed in: 84.3038082123 ms.
Enjoy ;)<file_sep>/apps/crawler/controllers/controller.py
from j25.web import Controller
from apps.crawler.tasks.asynch import query
from celery.task.sets import TaskSet
from time import time
class C9Twitter(Controller):
def search(self):
'''
Extracts the search tags from the request query string
Runs set of tasks asynchronusly, each per tag
Returns the search results and the time consumed
'''
tags = self.request.GET.getall('tag')
tasks = []
# prepare list of sub tasks
for tag in tags:
tasks.append(query.subtask((tag, )))
job = TaskSet(tasks=tasks)
result = job.apply_async()
# calculate the time consumed
start_time = time()
all_tags_data = result.join()
end_time = time()
spent = (end_time - start_time)*100
# prepare the output text
output = 'Your search results: \n'
for tag_data in all_tags_data:
output += tag_data[0] + '\n' + 'has %s tweets' % tag_data[1] + '\n'
output += 'All search queries consumed in: %s ms.' % spent
return output
|
aa3cca1b5a2fffc9438cd911fe0fdfaff308d18d
|
[
"Markdown",
"Python",
"INI"
] | 5 |
Python
|
cloud9ers/c9twitter
|
1ad9de790c05d04f412cbf7184f2f7ac422baffd
|
3339bc7481e50a6245bd24ae263de99163745bde
|
refs/heads/master
|
<file_sep> import java.util.*;
public abstract class Player {
private String playerName;
private int playAsType;
private ArrayList<Play> playHistory = new ArrayList<Play>();
//private ArrayList<Score> sscoreHistory = new ArrayList<Score>();
private int totalScore;
public Player (String playerName) {
this.playerName = playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerName(){
return playerName;
}
public void setPlayAsType (int playAsType) {
this.playAsType = playAsType;
}
public int getPlayAsType(){
return playAsType;
}
public void AddPlayHistory(Play p) {
playHistory.add(p);
}
//public void AddPlayScore (Score s) {
// sscoreHistory.add(s);
//}
public Play getLastPLay () {
int last = playHistory.size() -1;
return playHistory.get(last);
}
public int gettotalScore() {
return totalScore;
}
abstract Play Play();
}
<file_sep># VCR-NCIRL-JAVAPROJ
|
0591f528d4ed33cbd6e1d69f3b870ba6c0983cc8
|
[
"Markdown",
"Java"
] | 2 |
Java
|
vdate-ncirl/VCR-NCIRL-JAVAPROJ
|
ad1efaba4dea656d685a8ff84341dc652585e22d
|
461d757dc7e8a277c2daf9bbc2034f7c0d4480b6
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using Selenium.UnitTestProject.QCPages;
using Selenium.UnitTestProject.EnvironmentConfig;
using Selenium.UnitTestProject.PSPPages;
namespace Selenium.UnitTestProject
{
class Login
{
[SetUp]
public void Initialize()
{
//Managed from App.config
}
[Test]
public void PSPLoginTest()
{
using (IWebDriver driver = WebDriverManager.WebDriverManager.GetWebDriverForConfig())
{
PSPPages.PSPLandingPage.clickOnPrivateEventsButton(driver);
}
}
[TearDown]
public void EndTest()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.QCPages
{
class ShowManagerSkillsLicencePage
{
public static IWebElement element = null;
public static string getTextForHeader(IWebDriver driver)
{
string showManagerSkillsLicenceHeader = driver.FindElement(By.XPath("//*[@id='dash']/div/dl/dt[1]")).Text;
return showManagerSkillsLicenceHeader;
}
public static IWebElement selectDeclineSkillsLicenceButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div/dl/dd[8]/ul/li[2]/a/span[1]"));
return element;
}
public static IWebElement selectApproveSkillsLicenceButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div/dl/dd[8]/ul/li[1]/a/span[1]"));
return element;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.QCPages
{
class ManagerDashboardPage
{
public static IWebElement element = null;
public static string getTextForHeader(IWebDriver driver)
{
string managerDashboardHeader = driver.FindElement(By.XPath(".//*[@id='dash']/div[1]/div/h2")).Text;
return managerDashboardHeader;
}
public static string getSkillsLicencePendingApproval(IWebDriver driver)
{
string managerDashboardHeader = driver.FindElement(By.XPath("//*[@id='dash']/div[1]/table/tbody/tr[1]/td[1]/a/span[1]")).Text;
return managerDashboardHeader;
}
public static IWebElement selectSkillsLicenceForReview(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div[1]/table/tbody/tr[1]/td[1]/a/span[1]"));
return element;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.QCPages
{
class HeaderPage
{
public static IWebElement element = null;
public static IWebElement quotationsMenuOption(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='head']/div[1]/ul/li[3]/span"));
return element;
}
public static IWebElement salesPortalMenuOption(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='head']/div[1]/ul/li[3]/ul/li[1]/a"));
return element;
}
}
}
<file_sep>using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selenium.UnitTestProject
{
class CustomerApprovalPage
{
public static IWebElement element = null;
public static string getTextForHeader(IWebDriver driver)
{
string actualvalue = driver.FindElement(By.XPath(".//*[@id='main']/div[1]/h2")).Text;
return actualvalue;
}
public static IWebElement getBAPSSection(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='how_to_send']/label[3]"));
return element;
}
public static IWebElement getBAPSButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='how_to_send']/label[3]/div[2]/span"));
return element;
}
public static IWebElement getPortalSection(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='how_to_send']/label[1]"));
return element;
}
public static IWebElement selectSendToCustomerViaPortalButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='btn_CustomerApproval_SendPortal']/span[1]"));
return element;
}
public static IWebElement getEchosignSection(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='how_to_send']/label[2]"));
return element;
}
public static IWebElement selectSendToCustomerViaEchosignButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='btn_CustomerApproval_SendAdobeSign']/span[1]"));
return element;
}
public static string getTextForEchosignSubHeading(IWebDriver driver)
{
string actualvalue = driver.FindElement(By.XPath("//*[@id='main']/div[4]/div[1]/h2")).Text;
return actualvalue;
}
public static string getTextForPortalSubHeading(IWebDriver driver)
{
string actualvalue = driver.FindElement(By.XPath("//*[@id='main']/div[3]/div[1]/h2")).Text;
return actualvalue;
}
public static string getTextForBAPSSubHeading(IWebDriver driver)
{
string actualvalue = driver.FindElement(By.XPath("//*[@id='main']/div[5]/div[1]/h2")).Text;
return actualvalue;
}
public static IWebElement selectQuoteA(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div[5]/div[2]/div/div[1]/label"));
return element;
}
public static IWebElement selectQuoteAEchosign(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div[4]/div[2]/div/div[1]/label"));
return element;
}
public static IWebElement selectQuoteB(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='main']/div[4]/div[2]/div[1]/div[2]/label"));
return element;
}
public static IWebElement selectQuoteC(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='main']/div[4]/div[2]/div[1]/div[3]/label"));
return element;
}
public static IWebElement selectCreateButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='btn_CustomerApproval_SendBAPS']/span[1]"));
return element;
}
}
}
<file_sep>using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selenium.UnitTestProject
{
class DashboardWithMeDeclinedPage
{
public static IWebElement element = null;
/**
* Returns the Header element
* @param driver
* @return
*/
public static String getTextForHeader(IWebDriver driver)
{
string getTextForHeader = driver.FindElement(By.XPath("//*[@id='dash']/div/div/h2/text()")).Text;
return getTextForHeader;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.QCPages
{
class AlterSkillsLicencePage
{
public static IWebElement element = null;
/**
* Returns the quote A text box
* @param driver
* @return
*/
public static string getTextForHeader(IWebDriver driver)
{
string actualValue5 = driver.FindElement(By.XPath(".//*[@id='dash']/div/dl/dt[1]")).Text;
return actualValue5;
}
public static IWebElement getNewCustomerCheckbox(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div/dl/dd[3]/ul/li[2]/span"));
return element;
}
public static string getTextForNewCustomerCheckboxUnticked(IWebDriver driver)
{
string actualValue6 = driver.FindElement(By.XPath("//*[@id='dash']/div/dl/dd[3]/ul/li[2]/span")).Text;
return actualValue6;
}
public static string getTextForNewCustomerCheckboxTicked(IWebDriver driver)
{
string actualValue6 = driver.FindElement(By.XPath("//*[@id='dash']/div/dl/dd[3]/ul/li[1]/span")).Text;
return actualValue6;
}
public static IWebElement quoteATextBox(IWebDriver driver)
{
element = driver.FindElement(By.Id("the_main_input"));
return element;
}
/**
* Returns the hierarchy threshold warning
*
*
*/
public static string getHierarchyWarning(IWebDriver driver)
{
string actualValue7 = driver.FindElement(By.XPath("//*[@id='main']/div/table/tbody[1]/tr[3]/td[5]/span[5]")).Text;
return actualValue7;
}
/**
* Returns the ITpractice
* @param driver
* @return
*/
public static IWebElement itPracticeSelect(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div/table/tbody[1]/tr[1]/th/span[1]/span"));
return element;
}
/**
* Returns All Vendors
* @param driver
* @return
*/
public static IWebElement itAllVendors(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div/table/tbody[1]/tr[1]/th/span[3]/span[2]/span"));
return element;
}
/**
*
* returns Agile and Scrum Vendor
*
*/
public static IWebElement agileAndScrumPremium(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div/table/tbody[1]/tr[3]/td[2]/input"));
return element;
}
/**
*
* returns Agile and Scrum Vendor's Quote A discount box
*
*/
public static IWebElement QuoteADiscountBox(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div/table/tbody[1]/tr[3]/td[2]/input"));
return element;
}
//
/**
*
* selects the SaveAndSend button
*
*/
public static void clickOnSaveAndSendButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div/table/tfoot/tr/td[1]/ul/li[1]/a/span[1]"));
element.Click();
}
/**
*
* selects the Draft button
*
*/
public static void clickOnDraftButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='saveasdraft_link']"));
element.Click();
}
/**
*
* selects the colour of the threshold warning box
*
*/
public static String checkColourOfQuoteADiscountBox(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div/table/tbody[1]/tr[3]/td[2]/input"));
string colour = element.GetCssValue("colour");
return colour;
}
}
}
<file_sep>using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selenium.UnitTestProject
{
class DashboardWithMeApprovedPage
{
public static IWebElement element = null;
/**
* Returns the search box element
* @param driver
* @return
*/
public static String getTextForApprovedBody(IWebDriver driver)
{
string getTextForApprovedBody = driver.FindElement(By.XPath(".//*[@id='dash']/div/table/tbody/tr/td")).Text;
return getTextForApprovedBody;
}
public static IWebElement getApprovedLicence(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div/table/tbody/tr/td[1]/a/span[1]"));
return element;
}
public static String getTextForApprovedLicenceLine(IWebDriver driver)
{
string getTextForApprovedLicenceLine = driver.FindElement(By.XPath(".//*[@id='dash']/div/table/tbody/tr/td[1]/a/span[1]")).Text;
return getTextForApprovedLicenceLine;
}
public static IWebElement clickSuspendApprovedLicence(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div/table/tbody/tr[1]/td[7]/a/span"));
return element;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Chrome;
namespace Selenium.UnitTestProject.WebDriverManager
{
public static class WebDriverManager
{
public static IWebDriver GetWebDriverForConfig()
{
IWebDriver driver;
switch (EnvironmentConfig.ConfigurationWrapper.Browser())
{
case "FireFox":
driver = GetWebDriverFireFox();
break;
case "IE":
driver = GetWebDriverFireIE();
break;
case "Chrome":
driver = GetWebDriverForChrome();
break;
case "Headless":
driver = GetHeadlessWebDriverForChrome();
break;
default:
throw new Exception("Unknown browser:" + EnvironmentConfig.ConfigurationWrapper.Browser());
}
driver.Manage().Timeouts().ImplicitWait =
TimeSpan.FromSeconds(
EnvironmentConfig.ConfigurationWrapper.WebDriverTimeout()
);
driver.Manage().Window.Maximize();
driver.Url = EnvironmentConfig.ConfigurationWrapper.GetURLFromEnvironmentKey();
return driver;
}
private static IWebDriver GetWebDriverForChrome()
{
IWebDriver driver;
driver = new ChromeDriver();
return driver;
}
private static IWebDriver GetHeadlessWebDriverForChrome()
{
IWebDriver driver;
driver = new ChromeDriver();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
return driver;
}
private static IWebDriver GetWebDriverFireFox()
{
IWebDriver driver;
driver = new FirefoxDriver();
return driver;
}
private static IWebDriver GetWebDriverFireIE()
{
IWebDriver driver;
driver = new InternetExplorerDriver();
return driver;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.PSPPages
{
class PSPLandingPage
{
public static IWebElement element = null;
/**
* Returns the search box element
* @param driver
* @return
*
*
*/
public static string getTextForHeader(IWebDriver driver)
{
string actualValue1 = driver.FindElement(By.XPath("//*[@id='dash']/div/div/h2")).Text;
return actualValue1;
}
public static void clickOnPrivateEventsButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='MainMenu_mnuMainMenu']/ul/li[5]/a"));
element.Click();
}
public static IWebElement skillsLicenceHeader(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div/div/h2"));
return element;
}
public static IWebElement approvedCount(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div/table/tbody/tr[3]/td[2]"));
return element;
}
public static IWebElement approved(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div/table/tbody/tr[3]/td[1]/a/span"));
return element;
}
public static IWebElement approvedButSuspended(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div[1]/table/tbody[1]/tr[4]/td[1]/a/span"));
return element;
}
/**
* Returns the create skills licence button
* @param driver
* @return
*/
public static IWebElement createSkillsLicenceButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div/ul/li/a/span[1]"));
return element;
}
public static IWebElement userCircle(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='base']/ul/li[2]/span[1]/i"));
return element;
}
public static IWebElement changeUserFreeTextBox(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='userCode']"));
return element;
}
public static IWebElement changeTheUserButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='menu']/div/ul/li[3]/form/div/ul/li/label/span[1]"));
return element;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.QCPages
{
class GetMylicencesPage
{
public static IWebElement element = null;
/**
* Returns the search box element
* @param driver
* @return
*/
public static string getTextForHeader(IWebDriver driver)
{
string actualValue4 = driver.FindElement(By.XPath(".//*[@id='main']/div[1]/h2")).Text;
return actualValue4;
}
public static IWebElement blankTemplate(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div[2]/ul/li[1]/a"));
return element;
}
/**
* Returns the customer element
* @param driver
* @return
*/
public static IWebElement customerSelect(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='reducing']/ul/li/a"));
return element;
}
}
}
<file_sep>using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selenium.UnitTestProject
{
class ManagerApprovalPage
{
public static IWebElement element = null;
public static string getTextForHeader(IWebDriver driver)
{
string actualvalue = driver.FindElement(By.XPath("//*[@id='main']/div[1]/h2")).Text;
return actualvalue;
}
/**
*
* selects the first manager name tickbox
*
*/
public static void clickOnManagerNameTickbox(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='approval']/div[2]/div[1]/div[2]/ul/li[2]/span[1]/span[1]/i"));
element.Click();
}
/**
*
* selects the send to manager button
*
*/
public static void clickOnSendToManagerButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='Save_Submit_To_Manager_link']/span[1]"));
element.Click();
}
/* public static IWebElement getBAPSSection(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='how_to_send']/label[3]"));
return element;
}
public static IWebElement getBAPSButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='how_to_send']/label[3]/div[2]/span"));
return element;
}
public static string getTextForSubHeading(IWebDriver driver)
{
string actualvalue = driver.FindElement(By.XPath(".//*[@id='main']/div[5]/div[1]/h2")).Text;
return actualvalue;
}
public static IWebElement selectQuoteA(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='main']/div[5]/div[2]/div/div/label"));
return element;
}
public static IWebElement selectCreateButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='btn_CustomerApproval_SendBAPS']/span[1]"));
return element;
}
*/
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.QCPages
{
class GetMyCustomerContactsPage
{
public static IWebElement element = null;
/**
* Returns the search box element
* @param driver
* @return
*/
public static string getTextForHeader(IWebDriver driver)
{
string actualValue3 = driver.FindElement(By.XPath(".//*[@id='main']/div[1]/h2")).Text;
return actualValue3;
}
public static IWebElement contactsSearchBox(IWebDriver driver)
{
element = driver.FindElement(By.Id("selected"));
return element;
}
/**
* Returns the delegate button
* @param driver
* @return
*/
public static IWebElement delegateButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='main']/div[1]/div/label[2]"));
return element;
}
/**
* Returns the customer element
* @param driver
* @return
*/
public static IWebElement contactSelect(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//a[@href='/Home/GetMyLicences?ContactId=5241159&ContactName=Beth%20Marshall&ContactEmail=bethmarshall2013%40hotmail.co.uk']"));
return element;
}
}
}
<file_sep>using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selenium.UnitTestProject
{
class GetMyCustomersPage
{
public static IWebElement element = null;
/**
* Returns the search box element
* @param driver
* @return
*/
public static IWebElement customerSearchBox(IWebDriver driver)
{
element = driver.FindElement(By.Id("selected"));
return element;
}
public static string getTextForHeader(IWebDriver driver)
{
string actualValue2 = driver.FindElement(By.XPath(".//*[@id='main']/div[2]/h2")).Text;
return actualValue2;
}
/**
* TO DO - ADD IN A CHECK YOU ARE ON THE RIGHT PAGE LIKE WITH THE END ASSERT IN SMOKE TEST
*/
public static IWebElement customerSelect(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//a[@href='/Home/GetMyCustomerContacts?CustomerId=3402211&CustomerName=TEST QC CUSTOMER&customerAddress=Test building, Town, DY12 3AY']"));
return element;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using Selenium.UnitTestProject.QCPages;
using Selenium.UnitTestProject.EnvironmentConfig;
namespace Selenium.UnitTestProject
{
//add these bits in to make all tests run at same time
[TestFixture]
[Parallelizable]
class ChangeUserToAStandardUser
{
//IWebDriver driver;
[SetUp]
public void Initialize()
{
//Managed from WebDriverManager.App.config
}
[Test]
//This tests uses the app.config value to pick a salesperson and change SP to use that salesperson to login
public void ChangeUserToAStandardUserTest()
{
using (IWebDriver driver = WebDriverManager.WebDriverManager.GetWebDriverForConfig())
{
string page = EnvironmentConfig.ConfigurationWrapper.GetURLFromEnvironmentKey();
string actualValue = DashboardPage.getTextForHeader(driver);
while (actualValue == null)
{
driver.Url = page;
}
Assert.IsTrue(actualValue.Contains("SKILLS LICENCES"), actualValue + " doesn't contain 'SKILLS LICENCES'");
DashboardPage.userCircle(driver).Click();
DashboardPage.changeUserFreeTextBox(driver).SendKeys(ConfigurationWrapper.SalspersonUserName());
DashboardPage.changeTheUserButton(driver).Click();
string actualValue1 = DashboardPage.getTextForHeader(driver);
Assert.IsTrue(actualValue1.Contains("SKILLS LICENCES"), actualValue + " doesn't contain 'SKILLS LICENCES'");
}
}
[TearDown]
public void EndTest()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using Selenium.UnitTestProject.QCPages;
using Selenium.UnitTestProject.EnvironmentConfig;
namespace Selenium.UnitTestProject
{
//add these bits in to make all tests run at same time
[TestFixture]
[Parallelizable]
class ChangeUserToAManager
{
//IWebDriver driver;
[SetUp]
public void Initialize()
{
//Managed from WebDriverManager.App.config
}
[Test]
//This tests uses the app.config value to pick a manager and change SP to use that salesperson to login. It then checks user has landed on a manager version of the dashboard page.
public void ChageUserToAManagerTest()
{
using (IWebDriver driver = WebDriverManager.WebDriverManager.GetWebDriverForConfig())
{
string page = EnvironmentConfig.ConfigurationWrapper.GetURLFromEnvironmentKey();
string actualValue = DashboardPage.getTextForHeader(driver);
while (actualValue == null)
{
driver.Url = page;
}
Assert.IsTrue(actualValue.Contains("SKILLS LICENCES"), actualValue + " doesn't contain 'SKILLS LICENCES'");
DashboardPage.userCircle(driver).Click();
DashboardPage.changeUserFreeTextBox(driver).SendKeys(ConfigurationWrapper.ManagerUserName());
DashboardPage.changeTheUserButton(driver).Click();
string ManagerDashboardHeader = DashboardPage.getTextForHeader(driver);
Assert.IsTrue(ManagerDashboardHeader.Contains("APPROVALS PENDING"), ManagerDashboardHeader + " doesn't contain 'APPROVALS PENDING'");
}
}
[TearDown]
public void EndTest()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Selenium.UnitTestProject.QCPages
{
class DashboardPage
{
public static IWebElement element = null;
/**
* Returns the search box element
* @param driver
* @return
*
*
*/
public static string getTextForHeader(IWebDriver driver)
{
string actualValue1 = driver.FindElement(By.XPath("//*[@id='dash']/div/div/h2")).Text;
return actualValue1;
}
public static void clickOnSideMenuArrow(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='menu']/span"));
element.Click();
}
public static IWebElement skillsLicenceHeader(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div/div/h2"));
return element;
}
public static IWebElement approvedCount(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div/table/tbody/tr[3]/td[2]"));
return element;
}
public static IWebElement draft(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div[1]/table/tbody[1]/tr[2]/td[1]/a/span"));
return element;
}
public static IWebElement approved(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div[1]/table/tbody[1]/tr[3]/td[1]/a/span"));
return element;
}
public static IWebElement approvedButSuspended(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div[1]/table/tbody[1]/tr[4]/td[1]/a/span"));
return element;
}
public static IWebElement declined(IWebDriver driver)
{
element = driver.FindElement(By.XPath(".//*[@id='dash']/div[1]/table/tbody[1]/tr[5]/td[1]/a/span"));
return element;
}
public static IWebElement awaitingApproval(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div[1]/table/tbody[2]/tr[2]/td[1]/a/span"));
return element;
}
public static IWebElement AllSkillsLicencesWithCustomers(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div[1]/table/tbody[2]/tr[4]/td[1]/a/span"));
return element;
}
/**
* Returns the create skills licence button
* @param driver
* @return
*/
public static IWebElement createSkillsLicenceButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='dash']/div/ul/li/a/span[1]"));
return element;
}
public static IWebElement userCircle(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='base']/ul/li[2]/span[1]/i"));
return element;
}
public static IWebElement changeUserFreeTextBox(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='userCode']"));
return element;
}
public static IWebElement changeTheUserButton(IWebDriver driver)
{
element = driver.FindElement(By.XPath("//*[@id='menu']/div/ul/li[3]/form/div/ul/li/label/span[1]"));
return element;
}
}
}
|
22577a15e50dc235bce293193aa44d9a3e7c7a76
|
[
"C#"
] | 17 |
C#
|
Iona777/AppConfigExampleProj
|
48d14a0f3014944d7d755ff7cf392647680a75b4
|
42290041f0076c9b53c0b9d871ad6276f189d48e
|
refs/heads/master
|
<repo_name>EarlyZhao/aggregateIncrWrite<file_sep>/metric.go
package aggregateIncrWrite
var emptyMetricer = &emptyMetric{}
type Metric interface {
MetricIncrCount(delta int64)
MetricBatchCount(delta int64)
}
type emptyMetric struct {
}
func (m *emptyMetric) MetricIncrCount(delta int64) {
}
func (m *emptyMetric) MetricBatchCount(delta int64) {
}
<file_sep>/store.redis.go
package aggregateIncrWrite
import (
"context"
"fmt"
"github.com/go-redis/redis"
"hash/crc32"
"strconv"
"sync"
"time"
)
/*
方案概述:
1. 核心数据结构:
- SkipList 按照首次写入时间(score), id为member 维护一个跳表。保存(触发回调)时优先取score小的。
- HashMap id为hash 的filed, value的累加通过 hincrby累计
2. 取数据
- zset zrem可以取一个id出来
- 在hash中删除这个field --- hdel
均是线程安全的。
3. 并发能力
通过saveConcurrency 扩展队列的数量(skiplist 和 hashmap的数量)
4. 风险
1. 数据安全。在 hdel 获取数据后,调用saveHandler失败,此时有丢数据的风险,可以通过实现failureHandler来尽量规避。
2. 热key风险。每个队列会写同样的key,此风险可以通过增加saveConcurrency来规避
5. 数据积压
redis是一个天然的暂存队列,当程序退出后,队列中暂存的数据,可以待下次启动再处理。
当队列数量增加或扩展时,需要注意老队列被遗忘的情况。(可能老队列还有数据)
*/
func NewRedisStore(notChangeBussinessId string, cache *redis.Client) AggregateStoreInterface{
return &storeRedis{cache: cache,
notChangeBussinessId: notChangeBussinessId,
wait: &sync.WaitGroup{},
stopChan: make(chan bool),
}
}
const _redisstorekey = "aIw"
type storeRedis struct {
*Config
notChangeBussinessId string
cache *redis.Client
skipListKeys []string
wait *sync.WaitGroup
batchAggChan chan aggItem
stopChan chan bool
}
func(a *storeRedis) incr(ctx context.Context, id string, val int64)( err error) {
item := &incrItem{id: id, delta: val}
zsetKey := a.dispatch(ctx, item)
incrKey := a.incrKey(item.id)
// 先 incr
if err = a.incrByKey(ctx, incrKey, item); err != nil {
return
}
// 再zadd
if err = a.recordInList(ctx, zsetKey, item.id);err != nil {
return
}
return
}
func (a *storeRedis) incrKey(id string) string {
return _redisstorekey + a.notChangeBussinessId + id
}
func (a *storeRedis) recordInList(ctx context.Context, key string, member string) (err error) {
err = a.cache.ZAddNX(key, redis.Z{Score:float64( time.Now().Unix()), Member: member}).Err()
return
}
func (a *storeRedis) incrByKey(ctx context.Context, key string, item *incrItem) (err error) {
err = a.cache.IncrBy(key, item.delta).Err()
a.cache.Expire(key, time.Hour * 12)
return
}
func (a *storeRedis) zrangebyScore(key string, score int64, limit int64) []string{
return a.cache.ZRangeByScore(key, redis.ZRangeBy{Min:"0", Max: fmt.Sprintf("%d", score),Count: limit}).Val()
}
func (a *storeRedis) zrem(key string, id string) int64{
return a.cache.ZRem(key, id).Val()
}
func (a *storeRedis) getset(key string, set int) int64{
ret := a.cache.GetSet(key, 0).Val()
intVal, _ := strconv.ParseInt(ret, 10, 0)
return intVal
}
func(a *storeRedis) stop(ctx context.Context) (err error) {
close(a.stopChan)
a.wait.Wait()
return
}
func(a *storeRedis) start(c *Config) {
a.Config = c
a.batchAggChan = make(chan aggItem, 100 *a.Config.getSaveConcurrency())
interval := int(a.Config.getInterval())
intervalPice := interval/a.Config.getConcurrency()
for i := 0; i < a.Config.getSaveConcurrency(); i++ {
zset := a.skipKey(i)
a.skipListKeys = append(a.skipListKeys, zset)
a.wait.Add(1)
delayInterval := interval
go func() {
time.Sleep(time.Duration(delayInterval))
a.aggregating(zset)
}()
interval -= intervalPice
}
// todo: 启动时应该有对应的任务清理旧数据。应对初始化参数中队列数量缩减的情况。
return
}
func (a *storeRedis) dispatch(ctx context.Context, item *incrItem) (zsetKey string){
sum := crc32.ChecksumIEEE([]byte(item.id))
index := sum % uint32(len(a.skipListKeys))
return a.skipListKeys[index]
}
func (a *storeRedis) batchAgg() chan aggItem{
return a.batchAggChan
}
func (a *storeRedis) skipKey(index int) string {
return fmt.Sprintf("%s:zset:%s:%v", _redisstorekey, a.notChangeBussinessId, index)
}
func (a *storeRedis) aggregating(zset string) {
defer a.wait.Done()
tiker := time.Tick(a.Config.getInterval())
for {
select{
case <- a.stopChan:
a.clear()
return
case <- tiker:
ids := a.zrangebyScore(zset, time.Now().Unix() - 1, 500)
aggs := make(aggItem)
for _, key := range ids{
if a.zrem(zset, key) > 0 {
if delta := a.getset(a.incrKey(key), 0); delta != 0 {
aggs[key] = delta
}
}
}
a.batchAggChan <- aggs
// todo add metric
}
}
}
func (a *storeRedis) clear() {
// todo: 此处需要记录下当前有哪些key,防治有数据忘记落在了 hashMapKeys里面
}<file_sep>/readme.md
# Aggregate increase Write
## 背景
数据库中有大量的增量写操作,常见于点赞类incr数值操作,SQL语句类似:
```SQL
update xxtable set xxcolums = xxcolumn + 1 where id = xxx ;
```
## 问题
此等写操作偶尔会很频繁,如果id分散,则写操作的压力,一方面异步化,另一方面可以分库解决。
但是当在类似点赞、增加积分等业务场景下,可能会集中给某个id执行incr操作。且在业务上来源可能分散,难以在
业务源头对incr类操作进行聚合。
此时上面的集中的incr操作,很容易因为写冲突出现性能瓶颈,且该压力难以分散。往往可能阻碍业务发展,且大量浪费数据库资源。
## 解决方案
由于incr操作的独特性,如果能有种方式将某个id的incr操作聚合起来,以一定时间窗口或数量做合并更新,则写冲突和性能压力都会引刃而解。
## 实现
本项目就是上面解决方案的实现。 暂时提供两种机制:
- 本地聚合式写聚合,基于本地内存
- 分布式写聚合,基于分布式存储
可以根据实际场景选择合适的方案。
## 使用
#### 本地聚合
```golang
// 程序启动: 初始化聚合对象
agg := New(
&Config{ConcurrencyBuffer: 10, SaveConcurrency: 10},
SetOptionStore(NewLocalStore()),
SetOptionSaveHandler(func(id string, aggIncr int64) error {
// 回调函数: 将聚合后的值写入数据库
return nil
}),
SetOptionFailHandler(func(id string, aggIncr int64) error {
// 失败回调函数
return nil
}))
// incr操作
agg.Incr(ctx, xxid, 2)
// 程序退出
agg.Stop(ctx)
```
#### redis聚合
```golang
// 程序启动: 初始化聚合对象
agg := New(
&Config{ConcurrencyBuffer: 10, SaveConcurrency: 100},
SetOptionStore(NewRedisStore("someIdNotChange", redis.NewClient(&redis.Options{Addr:"127.0.0.1:6379"}))),
SetOptionSaveHandler(func(id string, aggIncr int64) error {
// 回调函数
return nil
}),
SetOptionFailHandler(nil),
)
// incr操作
agg.Incr(ctx, xxid, 1)
// 程序退出
agg.Stop(ctx)
```<file_sep>/saveWorker.go
package aggregateIncrWrite
type incrItem struct {
id string
delta int64
}
type aggItem map[string]int64
func (a *Aggregate ) saveWorker() {
defer a.wait.Done()
for {
select {
case item, ok := <- a.store.batchAgg():
if ok {
a.saveBatch(item)
}
case <- a.stoped:
// 打扫战场
for {
select {
case item, ok := <- a.store.batchAgg():
if !ok{
return
}
a.saveBatch(item)
default:
return
}
}
}
}
}
func (a *Aggregate) saveBatch(batch aggItem) {
for id, delta := range batch{
if err := a.saveHandler(id, delta); err != nil && a.failureHandler != nil {
a.failureHandler(id, delta)
}
}
}<file_sep>/store.go
package aggregateIncrWrite
import(
"context"
)
type AggregateStoreInterface interface {
incr(ctx context.Context, id string, delta int64)( err error)
stop(ctx context.Context) (err error)
start(config *Config)
batchAgg() chan aggItem
}<file_sep>/store.local.go
package aggregateIncrWrite
import (
"context"
"errors"
"hash/crc32"
"sync"
"time"
)
const incrBufferFull = "buffer full"
func NewLocalStore() AggregateStoreInterface{
return &storeLocal{stopChan: make(chan bool), wait: &sync.WaitGroup{}}
}
type storeLocal struct {
*Config
buffers []chan *incrItem
stopChan chan bool
batchAggChan chan aggItem
stoped bool
wait *sync.WaitGroup
}
func(a *storeLocal) incr(ctx context.Context, id string, val int64)( err error) {
if a.stoped {
return errors.New("has closesed, incr failed")
}
item := &incrItem{id: id, delta: val}
buffer := a.dispatch(ctx, item)
select {
case <- ctx.Done():
return ctx.Err()
case buffer <- item:
return nil
default:
return errors.New(incrBufferFull)
}
}
func (a *storeLocal) dispatch(ctx context.Context, item *incrItem) chan *incrItem{
sum := crc32.ChecksumIEEE([]byte(item.id))
index := sum % uint32(len(a.buffers))
return a.buffers[index]
}
func(a *storeLocal) stop(ctx context.Context) (err error) {
a.stoped = true
close(a.stopChan)
a.wait.Wait()
return
}
func(a *storeLocal) start(c *Config){
a.Config = c
a.buffers = make([]chan *incrItem, a.Config.getConcurrency())
a.batchAggChan = make(chan aggItem, a.Config.getBufferNum() * 100)
interval := int(a.Config.getInterval())
intervalPice := interval/a.Config.getConcurrency()
for i := 0; i < a.Config.getConcurrency(); i ++ {
buffer := make(chan *incrItem, a.Config.getBufferNum())
a.buffers[i] = buffer
a.wait.Add(1)
delayInterval := interval
go func() {
time.Sleep(time.Duration(delayInterval)) // 均匀打散
a.aggregating(buffer)
}()
interval -= intervalPice
}
return
}
func (a *storeLocal) batchAgg() chan aggItem {
return a.batchAggChan
}
func (a *storeLocal) aggregating(buffer chan *incrItem) {
pool := make(aggItem)
// 让tick的启动时间分散
ticker := time.Tick(a.Config.getInterval())
defer a.wait.Done()
for {
select {
case <- a.stopChan:
a.stoped = true
for {
select {
case item := <- buffer:
pool[item.id] += item.delta
default:
a.batchAggChan <- pool
a.Config.getLogger().Info("aggregating exit")
return
}
}
case item, ok := <- buffer:
if !ok {
break
}
pool[item.id] += item.delta
a.Config.getMetric().MetricIncrCount(item.delta)
case <-ticker:
a.Config.getLogger().Info("lcoal run save")
a.batchAggChan <- pool
a.Config.getMetric().MetricBatchCount(int64(len(pool)))
pool = make(aggItem)
}
}
}
<file_sep>/aggregate.go
package aggregateIncrWrite
import (
"context"
"sync"
)
type Option func(a *Aggregate)
type Aggregate struct {
config *Config
store AggregateStoreInterface
// 聚合保存回调
saveHandler func(id string, aggIncr int64) error
// 回调错误时触发
failureHandler func(id string, aggIncr int64)
stoped chan bool
wait *sync.WaitGroup
}
func (c *Aggregate) SetLogger(logger Logger) {
c.config.logger = logger
}
func (c *Aggregate) SetMetric(m Metric) {
c.config.metric = m
}
func (a *Aggregate) Stop(ctx context.Context) error {
a.store.stop(ctx)
close(a.stoped)
a.wait.Wait()
return nil
}
func (a *Aggregate) Incr(ctx context.Context, id string, delta int64) (err error) {
err = a.store.incr(ctx, id, delta)
if err != nil {
// todo metric
err = a.saveHandler(id, delta)
}
return
}
func New(conf *Config, options ...Option) *Aggregate {
if conf == nil {
conf = emptyConf()
}
agg := &Aggregate{
store: NewLocalStore(), // default
config: conf,
stoped: make(chan bool),
wait: &sync.WaitGroup{},
}
for _, op := range options{
op(agg)
}
if agg.saveHandler == nil {
panic("saveHandler must exist, use SetOptionSaveHandler")
}
agg.store.start(agg.config)
for i := 0; i < agg.config.getSaveConcurrency(); i++ {
agg.wait.Add(1)
go agg.saveWorker()
}
return agg
}
func SetOptionStore(store AggregateStoreInterface) Option{
return func(a *Aggregate){
a.store = store
}
}
func SetOptionSaveHandler(save func(id string, aggIncr int64) error) Option{
return func(a *Aggregate){
a.saveHandler = save
}
}
func SetOptionFailHandler(fail func(id string, aggIncr int64)) Option{
return func(a *Aggregate){
a.failureHandler = fail
}
}
<file_sep>/agg_test.go
package aggregateIncrWrite
import (
"context"
"fmt"
"github.com/go-redis/redis"
. "github.com/smartystreets/goconvey/convey"
"math/rand"
"sync/atomic"
"testing"
"time"
)
func Test_NewAgg(t *testing.T) {
New(&Config{}, SetOptionStore(NewLocalStore()), SetOptionSaveHandler(func(id string, aggIncr int64) error {
return nil
}), SetOptionFailHandler(nil))
}
func Test_AggLocalIncr(t *testing.T) {
ctx := context.TODO()
Convey("test local incr", t, func() {
times := 300000
var total int64
agg := New(
&Config{ConcurrencyBuffer: 10, SaveConcurrency: 10},
SetOptionStore(NewLocalStore()),
SetOptionSaveHandler(func(id string, aggIncr int64) error {
time.Sleep(time.Millisecond)
fmt.Printf("local: id: %s, val: %d\n", id, aggIncr)
atomic.AddInt64(&total, aggIncr)
return nil
}),
SetOptionFailHandler(nil))
for i := 0; i < times; i ++ {
agg.Incr(ctx, fmt.Sprintf("%d", rand.Intn(times)), 1)
time.Sleep(5000*time.Nanosecond)
}
done := make(chan bool)
go func() {
for i := 0; i < times; i ++ {
agg.Incr(ctx, fmt.Sprintf("%d", rand.Intn(1000)), 1)
}
done <- true
for i := 0; i < times/100; i ++ {
agg.Incr(ctx, fmt.Sprintf("%d", rand.Intn(1000)), 1)
}
}()
<- done
agg.Stop(ctx)
So(total, ShouldEqual, times + times + times/100)
})
}
func Test_AggRedisIncr(t *testing.T) {
ctx := context.TODO()
Convey("test redis incr", t, func() {
times := 300000
var total int64
agg := New(
&Config{ConcurrencyBuffer: 10, SaveConcurrency: 100},
SetOptionStore(NewRedisStore("test", redis.NewClient(&redis.Options{Addr:"127.0.0.1:6379"}))),
SetOptionSaveHandler(func(id string, aggIncr int64) error {
fmt.Printf("redis: id: %s, val: %d\n", id, aggIncr)
time.Sleep(time.Millisecond)
atomic.AddInt64(&total, aggIncr)
return nil
}),
SetOptionFailHandler(nil))
for i := 0; i < times; i ++ {
agg.Incr(ctx, fmt.Sprintf("%d", rand.Intn(times)), 1)
//time.Sleep(55*time.Millisecond)
}
done := make(chan bool)
go func() {
for i := 0; i < times; i ++ {
if i % 50 == 0 {
go agg.Incr(ctx, fmt.Sprintf("%d", rand.Intn(1000)), 1)
continue
}
agg.Incr(ctx, fmt.Sprintf("%d", rand.Intn(1000)), 1)
}
done <- true
}()
<- done
time.Sleep(2*time.Second)
agg.Stop(ctx)
So(total, ShouldEqual, times + times)
})
}<file_sep>/config.go
package aggregateIncrWrite
import (
"time"
)
// 配置只能更新一次
type Config struct {
// 聚合时间窗口 窗口到期后触发写操作
Interval time.Duration
// 并发队列数量 独立channel
ConcurrencyBuffer int
// 单队列buffer大小
Buffer int
// 写操作并行度 执行save操作gourouting数量
SaveConcurrency int
IncrTimeout time.Duration
// 自定义日志
logger Logger
// 自定义埋点
metric Metric
}
func (c *Config) getInterval() time.Duration {
if c.Interval > 0 {
return c.Interval
}
return time.Second
}
func (c *Config) getConcurrency() int {
if c.ConcurrencyBuffer > 0 {
return c.ConcurrencyBuffer
}
return 1
}
func (c *Config) getBufferNum() int {
if c.Buffer > 0 {
return c.Buffer
}
return 2048
}
func (c *Config) getSaveConcurrency() int {
if c.SaveConcurrency > 0 {
return c.SaveConcurrency
}
return 1
}
func emptyConf() *Config{
return &Config{}
}
func (c *Config) getLogger() Logger {
if c.logger != nil {
return c.logger
}
return emptyLogger
}
func (c *Config) getMetric() Metric {
if c.metric != nil {
return c.metric
}
return emptyMetricer
}
<file_sep>/logger.go
package aggregateIncrWrite
import (
"context"
"fmt"
)
var emptyLogger = &emptyLog{}
type Logger interface {
Infoc(ctx context.Context, val string)
Info(val string)
Error(val string)
Errorc(ctx context.Context, val string)
}
type emptyLog struct {
}
func (l *emptyLog) Infoc(ctx context.Context, val string){
}
func (l *emptyLog) Info(val string){
fmt.Println(fmt.Sprintf("info: %s", val))
}
func (l *emptyLog) Error(val string){
fmt.Println(fmt.Sprintf("error: %s", val))
}
func (l *emptyLog) Errorc(ctx context.Context, val string){
}
|
88e5a9ca754eaabcf1d0de41b747e7ff5e5fe9fd
|
[
"Markdown",
"Go"
] | 10 |
Go
|
EarlyZhao/aggregateIncrWrite
|
b5689a596b152401cba51fb8b43d342e1bc201ab
|
da58b85ac220ecbb8869b2e243e71fada73c769d
|
refs/heads/master
|
<repo_name>afhuertass/aws-backuper<file_sep>/README.md
# A simple backup script for AWS buckets
<NAME> - Cloud AWS Fundamentals, University of Helsinki.
This simple scripts uploads the contents of a given folder to a AWS bucket. The script asumes the existence of the bucket( and proper configuration) and will raise an exception otherwise.
The scripts checks for files in a given directory and list them, afterwards begin to upload one by one the files into the bucket, creating new versions of the files if the versioning mode is activated
To work it needs boto3, and a credentials file with the following format:
aws_access_key_id
aws_secret_access_key
aws_session_token
Basically one token or key per line.
The script can be used with the following command:
python backuper.py -credfile=creditx.txt -folder=./data -bucket=aws-uh-bckup -time=1 -versioning=false
The arguments are as follows:
**-bucket**: the target bucket
**-credfile**: the File with the AWS credentials (str)
**-folder**: The folder to be updated to AWS ( str)
**-time**: the time in minutes between each update ( int)
**-versioning** : Use this option to activate Bucker versioning.
<file_sep>/backuper.py
import boto3
import time, threading
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-credfile" , help = "Credentials File " , type = str , required = True)
parser.add_argument( "-folder" , help ="local folder to upload" , type = str , required = True)
parser.add_argument( "-bucket" , help = "AWS bucket" , type = str , required = True)
parser.add_argument("-time" , help ="delta time in minutes for updates" , type = int , required = True)
parser.add_argument("-versioning" , help ="Enables versioning for the bucket" , type = bool )
#dfolder = "./data"
#bucket_name = "aws-uh-bckup"
WAIT_SECONDS = 60 # execute each 5 minutes
def upload_file( file_path , bucket = None ):
key = file_path.split("/")[-1]
print(" Uploading file:" , file_path )
bucket.upload_file( file_path, key )
print("Up!")
return
def list_files(path):
files = []
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
files.append( file )
return files
def backup(folder , bucket ):
files = list_files( folder )
print( files )
for file in files:
print(file)
upload_file( folder+"/"+file , bucket )
#threading.Timer( WAIT_SECONDS , backup(folder , bucket) ).start()
def enable_versioning( s3 , bucket_name ):
# Enable versioning for the bucket
bkt_versioning = s3.BucketVersioning(bucket_name)
bkt_versioning.enable()
print(bkt_versioning.status)
def parse_creds( cred ):
data = []
f = open(cred)
for line in f:
data.append( line.rstrip('\n') )
f.close()
tokens = dict()
tokens["access_key"] = data[0]
tokens["secret_key"] = data[1]
tokens["session_token"] =data[2]
return tokens
def s3_from_file( path_cred ):
tokens = parse_creds( path_cred )
print( tokens )
s3 = boto3.resource(
"s3" ,
aws_access_key_id = tokens["access_key"] ,
aws_secret_access_key = tokens["secret_key"] ,
aws_session_token = tokens["session_token"]
)
return s3
if __name__ == "__main__":
args = parser.parse_args()
varsdict = vars( args )
#print( vars(args) )
s3 = s3_from_file( varsdict["credfile"])
bucket = s3.Bucket( varsdict["bucket"] )
seconds = varsdict["time"]*WAIT_SECONDS
ticker = threading.Event()
if varsdict["versioning"]:
enable_versioning(s3 , varsdict["bucket"] )
while not ticker.wait( seconds ):
print(" Running backup on bucket {}".format( varsdict["bucket"]) )
backup( varsdict["folder"] , bucket )
|
ed1c51ea3fec29a42b7f2132757fd1f466912ab9
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
afhuertass/aws-backuper
|
befdf2abd78f4dac3ee3b4611388130251493581
|
e8163d6dcd1261d519e87f069043c97656dc11cb
|
refs/heads/master
|
<file_sep>package com.nextapps.appangintegrationane;
import java.util.HashMap;
import java.util.Map;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
public class AppangIntegrationANEContext extends FREContext {
@Override
public void dispose() {
// TODO Auto-generated method stub
}
@Override
public Map<String, FREFunction> getFunctions() {
// TODO Auto-generated method stub
Map<String, FREFunction> map = new HashMap<String, FREFunction>();
map.put("run", new Run());
return map;
}
}
<file_sep>appang-integration-ane
======================
앱팡 연동을 위한 Adobe Air용 ANE
* build
1) make .jar in ‘android’ project using eclipse or ADT.
2) ant build using as/build.xml
3) using ANE! that is as/bin/AppangIntegrationANE.ane
* add parts
- manifest in air project
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application>
…
<activity android:name="com.nextapps.appangintegrationane.MainActivity"></activity>
…
…
<extensionID>com.nextapps.appangintegrationane</extensionID>
</extensions>
</application>
* call integrations
var ai:AppangIntegrationANE = new AppangIntegrationANE();
var key:String = avtertiseKey(get in appang)
ai.run(key);<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project name="Build ANE" default="all">
<target name="all" >
<property name="SDK_PATH" value="/Applications/Adobe Flash Builder 4.7/sdks/ApacheFlexSDK"></property>
<property name="ADT" value="${SDK_PATH}/lib/adt.jar"></property>
<copy file="bin/AppangIntegrationANE.jar" todir="bin/android" overwrite="true"/>
<unzip src="bin/AppangIntegrationANE.jar" dest="bin/temp"></unzip>
<copydir src="bin/libNASRun" dest="bin/temp"/>
<jar destfile="bin/AppangIntegrationANE.jar" basedir="bin/temp" />
<unzip src="bin/AppangIntegrationANE.swc" dest="bin"></unzip>
<java jar="${ADT}" dir="bin" fork="true" output="build.log">
<arg value="-package"></arg>
<arg value="-target"></arg>
<arg value="ane"></arg>
<arg value="AppangIntegrationANE.ane"></arg>
<arg value="extension.xml"></arg>
<arg line="-swc AppangIntegrationANE.swc"/>
<arg line="-platform Android-ARM library.swf AppangIntegrationANE.jar"/>
</java>
</target>
</project>
|
8447c52b9699746c6522bb4fd0a95f36463d5a29
|
[
"Java",
"Text",
"Ant Build System"
] | 3 |
Java
|
fredriccliver/appang-integration-ane
|
ac8050bbdce53cd828399b9b6876592519366c4a
|
d8b4df9091107b9c0282b52b4a25855afed8475b
|
refs/heads/master
|
<repo_name>VivoKey/vivocoin<file_sep>/coinweb/views.py
import random
import json
import secrets
import urllib.request
from django.shortcuts import render, redirect
from django.contrib.auth import logout as django_logout
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.core.signing import Signer
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .models import Account, Payment
INITIAL_BALANCE = 10000
class ValidationFailed(Exception):
pass
def _start_vivokey_validation_fromserver(request, message, our_id):
"""
We do this while the user waits for the page to load -- a proper implementation
would do this via AJAX so the user can see some feedback (or use a worker
thread and redirects)
Returns the transaction ID or raises ValidationFailed.
"""
token = request.session['oidc_access_token']
print('oidc_access_token:', token)
json_data = json.dumps({
'message': message,
'timeout': 30,
'id': our_id,
'callback': settings.VALIDATION_CALLBACK,
}).encode('utf-8')
request = urllib.request.Request(
settings.VIVO_VALIDATE,
data=json_data,
headers={
'Authorization': 'Bearer %s' % (token,),
'Content-Type': 'application/json',
}
)
response = json.loads(urllib.request.urlopen(request).read())
if not response.get('accepted', False):
raise ValidationFailed(response.get('message', 'No message supplied'))
return response['vivo_id']
def _get_signed_payment_token(payment):
to_sign = '%d:%s' % (payment.id, payment.nonce)
return Signer().sign(to_sign)
def _get_payment_from_signed_token(signed_token):
unsigned = Signer().unsign(signed_token)
payment_id, nonce = unsigned.split(':', 1)
return Payment.objects.get(pk=payment_id, nonce=nonce)
def index(request):
# Create the user account if it doesn't exist.
message = None
wait_for_payment = None
if request.user.is_authenticated:
try:
account = Account.objects.get(django_user=request.user)
except Account.DoesNotExist:
account = Account.objects.create(django_user=request.user, balance=INITIAL_BALANCE)
# Do actions
if request.POST.get('action') == 'more_money_pls':
account.balance += random.randint(0, 100) * 100
account.save()
elif request.POST.get('action') == 'spend_money':
spend_amount_cents = int(request.POST.get('cents'))
message = 'Pay $%.02f to VivoCoin' % (spend_amount_cents // 100,)
payment = Payment.objects.create(nonce=secrets.token_hex(8),
status='auth',
from_account=account,
amount_cents=spend_amount_cents)
try:
signed_id = _get_signed_payment_token(payment)
_start_vivokey_validation_fromserver(request, message, signed_id)
except ValidationFailed as e:
payment.status = 'failed'
payment.save()
message = 'Validation not accepted: %s' % (str(e),)
else:
message = 'Validation started for transaction ID %d' % (payment.id,)
wait_for_payment = payment.id
balance_dollars = account.balance // 100
else:
account = None
balance_dollars = 0
context = {
'account': Account,
'balance_dollars': balance_dollars,
'debt': balance_dollars < 0,
'message': message,
'wait_for_payment': wait_for_payment
}
return render(request, 'coinweb/index.html', context)
def _oidc_userinfo(request):
"""
Make the /userinfo call to VivoKey.
mozilla_django_oidc has already made this API call as as part of logging
in, but unfortunately didn't store the result, so just ask again.
"""
token = request.session['oidc_access_token']
print('oidc_access_token:', token)
json_data = json.dumps({
'timeout': 30,
}).encode('utf-8')
request = urllib.request.Request(
settings.OIDC_OP_USER_ENDPOINT,
data=json_data,
headers={
'Authorization': 'Bearer %s' % (token,),
'Content-Type': 'application/json',
}
)
response = urllib.request.urlopen(request).read().decode('utf-8')
return response
@login_required
@require_POST
def userinfo(request):
"""
Return some information about the logged-in user.
This is extra info to help you while working with VivoKey OIDC and isn't
required to implement any core functionality.
"""
context = {
'oidc_access_token': request.session.get('oidc_access_token', ''), # for debugging
'oidc_userinfo': _oidc_userinfo(request)
}
return render(request,'coinweb/userinfo.html', context)
def validation_complete(request):
# Callback from VivoKey.
# Note that we have to ensure that the callback has not been forged. We do
# that by validating (cryptographically, using the Signer module) that the
# payment ID we've received is the one we originally sent.
json_response = json.loads(request.body)
payment = _get_payment_from_signed_token(json_response.get('id', ''))
success = json_response.get('success', False)
if success:
payment.from_account.balance -= payment.amount_cents
payment.from_account.save()
payment.status = 'completed' if success else 'failed'
payment.save()
return JsonResponse({})
def auth_status(_request, payment_id):
payment = Payment.objects.get(id=payment_id)
return JsonResponse({'status': payment.status})
def logout(request):
django_logout(request)
return redirect(index)
<file_sep>/coinweb/urls.py
from django.urls import path, re_path
from django.views.decorators.csrf import csrf_exempt
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('userinfo/', views.userinfo, name='userinfo'),
re_path('auth_status/([0-9]+)/', views.auth_status, name='auth_status'),
path('validation_complete/', csrf_exempt(views.validation_complete), name='validation_complete'),
path('logout/', views.logout, name='logout'),
]
<file_sep>/vivocoin/info_pack.py
import os
import zipfile
import json
def find_filename(filename, info_list):
for info in info_list:
basename = os.path.basename(info.filename)
if basename == filename:
return info.filename
return None
def read_auth_requestor_info(info_pack_filename):
with zipfile.ZipFile(info_pack_filename, 'r') as thezip:
info_list = thezip.infolist()
auth_requestor_filename = find_filename('auth_requestor.json', info_list)
if auth_requestor_filename:
with thezip.open(auth_requestor_filename, 'r') as handle:
return json.loads(handle.read())
return None
<file_sep>/requirements.txt
asn1crypto==0.24.0
certifi==2018.8.24
cffi==1.14.0
chardet==3.0.4
cryptography==2.3.1
Django==2.2.4
idna==2.7
josepy==1.1.0
mozilla-django-oidc==1.1.2
pycparser==2.18
pycrypto==2.6.1
pyjwkest==0.6.2
pyOpenSSL==18.0.0
pytz==2018.5
requests==2.19.1
six==1.11.0
South==1.0.2
sqlparse==0.3.0
urllib3==1.23
<file_sep>/coinweb/templates/coinweb/userinfo.html
{% extends "coinweb/base.html" %}
{% load static %}
{% block title %}VivoCoin user info{% endblock %}
{% block content %}
<div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">
<h1 class="display-4">User Info</h1>
<p>OIDC access token: {{oidc_access_token}}</p>
<p>OIDC userinfo endpoint response: <tt>{{oidc_userinfo}}</tt></p>
<p><a href="{% url 'index' %}">Go back</a></p>
</div>
{% endblock %}
<file_sep>/coinweb/migrations/0002_payment.py
# Generated by Django 2.1.1 on 2018-09-01 19:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coinweb', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Payment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.TextField(choices=[('auth', 'Waiting for authorisation'), ('failed', 'Failed'), ('completed', 'Completed')])),
('amount_cents', models.IntegerField()),
('from_account', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='coinweb.Account')),
],
),
]
<file_sep>/docker/Dockerfile
# Build Python extensions requiring gcc and dev libraries
FROM python:3.7-alpine3.8 as build
RUN apk add libc-dev gcc postgresql-dev libffi-dev linux-headers
COPY requirements.txt /tmp
RUN pip install virtualenv
RUN virtualenv /virtualenv
RUN /virtualenv/bin/pip install -r /tmp/requirements.txt
# Copy the built virtualenv across to the final container
FROM python:3.7-alpine3.8
RUN apk add postgresql-client openssl stunnel
COPY --from=build /virtualenv/ /virtualenv
<file_sep>/README.md
About
=====
VivoCoin is a demo app for third-party integration with VivoKey. It demonstrates two different uses of the VivoKey API: logging in with VivoKey (using OpenID Connect), and requesting an authorisation with VivoKey.
Installation
============
VivoCoin is written in Python. Installation using a virtualenv is highly recommended:
$ virtualenv vivocoin-virtualenv
$ source vivicoin-virtualenv/bin/activate
Once in the virtualenv, you can install the requirements using pip:
pip install -r requirements.txt
Configuration
=============
Before you start, you will need a custom application set up on the VivoKey server. Specifically, you will need your OpenID client ID and client secret. If you don't have these, contact your friendly VivoKey representative.
Set the following environment variables:
* `VIVO_SERVER`: `https://api.vivokey.com/`
* `VALIDATION_CALLBACK`: `http://your-server-location/validation_complete/`
* `OIDC_RP_CLIENT_ID`: Your OpenID Connect client ID
* `OIDC_RP_CLIENT_SECRET`: Your OpenID Connect client secret
Here is an example configuration:
export VIVO_SERVER="https://api.vivokey.com/"
export VALIDATION_CALLBACK="http://192.168.0.2:8000/validation_complete/"
export OIDC_RP_CLIENT_ID="29485022"
export OIDC_RP_CLIENT_SECRET="<KEY>"
Configuration from an info pack
===============================
If you have a VivoKey info pack, you can omit `VALIDATION_CALLBACK`, `OIDC_RP_CLIENT_ID`, and `OIDC_RP_CLIENT_SECRET`, and instead supply the path to the info pack using the environment variable `OIDC_INFO_PACK`.
Running the server (development)
================================
VivoCoin is a Django application. You can therefore run a test server using manage.py, like this:
python3 manage.py runserver 0.0.0.0:8000
Running the server (production)
===============================
VivoCoin is an API demo and is not intended to be run in production. However, if you do wish to expose VivoCoin to the Internet, make the following changes to `vivocoin/settings.py` before doing so:
* Change `DEBUG = True` to `DEBUG = False`.
* Change `SECRET_KEY`.
* Restrict `ALLOWED_HOSTS` to the name of the server that VivoCoin is running on (e.g. if your server is at https://vivocoin.mycompany.com/, set `ALLOWED_HOSTS` to `['vivocoin.mycompany.com']`.
If running in production, you should run VivoCoin behind a real web server (such as nginx or Apache), using WSGI or similar.
<file_sep>/coinweb/apps.py
from django.apps import AppConfig
class CoinwebConfig(AppConfig):
name = 'coinweb'
<file_sep>/coinweb/models.py
from django.db import models
from django.contrib.auth.models import User
PAYMENT_STATUSES = [
('auth', 'Waiting for authorisation'),
('failed', 'Failed'),
('completed', 'Completed')
]
class Account(models.Model):
django_user = models.OneToOneField(User, on_delete=models.CASCADE)
balance = models.IntegerField(default=0) # account balance in cents
class Payment(models.Model):
nonce = models.TextField(null=True)
status = models.TextField(choices=PAYMENT_STATUSES)
from_account = models.ForeignKey(Account, null=True, on_delete=models.SET_NULL)
# Normally we'd have to_account (and time of initiation, completion, etc),
# but for this demo we don't need it.
amount_cents = models.IntegerField()
|
a121b41a74dd7cf2ddee8ba42a9979c873fc1542
|
[
"HTML",
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 10 |
Python
|
VivoKey/vivocoin
|
87ff329d46b13998265cc97952d6f50e73efb1a1
|
86e1b3f52b32c2a5f8243502b857d3249a2c3bc3
|
refs/heads/master
|
<repo_name>baevdantesdev/jsdelivr<file_sep>/src/api.ts
import axios from 'axios'
import { PackageList } from '@/interfaces'
export default class Api {
static getPackages (text: string) {
return axios.get<PackageList>('/-/v1/search', {
params: {
text,
size: 100
}
})
}
}
<file_sep>/src/store/index.ts
import Vue from 'vue'
import Vuex from 'vuex'
import Api from '@/api'
import { AppState, PackageList } from '@/interfaces'
Vue.use(Vuex)
const state: AppState = {
packages: null
}
export default new Vuex.Store({
state,
mutations: {
setPackages: (state, payload: PackageList) => {
state.packages = payload
}
},
actions: {
getPackages: ({ commit }, text: string) => {
return Api.getPackages(text).then((res) => {
commit('setPackages', res.data)
return res.data
})
}
}
})
<file_sep>/src/interfaces.ts
export interface AppState {
packages: PackageList | null;
}
export interface PackageList {
objects: Package[];
total: number;
time: Date;
}
export interface Package {
'package': {
'name': string;
'version': string;
'description': string;
'keywords': string[];
'date': Date;
'links': {
'npm': string;
'homepage': string;
'repository': string;
'bugs': string;
};
'publisher': {
'username': string;
'email': string;
};
author: {
name: string;
url: string;
};
'maintainers': Maintainer[];
};
'score': {
'final': number;
'detail': {
'quality': number;
'popularity': number;
'maintenance': number;
};
};
'searchScore': number;
}
export interface Maintainer {
'username': string;
'email': string;
}
export interface PackageTableRow {
name: string;
author: string;
publisher: string;
version: string;
}
<file_sep>/src/main.ts
import Vue from 'vue'
import App from './app.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import VueAxios from 'vue-axios'
import axios from 'axios'
import { AxiosConfig } from '@/axios.config'
import { BootstrapVue } from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.config.productionTip = false
Vue.use(VueAxios, axios)
Object.assign(Vue.axios.defaults, AxiosConfig)
Vue.use(BootstrapVue)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
|
8edd1f02641d199caec5b7857f890b382fed123d
|
[
"TypeScript"
] | 4 |
TypeScript
|
baevdantesdev/jsdelivr
|
c5cf16fc2b2e513e14f74b2c545b0c36d9af223e
|
3d45130533d7a0e671f75412b1064e820da9cfa9
|
refs/heads/main
|
<repo_name>michaelastefkova/arch-studio<file_sep>/src/components/MapSkin.js
export const mapSkin = [
{
"featureType": "all",
"elementType": "labels",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "all",
"elementType": "labels.text",
"stylers": [
{
"color": "#444444"
}
]
},
{
"featureType": "administrative.country",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.country",
"elementType": "geometry",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "administrative.province",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative.locality",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
},
{
"saturation": "-100"
},
{
"lightness": "30"
}
]
},
{
"featureType": "administrative.neighborhood",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative.land_parcel",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
},
{
"gamma": "0.00"
},
{
"lightness": "74"
}
]
},
{
"featureType": "landscape",
"elementType": "geometry",
"stylers": [
{
"color": "#ffffff"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"visibility": "off"
},
{
"color": "#353535"
},
{
"saturation": "-15"
},
{
"lightness": "40"
},
{
"gamma": "1.25"
}
]
},
{
"featureType": "road",
"elementType": "labels",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry",
"stylers": [
{
"visibility": "simplified"
},
{
"color": "#eeeff4"
},
{
"weight": "2"
},
{
"saturation": "0"
},
{
"lightness": "0"
}
]
},
{
"featureType": "transit",
"elementType": "labels",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "transit",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit.line",
"elementType": "geometry",
"stylers": [
{
"color": "#ff0000"
},
{
"lightness": "80"
}
]
},
{
"featureType": "transit.station",
"elementType": "geometry",
"stylers": [
{
"color": "#e5e5e5"
}
]
},
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "#eeeff4"
}
]
},
{
"featureType": "water",
"elementType": "labels",
"stylers": [
{
"visibility": "off"
}
]
}
];
<file_sep>/cypress/integration/spec.js
describe('Sapper template app', () => {
beforeEach(() => {
cy.visit ('/')
});
it('has the correct <h1>, () => {
cy.contains ('h1', 'Great success!')
});
it navigates to about
cy.get nav a.contains about.click
cy.url. should 'include', '/about');
it('navigates to /blog', () => {
cy.get('nav a').contains('blog').click();
cy.url().should('include', '/blog');
});
});
|
a5afc06daecaba3f30cf495910f284f577c6200c
|
[
"JavaScript"
] | 2 |
JavaScript
|
michaelastefkova/arch-studio
|
af27a617021ec26ad533826bf861b88a3a12e4ba
|
80cc396d264b438c426d412d0f093baee52e53ac
|
refs/heads/master
|
<file_sep>from tkinter import *
root = Tk()
root.title("Scrollbar Widget")
list = ["Shirt","Bag","Toy","Books","Fruits",
"Vegetables","Jeans","Headphones",
"Watch","Dress","Snaks","Dry fruits"]
def add():
w = Lb.get(ACTIVE)
cart.insert(END,w)
Scr.set(100,400)
print("Item {} Added to Your Cart".format(w))
Lb = Listbox(root)
Lb.pack(side=LEFT, expand=1,fill=X)
cart = Listbox(root)
cart.pack(side=RIGHT, expand=1,fill=X)
Scr = Scrollbar(root,troughcolor='red',jump=1)
Scr.pack(side=LEFT,fill=Y)
Btn= Button(root,text="ADD TO CART ->",fg='white',bg='green',command=add).pack(side=RIGHT)
for i in list:
Lb.insert(END ,i)
Lb.config(yscrollcommand=Scr.set)
Scr.config(command=Lb.yview)
mainloop()
|
1dd43e1b14f8a68faf7c2a7bbf26dd2eb0560d20
|
[
"Python"
] | 1 |
Python
|
python2238/Tkinter-Scrollbar
|
3d87a5b6192c492f262c1a62ca3f730704528497
|
7fb2a58568cfe20d6b95b0c456bfeb225bc09ac4
|
refs/heads/master
|
<repo_name>pako10/pizzamania2<file_sep>/pizzamania2/quesoController.swift
//
// quesoController.swift
// pizzamania2
//
// Created by <NAME> on 15/11/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class quesoController: UIViewController {
@IBOutlet weak var parmesano: UISwitch!
@IBOutlet weak var mozarella: UISwitch!
@IBOutlet weak var cheddar: UISwitch!
@IBOutlet weak var sinQueso: UISwitch!
var masa=[""]
var size=[""]
var queso=[String]()
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let sigVista = segue.destinationViewController as! ingredientesController
sigVista.masa = self.masa
sigVista.size=self.size
sigVista.queso=self.queso
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func next(sender: AnyObject) {
selecQueso()
}
func selecQueso(){
if parmesano.on{
queso.append("Parmesano")
}
if mozarella.on{
queso.append("Mozarella")
}
if cheddar.on{
queso.append("Cheddar")
}
if sinQueso.on{
queso.append("Sin Queso")
}
if (queso.isEmpty)
{
let alert = UIAlertController(title: "Error", message: "Selecciona un queso", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/pizzamania2/ingredientesController.swift
//
// ingredientesController.swift
// pizzamania2
//
// Created by <NAME> on 15/11/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class ingredientesController: UIViewController {
var masa=[""]
var size=[""]
var queso=[""]
var ingredientes=[String]()
@IBOutlet weak var anchoas: UISwitch!
@IBOutlet weak var piña: UISwitch!
@IBOutlet weak var pimiento: UISwitch!
@IBOutlet weak var cebolla: UISwitch!
@IBOutlet weak var aceitunas: UISwitch!
@IBOutlet weak var salchicha: UISwitch!
@IBOutlet weak var pavo: UISwitch!
@IBOutlet weak var peperoni: UISwitch!
@IBOutlet weak var jamon: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let sigVista = segue.destinationViewController as! confirmacionController
sigVista.masa = self.masa
sigVista.size=self.size
sigVista.queso=self.queso
sigVista.ingredientes=self.ingredientes
}
@IBAction func next(sender: AnyObject) {
selecIngredientes()
}
func selecIngredientes(){
if jamon.on{
ingredientes.append("jamon")
}
if peperoni.on{
ingredientes.append("peperoni")
}
if pavo.on{
ingredientes.append("pavo")
}
if salchicha.on{
ingredientes.append("salchicha")
}
if aceitunas.on{
ingredientes.append("aceitunas")
}
if pimiento.on{
ingredientes.append("pimiento")
}
if cebolla.on{
ingredientes.append("cebolla")
}
if piña.on{
ingredientes.append("piña")
}
if anchoas.on{
ingredientes.append("anchoas")
}
if (ingredientes.isEmpty)
{
let alert = UIAlertController(title: "Error", message: "Selecciona al menos 1 ingrediente", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/pizzamania2/confirmacionController.swift
//
// confirmacionController.swift
// pizzamania2
//
// Created by <NAME> on 15/11/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class confirmacionController: UIViewController {
var masa=[""]
var size=[""]
var queso=[""]
var ingredientes=[""]
@IBOutlet weak var cheese: UILabel!
@IBOutlet weak var ingredient: UILabel!
@IBOutlet weak var mas: UILabel!
@IBOutlet weak var tamaño: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var x:CGFloat = 40
let y:CGFloat = 450
for i in ingredientes
{
let label = UILabel(frame: CGRectMake(0, 0, 100, 21))
label.center = CGPointMake(x, y)
label.textAlignment = NSTextAlignment.Center
label.text = "\(i)"
self.view.addSubview(label)
x += 70
}
for i in queso
{
let label = UILabel(frame: CGRectMake(0, 0, 100, 21))
label.center = CGPointMake(x, y)
label.textAlignment = NSTextAlignment.Center
label.text = "\(i)"
self.view.addSubview(label)
x += 70
}
for i in size
{
let label = UILabel(frame: CGRectMake(0, 0, 100, 21))
label.center = CGPointMake(x, y)
label.textAlignment = NSTextAlignment.Center
label.text = "\(i)"
self.view.addSubview(label)
x += 70
}
for i in masa
{
let label = UILabel(frame: CGRectMake(0, 0, 100, 21))
label.center = CGPointMake(x, y)
label.textAlignment = NSTextAlignment.Center
label.text = "\(i)"
self.view.addSubview(label)
x += 70
}
// Do any additional setup after loading the view.
}
@IBAction func confirmacion(sender: AnyObject) {
let alert = UIAlertController(title: "Pedido", message: "Esta Correcto tu Pedido?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/pizzamania2/sizeController.swift
//
// sizeController.swift
// pizzamania2
//
// Created by <NAME> on 15/11/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class sizeController: UIViewController {
var size = [String]()
@IBOutlet weak var mediana: UISwitch!
@IBOutlet weak var chica: UISwitch!
@IBOutlet weak var grande: UISwitch!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let sigVista = segue.destinationViewController as! masaController
sigVista.size = self.size
}
@IBAction func enviarDatos(sender: AnyObject) {
selecSize()
}
func selecSize(){
if chica.on{
size.append("Chica")
}
if mediana.on{
size.append("Mediana")
}
if grande.on{
size.append("Grande")
}
if (size.isEmpty)
{
let alert = UIAlertController(title: "Error", message: "Selecciona el tamaño", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier == "segueIngToPedido"
{
if (size.isEmpty)
{
let alert = UIAlertController(title: "Error", message: "Selecciona el tamaño", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
return false
}
else
{
return true
}
}
return true
}
}
|
4bd915b1cce1bb0887ba79aa9c0ab74804051ca7
|
[
"Swift"
] | 4 |
Swift
|
pako10/pizzamania2
|
62272cdec3998a3f81f8666801765b596e63f4d8
|
c2446a77e110c34046d12afbca7ee06155065c9a
|
refs/heads/master
|
<repo_name>filipemsl/lima-site<file_sep>/README.md
# lima
Initial release of my own website, to be used as a portfolio.
<file_sep>/js/script.js
// Look for .hamburger
var hamburger = document.querySelector(".hamburger");
// On click
hamburger.addEventListener("click", function() {
// Toggle class "is-active"
hamburger.classList.toggle("is-active");
// Do something else, like open/close menu
});
const Modaleaster = {
open() {
// Abrir modal
// Adicionar a class active ao modal
document.querySelector('.modal-easter-overlay').classList.add('active')
}, close() {
// Fechar o modal
// Remover a classe active do modal
document.querySelector('.modal-easter-overlay').classList.remove('active')
}
}
function scrollToContato () {
document.getElementById('contato').scrollIntoView({
behavior: 'smooth'
});
}
function scrollToContatoAlt () {
window.location.href = "index.html";
document.getElementById('contato').scrollIntoView({
behavior: 'smooth'
});
}
function seguirPortfolio (){
window.location.href = "https://bit.ly/3mKwk9h"
}
var openPhotoSwipe = function() {
var pswpElement = document.querySelectorAll('.pswp')[0];
// build items array
var items = [
{
src: '../images/Artesa.jpg',
w: 5000,
h: 3500
},
{
src: '../images/DA.jpg',
w: 1092,
h: 764
},
{
src: '../images/Passarela.jpg',
w: 3507,
h: 2479
},
{
src: '../images/Acmed.jpg',
w: 3500,
h: 2520
},
{
src: '../images/Emporio.jpg',
w: 1920,
h: 1440
},
{
src: '../images/Maisa.jpg',
w: 1629,
h: 1141
},
{
src: '../images/Vtrine.jpg',
w: 3368,
h: 2358
},
{
src: '../images/Clay.jpg',
w: 4824,
h: 3376
},
{
src: '../images/Cecilia.jpg',
w: 3998,
h: 2297
},
{
src: '../images/Osiris.jpg',
w: 2000,
h: 1185
},
{
src: '../images/Arretado.jpg',
w: 2553,
h: 1418
}
];
// define options (if needed)
var options = {
// history & focus options are disabled on CodePen
history: false,
focus: false,
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
openPhotoSwipe();
document.getElementById('btn').onclick = openPhotoSwipe;
|
286db3314436075cc17597d0445d39bc7e7a7718
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
filipemsl/lima-site
|
d8f82917e9e1ca95d62aa19454a94d6a722e2ef4
|
3182beacbf2f95a21705f187f3de01c507b676ba
|
refs/heads/master
|
<repo_name>saif-mhr/TempData_asp.netCoreMvc<file_sep>/TempData/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TempData.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
string[] str = { "saifullah", "mahar", "Faqeer" };
TempData["var1"] =str;
TempData["var2"] = new List<string>()
{
"saif",
"mahar",
"faqeer",
};
return View();
}
public IActionResult about()
{
TempData.Keep();
return View();
}
public IActionResult Contact()
{
return View();
}
}
}
|
8a68c941337c61af122c479650ea8e77d616dbf8
|
[
"C#"
] | 1 |
C#
|
saif-mhr/TempData_asp.netCoreMvc
|
f960dacafe43875b51059adf606c9809062612a4
|
2afe754605f44e2ac35b67d6393a0ac897b55db9
|
refs/heads/master
|
<file_sep># quicksort
quicksort in Python
implements Hoare and Lomuto partition methods
<file_sep>def qsort(array):
_qsort(array, 0, len(array) - 1)
def _qsort(array, start, end):
if end - start < 1:
return
else:
pivot = partition_hoare(array, start, end)
_qsort(array, start, pivot - 1)
_qsort(array, pivot + 1, end)
def partition_lomuto(array, start, end):
pivot = start # pivot position to swap with pivot value; first value to the right
for i in range(start, end): # iterate from start to end - 1
if array[i] <= array[end]: # current value <= pivot value
array[i], array[pivot] = array[pivot], array[i] # swap current and value at pivot position
pivot += 1 # update pivot position
array[end], array[pivot] = array[pivot], array[end] # swap pivot value and value at pivot position
return pivot
def partition_hoare(array, start, end):
i, j = start, end - 1
while True:
while array[i] <= array[end] and i < j:
i += 1
while array[j] >= array[end] and i < j:
j -= 1
if i == j:
if array[i] <= array[end]:
i += 1
array[i], array[end] = array[end], array[i]
return i
else:
array[i], array[j] = array[j], array[i]
if __name__ == '__main__':
import numpy as np
from random import shuffle
print 'test with random list of integers and floats...'
test = list(np.random.randint(-50, 50, 500)) + list(np.random.uniform(-50, 50, 500))
shuffle(test)
control = sorted(test)
qsort(test)
print 'control == test:', control == test
|
64d2dd9aa016b25454c99109e7b0c6d4ac7ba901
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
scotchka/quicksort
|
e6e664f8fe4cf17dac9f6fe1a479b2e54966cbcd
|
23c6fbe8f2da39a0bfcf9e92402844cab25a6d61
|
refs/heads/master
|
<file_sep><?php
include_once 'connect.php';
if(isset($_GET['submit'])){
$num=$_GET['number'];
$stmt=$con->prepare("SELECT * FROM orders ORDER BY orderNumber DESC LIMIT $num ");
$stmt->execute();
$orders=$stmt->fetch();
print_r($orders);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="get" action="latest-orders.php">
<input type="number" placeholder="Enter Number" name="number">
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html><file_sep><?php
include_once 'connect.php';
if(isset($_GET['submit'])){
$Cname=$_GET['Cname'];
$stmt=$con->prepare("SELECT customerName FROM customers WHERE customerName LIKE '%$Cname%' OR customerName LIKE '$Cname%' OR customerName LIKE '%$Cname' OR customerName=$Cname ");
$stmt->execute();
$Names=$stmt->fetchAll();
print_r($Names);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="get" action="customer-search.php">
<input type="text" placeholder="Enter Search Name" name="Cname">
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html><file_sep><?php
include_once 'connect.php';
if(isset($_GET['submit'])){
$Pname=$_GET['Pname'];
$stmt=$con->prepare("SELECT COUNT(quantityOrdered) FROM orderdetails WHERE productCode=(SELECT productCode FROM products WHERE productName=?)");
$stmt->execute(array($Pname));
$Qordered=$stmt->fetchAll();
print_r($Qordered);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="get" action="product-quantity-orderded.php">
<input type="text" placeholder="Enter Product Name" name="Pname">
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
|
88879930706d1215a49e11b2091d198a4bb08511
|
[
"PHP"
] | 3 |
PHP
|
AyaEbrahimAlshafey/Aya-Ebrahim-Sat-5
|
5c2e1548988140541fa346cd8afb07d0e686a3ed
|
10b43578d31177dc666d9bcd88671acff3043dac
|
refs/heads/master
|
<file_sep>module github.com/FiloSottile/whoami.filippo.io
go 1.13
require (
github.com/go-sql-driver/mysql v1.5.0
github.com/google/go-cmp v0.4.0 // indirect
github.com/google/go-github/v29 v29.0.3
// https://github.com/influxdata/influxdb/issues/16901
github.com/influxdata/influxdb v1.7.9
golang.org/x/crypto v0.0.0-20200214034016-1d94cc7ab1c6
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
)
<file_sep>package main
import (
"context"
"crypto/rsa"
"database/sql"
"encoding/json"
"errors"
"expvar"
"fmt"
"net"
"os"
"strings"
"sync"
"text/template"
"time"
"github.com/google/go-github/v29/github"
"golang.org/x/crypto/ssh"
)
var termTmpl = template.Must(template.New("termTmpl").Parse(strings.Replace(`
+---------------------------------------------------------------------+
| |
| _o/ Hello {{ .Name }}!
| |
| |
| Did you know that ssh sends all your public keys to any server |
| it tries to authenticate to? |
| |
| That's how we know you are @{{ .User }} on GitHub!
| |
| Ah, maybe what you didn't know is that GitHub publishes all users' |
| ssh public keys and Ben (benjojo.co.uk) grabbed them all. |
| |
| That's pretty handy at times :) for example your key is at |
| https://github.com/{{ .User }}.keys
| |
| |
| P.S. This whole thingy is Open Source! (And written in Go!) |
| https://github.com/FiloSottile/whoami.filippo.io |
| |
| -- @FiloSottile (https://twitter.com/FiloSottile) |
| |
+---------------------------------------------------------------------+
`, "\n", "\n\r", -1)))
var failedMsg = []byte(strings.Replace(`
+---------------------------------------------------------------------+
| |
| _o/ Hello! |
| |
| |
| Did you know that ssh sends all your public keys to any server |
| it tries to authenticate to? You can see yours echoed below. |
| |
| We tried to use that to find your GitHub username, but we |
| couldn't :( maybe you don't even have GitHub ssh keys, do you? |
| |
| By the way, did you know that GitHub publishes all users' |
| ssh public keys and Ben (benjojo.co.uk) grabbed them all? |
| |
| That's pretty handy at times :) But not this time :( |
| |
| |
| P.S. This whole thingy is Open Source! (And written in Go!) |
| https://github.com/FiloSottile/whoami.filippo.io |
| |
| -- @FiloSottile (https://twitter.com/FiloSottile) |
| |
+---------------------------------------------------------------------+
`, "\n", "\n\r", -1))
var agentMsg = []byte(strings.Replace(`
***** WARNING ***** WARNING *****
You have SSH agent forwarding turned (universally?) on. That
is a VERY BAD idea. For example right now I have access to your
agent and I can use your keys however I want as long as you are
connected. I'm a good guy and I won't do anything, but ANY SERVER
YOU LOG IN TO AND ANYONE WITH ROOT ON THOSE SERVERS CAN LOGIN AS
YOU ANYWHERE.
Read more: http://git.io/vO2A6
`, "\n", "\n\r", -1))
var x11Msg = []byte(strings.Replace(`
***** WARNING ***** WARNING *****
You have X11 forwarding turned (universally?) on. That
is a VERY BAD idea. For example right now I have access to your
X11 server and I can access your desktop as long as you are
connected. I'm a good guy and I won't do anything, but ANY SERVER
YOU LOG IN TO AND ANYONE WITH ROOT ON THOSE SERVERS CAN SNIFF
YOUR KEYSTROKES AND ACCESS YOUR WINDOWS.
Read more: http://www.hackinglinuxexposed.com/articles/20040705.html
`, "\n", "\n\r", -1))
var roamingMsg = []byte(strings.Replace(`
***** WARNING ***** WARNING *****
You have roaming turned on. If you are using OpenSSH, that most likely
means you are vulnerable to the CVE-2016-0777 information leak.
THIS MEANS THAT ANY SERVER YOU CONNECT TO MIGHT OBTAIN YOUR PRIVATE KEYS.
Add "UseRoaming no" to the "Host *" section of your ~/.ssh/config or
/etc/ssh/ssh_config file, rotate keys and update ASAP.
Read more: https://www.qualys.com/2016/01/14/cve-2016-0777-cve-2016-0778/openssh-cve-2016-0777-cve-2016-0778.txt
`, "\n", "\n\r", -1))
type sessionInfo struct {
User string
Keys []ssh.PublicKey
}
type Server struct {
githubClient *github.Client
sshConfig *ssh.ServerConfig
newQuery *sql.Stmt
legacyQuery *sql.Stmt
hsErrs, errors *expvar.Int
agent, x11, roaming *expvar.Int
conns, withKeys, identified *expvar.Int
mu sync.RWMutex
sessionInfo map[string]sessionInfo
}
func (s *Server) PublicKeyCallback(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
s.mu.Lock()
si := s.sessionInfo[string(conn.SessionID())]
si.User = conn.User()
si.Keys = append(si.Keys, key)
s.sessionInfo[string(conn.SessionID())] = si
s.mu.Unlock()
// Never succeed a key, or we might not see the next. See KeyboardInteractiveCallback.
return nil, errors.New("")
}
func (s *Server) KeyboardInteractiveCallback(ssh.ConnMetadata, ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
// keyboard-interactive is tried when all public keys failed, and
// since it's server-driven we can just pass without user
// interaction to let the user in once we got all the public keys
return nil, nil
}
type logEntry struct {
Timestamp string
Username string
RequestTypes []string
Error string
KeysOffered []string
GitHub string
ClientVersion string
}
func (s *Server) Handle(nConn net.Conn) {
le := &logEntry{Timestamp: time.Now().Format(time.RFC3339)}
defer json.NewEncoder(os.Stdout).Encode(le)
conn, chans, reqs, err := ssh.NewServerConn(nConn, s.sshConfig)
if err != nil {
le.Error = "Handshake failed: " + err.Error()
s.hsErrs.Add(1)
return
}
defer func() {
s.conns.Add(1)
if len(le.KeysOffered) > 0 {
s.withKeys.Add(1)
}
if le.Error != "" {
s.errors.Add(1)
}
if le.GitHub != "" {
s.identified.Add(1)
}
s.mu.Lock()
delete(s.sessionInfo, string(conn.SessionID()))
s.mu.Unlock()
time.Sleep(500 * time.Millisecond)
conn.Close()
}()
roaming := false
go func(in <-chan *ssh.Request) {
for req := range in {
le.RequestTypes = append(le.RequestTypes, req.Type)
if req.Type == "<EMAIL>" {
roaming = true
}
if req.WantReply {
req.Reply(false, nil)
}
}
}(reqs)
s.mu.RLock()
si := s.sessionInfo[string(conn.SessionID())]
s.mu.RUnlock()
le.Username = conn.User()
le.ClientVersion = fmt.Sprintf("%x", conn.ClientVersion())
for _, key := range si.Keys {
le.KeysOffered = append(le.KeysOffered, string(ssh.MarshalAuthorizedKey(key)))
}
for newChannel := range chans {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
le.Error = "Channel accept failed: " + err.Error()
return
}
defer channel.Close()
agentFwd, x11 := false, false
reqLock := &sync.Mutex{}
reqLock.Lock()
timeout := time.AfterFunc(30*time.Second, func() { reqLock.Unlock() })
go func(in <-chan *ssh.Request) {
for req := range in {
le.RequestTypes = append(le.RequestTypes, req.Type)
ok := false
switch req.Type {
case "shell":
fallthrough
case "pty-req":
ok = true
// "auth-<EMAIL>" and "x11-req" always arrive
// before the "pty-req", so we can go ahead now
if timeout.Stop() {
reqLock.Unlock()
}
case "auth-<EMAIL>":
agentFwd = true
case "x11-req":
x11 = true
}
if req.WantReply {
req.Reply(ok, nil)
}
}
}(requests)
reqLock.Lock()
if agentFwd {
s.agent.Add(1)
channel.Write(agentMsg)
}
if x11 {
s.x11.Add(1)
channel.Write(x11Msg)
}
if roaming {
s.roaming.Add(1)
channel.Write(roamingMsg)
}
user, err := s.findUser(si.Keys)
if err != nil {
le.Error = "findUser failed: " + err.Error()
return
}
if user == "" {
channel.Write(failedMsg)
for _, key := range si.Keys {
channel.Write(ssh.MarshalAuthorizedKey(key))
channel.Write([]byte("\r"))
}
channel.Write([]byte("\n\r"))
return
}
le.GitHub = user
name, err := s.getUserName(user)
if err != nil {
le.Error = "getUserName failed: " + err.Error()
return
}
termTmpl.Execute(channel, struct{ Name, User string }{name, user})
return
}
}
func (s *Server) findUser(keys []ssh.PublicKey) (string, error) {
for _, pk := range keys {
var user string
key := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pk)))
err := s.newQuery.QueryRow(key).Scan(&user)
if err == sql.ErrNoRows && pk.Type() == ssh.KeyAlgoRSA {
// Try the legacy database.
k := pk.(ssh.CryptoPublicKey).CryptoPublicKey().(*rsa.PublicKey)
err = s.legacyQuery.QueryRow(k.N.String()).Scan(&user)
}
if err == sql.ErrNoRows {
continue
}
if err != nil {
return "", err
}
return user, nil
}
return "", nil
}
func (s *Server) getUserName(user string) (string, error) {
u, _, err := s.githubClient.Users.Get(context.TODO(), user)
if err != nil {
return "", err
}
if u.Name == nil {
return "@" + user, nil
}
return *u.Name, nil
}
<file_sep>package main
import (
"context"
"database/sql"
"expvar"
"log"
"net"
"net/http"
_ "net/http/pprof"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/google/go-github/v29/github"
"golang.org/x/crypto/ssh"
"golang.org/x/oauth2"
)
func fatalIfErr(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
go func() {
log.Println(http.ListenAndServe(os.Getenv("LISTEN_DEBUG"), nil))
}()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")},
)
tc := oauth2.NewClient(context.Background(), ts)
GitHubClient := github.NewClient(tc)
db, err := sql.Open("mysql", os.Getenv("MYSQL_DSN"))
fatalIfErr(err)
fatalIfErr(db.Ping())
_, err = db.Exec("SET NAMES UTF8")
fatalIfErr(err)
legacyQuery, err := db.Prepare("SELECT `username` FROM `keystore` WHERE `N` = ? LIMIT 1")
fatalIfErr(err)
newQuery, err := db.Prepare("SELECT `username` FROM `keys` WHERE `key` = ? LIMIT 1")
fatalIfErr(err)
server := &Server{
githubClient: GitHubClient,
legacyQuery: legacyQuery,
newQuery: newQuery,
sessionInfo: make(map[string]sessionInfo),
hsErrs: expvar.NewInt("handshake_errors"),
errors: expvar.NewInt("errors"),
agent: expvar.NewInt("agent"),
x11: expvar.NewInt("x11"),
roaming: expvar.NewInt("roaming"),
conns: expvar.NewInt("conns"),
withKeys: expvar.NewInt("with_keys"),
identified: expvar.NewInt("identified"),
}
server.sshConfig = &ssh.ServerConfig{
KeyboardInteractiveCallback: server.KeyboardInteractiveCallback,
PublicKeyCallback: server.PublicKeyCallback,
}
private, err := ssh.ParsePrivateKey([]byte(os.Getenv("SSH_HOST_KEY")))
fatalIfErr(err)
server.sshConfig.AddHostKey(private)
privateEd, err := ssh.ParsePrivateKey([]byte(os.Getenv("SSH_HOST_KEY_ED25519")))
fatalIfErr(err)
server.sshConfig.AddHostKey(privateEd)
listener, err := net.Listen("tcp", os.Getenv("LISTEN_SSH"))
fatalIfErr(err)
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Accept failed:", err)
continue
}
go server.Handle(conn)
}
}
<file_sep>package main
import (
"crypto/tls"
"crypto/x509"
"expvar"
"log"
"os"
"time"
"github.com/influxdata/influxdb/client/v2"
)
const (
influxTable = "whoami"
influxUsername = "frood"
influxDatabase = "frood"
influxAddr = "https://influxdb:8086"
influxRoot = `-----BEGIN CER<KEY>
-----END CERTIFICATE-----`
)
func startInfluxDB() {
pool := x509.NewCertPool()
pool.AppendCertsFromPEM([]byte(influxRoot))
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: influxAddr,
Username: influxUsername,
Password: os.Getenv("INFLUXDB_PASSWORD"),
Timeout: 10 * time.Second,
TLSConfig: &tls.Config{RootCAs: pool},
})
if err != nil {
log.Fatalln("InfluxDB error:", err)
}
go func() {
for range time.Tick(10 * time.Second) {
fields := make(map[string]interface{})
var do func(string, expvar.KeyValue)
do = func(prefix string, kv expvar.KeyValue) {
switch v := kv.Value.(type) {
case *expvar.Int:
fields[prefix+kv.Key] = v.Value()
case *expvar.Float:
fields[prefix+kv.Key] = v.Value()
case *expvar.String:
fields[prefix+kv.Key] = v.Value()
case *expvar.Map:
v.Do(func(x expvar.KeyValue) { do(kv.Key+".", x) })
default:
fields[prefix+kv.Key] = v.String()
}
}
expvar.Do(func(kv expvar.KeyValue) { do("", kv) })
if len(fields) == 0 {
continue
}
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
Database: influxDatabase,
Precision: "s",
})
pt, err := client.NewPoint(influxTable, nil, fields, time.Now())
if err != nil {
log.Fatalln("InfluxDB error:", err)
}
bp.AddPoint(pt)
if err := c.Write(bp); err != nil {
log.Fatalln("InfluxDB write error:", err)
}
}
}()
}
|
bb540e01364e7ef316364a17c843338f0c2927c2
|
[
"Go",
"Go Module"
] | 4 |
Go Module
|
isgasho/whoami.filippo.io
|
7464e26635ec2a31289eb80b73a0312764690137
|
b2903f5ccbce9feb3baf8964fb57b10c7cbb8501
|
refs/heads/master
|
<repo_name>MisterTrickster/OPD_4<file_sep>/OPD4_main.py
# Улучшить программу таким образом, чтобы она при запуске делала все пункты предыдущих заданий и рисовала график
# средней дневной температуры с начала текущего месяца по текущий день
import datetime # библиотека для отслеживания даты и времени
import requests # http библиотека для запросов.
import pickle # для записи и чтении в файл/из файла объектов в неизменном виде
import xlsxwriter # библиотека для того, чтобы записывать данные в файл фомрамата excel
# import re
from bs4 import BeautifulSoup
# вывод словаря столбиком
def print_dict(river_temp):
for item in river_temp:
print(item, ":\t", river_temp[item])
# вывод двумерного словаря столбиком
def print_2d_dict(any_dict):
for item in any_dict:
if item != 'дата':
print(any_dict['дата'].year, '.', any_dict['дата'].month, '.', item, ' ------')
print_dict(any_dict[item])
# Запись в файл.
def write(data_struction, file_name):
with open(file_name, 'wb') as f_write:
pickle.dump(data_struction, f_write)
f_write.close()
# Чтение из файла.
def read(file_name):
with open(file_name, 'rb') as f_read:
data_struction = pickle.load(f_read)
f_read.close()
return data_struction
# функция, возвразающая словарь, в котором ключ 'река river_name' и значение 'temperature'
def rivers_day_temp():
# ссылка на сайт с погодой
url = 'https://pogoda1.ru/katalog/sverdlovsk-oblast/temperatura-vody/'
r = requests.get(url)
# открытие страницы, которая сохранена в файле
with open('test.html', 'w') as output_file:
output_file.write(r.text)
# используем конструктор BeautifulSoup(), чтобы поместить текст ответа в переменную
soup = BeautifulSoup(r.text, features="html.parser")
# словарь с информацией о водоемах
rivers_temp_dict = {}
# поиск строчек в файле навзания рек и их температура, с последующей записью в файл
river_data = soup.find_all('div', class_="x-row")
for item in river_data:
rivers_temp_dict[item.find('a').text] = float(item.find('div', class_="x-cell x-cell-water-temp").text.strip())
return rivers_temp_dict
# функция выводящая(и записывающая в файл) значения средней температуры за день
def medial_day_temp():
new_dict = rivers_day_temp() # прочтенный с сайта словарь
# читаем словарь с файла, если файл пуст, то устанавливаем дату в new_dict и записываем
try:
old_dict = read('day_data.pickle')
except EOFError:
new_dict['дата'] = datetime.date.today()
write(new_dict, 'day_data.pickle')
return new_dict
# сравниваем дату, если дни не сходиться, то устанавливаем дату в new_dict и записываем в файл
if old_dict['дата'].day != datetime.date.today().day:
new_dict['дата'] = datetime.date.today()
write(new_dict, 'day_data.pickle')
return new_dict
else:
# цилк, который пробегает по ключам словаря и слкадывает температуру и делит на два, чтобы получить среднее
# арифметическое
for item in old_dict:
# пропускаем ключ 'дата'
if item != 'дата':
old_dict[item] = round(((old_dict[item] + new_dict[item]) / 2.0),
1) # складываем старые значние с новым и делим на два, округляем
write(old_dict, 'day_data.pickle')
return old_dict
# фунция, которая подсчитывает среднюю температуру за месяц.
def medial_month_temp():
new_dict = medial_day_temp() # 'Новый' словарь, который содержит средние данные за день
# читаем из файла, если он пустой, то записываем в файл новый массив с новыми данными
try:
old_dict = read('medial_month_data.pickle')
except EOFError:
new_dict['дата'] = datetime.date.today()
write(new_dict, 'medial_month_data.pickle')
return new_dict
# если месяц не сопаадет, то перезаписываем
if old_dict['дата'].month != datetime.date.today().month:
new_dict['дата'] = datetime.date.today()
write(new_dict, 'medial_month_data.pickle')
return new_dict
# если месяц совпадает, а день нет, то считаем среднее значение и записываем
elif (old_dict['дата'].day != datetime.date.today().day) and (
old_dict['дата'].month == datetime.date.today().month):
# цикл, который пробегает по всем рекам и вычсчитываем среднее значение для соответсвующих рек
for item in old_dict:
# пропускаем ключ 'дата'
if item != 'дата':
old_dict[item] = round(((old_dict[item] + new_dict[item]) / 2.0), 1)
write(old_dict, 'medial_month_data.pickle')
return old_dict
# если месяц и день соответсвенно совпадают, то просто возвращаем прочитанный список, оставляя файл без изменений
else:
return old_dict
# функция выводящая(и записывающая в файл) значения средней температуры за месяц
def medial_day_temp_by_month():
new_dict = {} # словарь, который содержит ключ 'номер_дня', а значение список со средней температурой за день.
# читаем из файла, если файл пустой то записываем новый словарь со словаряит в файл
try:
old_dict = read('month_data.pickle')
except EOFError:
new_dict['дата'] = datetime.date.today()
new_dict[datetime.date.today().day] = medial_day_temp()
write(new_dict, 'month_data.pickle')
return new_dict
# проверяем дату, если месяц не совпадает, то перезаписываем
if old_dict['дата'].month != datetime.date.today().month:
old_dict.clear()
new_dict['дата'] = datetime.date.today()
new_dict[datetime.date.today().day] = medial_day_temp()
write(new_dict, 'month_data.pickle')
return new_dict
# если совпадает, то перезаписываем средную температуру за день, в ячейку этого дня.
else:
old_dict[datetime.date.today().day] = medial_day_temp()
write(old_dict, 'month_data.pickle')
return old_dict
# Запись в xlsx файл
# открываем новый файл на запись
workbook = xlsxwriter.Workbook('rivers_data.xlsx')
# создаем там "лист1" и "лист2"
worksheet_1 = workbook.add_worksheet()
worksheet_2 = workbook.add_worksheet()
# делаем шаблон на Лист1
worksheet_1.write('B2', 'Дата:')
worksheet_1.write('C2', str(datetime.date.today())) # Дата
worksheet_1.write('B4', 'Название')
worksheet_1.write('C4', 'Текущ.темп')
worksheet_1.write('E4', 'Ср.темп:')
worksheet_1.write('F4', 'за день')
worksheet_1.write('G4', 'за месяц')
# делаем шаблон на Лист2
worksheet_2.write('B2', 'Средняя температура за месяц по дням')
worksheet_2.write('B4', 'Даты:')
# работа над листом_1
# вспомогательные переменные, колонка и столбик
col = 1
row = 4
# словарь с текущей температурой
current_temp_dict = rivers_day_temp()
# записываем навзание рек в строчку 'B' с 5 строки
for item in current_temp_dict:
worksheet_1.write(row, col, item)
worksheet_1.write(row, col + 1, current_temp_dict[item])
row += 1
# средняя температура за день
medial_day_temp_dict = medial_day_temp()
# средняя температура за месяц
medial_month_temp_dict = medial_month_temp()
row = 4
col = 5
# записываем средную температуру за день в колонку F начиная с 4 строки
for item in medial_day_temp_dict:
if item != 'дата':
worksheet_1.write(row, col, medial_day_temp_dict[item])
row += 1
row = 4
col = 6
# записываем средную температуру за месяц в колонку G начиная с 4 строки
for item in medial_month_temp_dict:
if item != 'дата':
worksheet_1.write(row, col, medial_month_temp_dict[item])
row += 1
# работа над листом_2
# вспомогательные переменные, колонка и столбик
col = 2
row = 3
# вспомогательные переменные для температуры и навзаний рек
col_1 = 1
row_1 = 4
# флажок
f = True
# словарь, в который сохранены данные по дням
rivers_days_data = medial_day_temp_by_month()
# записываем даты, в которые сохранены данные по дням
for item in rivers_days_data:
if item != 'дата':
worksheet_2.write(row, col, str(item)+'.'+str(rivers_days_data['дата'].month))
col += 1
# col_1 = 1
row_1 = 4
# запишем для каждой даты данные по температурам водоемах
if f:
for sub_item in rivers_days_data[item]:
if sub_item != 'дата':
worksheet_2.write(row_1, col_1, sub_item)
worksheet_2.write(row_1, col_1 + 1, rivers_days_data[item][sub_item])
row_1 += 1
f = False
col_1 += 2
else:
for sub_item in rivers_days_data[item]:
if sub_item != 'дата':
worksheet_2.write(row_1, col_1, rivers_days_data[item][sub_item])
row_1 += 1
col_1 += 1
# создадим объект типа диаграмма
line_chart = workbook.add_chart({'type': 'line'})
# зводим данные в диаграмму
# добавляем имена значение и категории в диаграмму
for i in range(4, 21):
line_chart.add_series({'values': ['Sheet2', i, 2, i, col_1 - 1],
'name': ['Sheet2', i, 1],
'categories': ['Sheet2', 3, 2, 3, col_1-1]})
# Устанавливаем наименования осей
line_chart.set_x_axis({'name': 'Дата'}) # Ось OX
line_chart.set_y_axis({'name': 'Температура(°C)'}) # Ось OY
line_chart.set_title({
'name': 'Средняя температура за день в месяце',
'overlay': True
})
# вставляем на лист_2 линейную диаграмму
worksheet_2.insert_chart('B26', line_chart)
print(col_1)
workbook.close()
|
f41d23833aab8a54670ec00db2434041e1d697bf
|
[
"Python"
] | 1 |
Python
|
MisterTrickster/OPD_4
|
fb27dee61afe2d997af46db50bcac23086af06be
|
afddf6c59417b7cec08c45938e0e5acfe503d6ae
|
refs/heads/master
|
<repo_name>hze1110/project<file_sep>/project/css/jd/slider.js
function animate(obj,target){
clearInterval(obj.timer);
var speed=target>obj.offsetLeft? 50 : -50;
obj.timer=setInterval(function(){
var result=target-obj.offsetLeft;
obj.style.left=obj.offsetLeft+speed+"px";
if(Math.abs(result)<=100){
clearInterval(obj.timer);
obj.style.left=target+"px";
}
},10);
}
window.onload=function(){
var slider=document.getElementById("_slider");
var ul=slider.children[0];
var ulLis=ul.children;
ul.appendChild(ulLis[0].cloneNode(true));
var ol=document.createElement('ol');
slider.appendChild(ol);
for(var i=0; i<ulLis.length-1;i++){
var li=document.createElement('li');
li.innerHTML=i+1;
ol.appendChild(li);
}
ol.children[0].className="current";
var olLis=ol.children;
for(var i=0; i<olLis.length; i++){
olLis[i].index=i;
olLis[i].onmouseover=function(){
for(var j=0; j<olLis.length; j++){
olLis[j].className="";
}
this.className="current";
animate(ul,-(this.index)*730);
// console.log(i);
key=span=this.index;
}
}
var key=0,timer=null;
var span=0;
timer=setInterval(fn,1500);
function fn(){
key++;
//console.log(key);
if(key>ulLis.length-1){
// console.log(key);
//clearInterval(timer);
console.log(key);
ul.style.left=0;
key=1;
}
animate(ul,-730*key);
span++;
if(span>olLis.length-1){
span=0;
}
for(var i=0; i<olLis.length; i++){
olLis[i].className="";
}
olLis[span].className="current";
}
slider.onmouseover=function(){
clearInterval(timer);
}
slider.onmouseout=function(){
timer=setInterval(fn,1500);
}
}<file_sep>/README.md
#project
/前端练习题/
|
88f2ab434d68641dab7736ade47557850285fda6
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
hze1110/project
|
8daf585d00b27c82ae5cd172d56287355325f2fe
|
4d4741e7100c71b4822c7b1e10abc7c652cbe99f
|
refs/heads/master
|
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>chorba.shkembe</groupId>
<artifactId>MScIT2020Project</artifactId>
<version>1.0</version>
<name>Top Trumps Application Project</name>
<description>This is the template java project for the Top Trumps Assessed Excercise for IT Software Development at Glasgow 2019. </description>
<!-- Specify which version of Dropwizard we are going to use for histing the REST API and Website -->
<properties>
<junit.jupiter.version>5.5.2</junit.jupiter.version>
<dropwizard.version>1.2.2</dropwizard.version>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<!-- Set the source directory for new directory structure -->
<src.dir>src/main/java</src.dir>
<!-- Set the .jar name for the package build -->
<package.name>TopTrumps</package.name>
</properties>
<!-- These are the other software libruaries developed by third parties that we need -->
<dependencies>
<!-- for JSON Parsing -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<!-- Mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.2.4</version>
</dependency>
<!-- PostreSQL Driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.9</version>
</dependency>
<!-- Dropwizard is a bundle of REST API hosting tools -->
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<!-- When hosting a website with dropwizard, we need to specify a language for writing views,
In this case, we are using freemarker https://freemarker.apache.org/ -->
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-views-freemarker</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<!-- Add folder for assets to use in ftl files
https://mvnrepository.com/artifact/io.dropwizard/dropwizard-assets -->
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-assets</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<!-- One of the requirements is to save results in a (mysql) database, so lets import the
database connection driver libruary for that as well -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- Add JUnit 5 for unit testing (see properties for version) -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- Where do our Java sources come from? -->
<sourceDirectory>${src.dir}</sourceDirectory>
<!-- Revert to Maven's default resource directory (src/main/resources) -->
<!-- <resources>
<resource>
<directory>resources</directory>
</resource>
</resources> -->
<!-- Plugin Management for users working with the Eclipse IDE. org.eclipse.m2e:lifecycle-mapping
instructs eclipse how to build the maven project -->
<pluginManagement>
<plugins>
<!-- Resources Plugin: Copy the JSON and Deck to the target directory for the .jar.
This is to simplify testing, as running the .jar from the /target directory makes it
complain.
-->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>copy-resources</id>
<!-- When running mvn package -->
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target/</outputDirectory>
<resources>
<resource>
<directory>${basedir}</directory>
<includes>
<!-- Only copy the .json and .txt files -->
<include>*.json</include>
<include>*.txt</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<!-- Allows a site to be built with reports etc.
Found in target/site -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<versionRange>[1.0,)</versionRange>
<goals>
<goal>parse-version</goal>
<goal>add-source</goal>
<goal>maven-version</goal>
<goal>add-resource</goal>
<goal>add-test-resource</goal>
<goal>add-test-source</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute>
<runOnConfiguration>true</runOnConfiguration>
<runOnIncremental>true</runOnIncremental>
</execute>
</action>
</pluginExecution>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<versionRange>[1.0.0,)</versionRange>
<goals>
<goal>resources</goal>
<goal>testResources</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute>
<runOnConfiguration>true</runOnConfiguration>
<runOnIncremental>false</runOnIncremental>
</execute>
</action>
</pluginExecution>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<versionRange>2.3.2</versionRange>
<goals>
<goal>testCompile</goal>
<goal>compile</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
<!-- copy-dependency plugin -->
<!-- http://stackoverflow.com/questions/26482070/using-maven-assembly-plugin-with-local-dependencies -->
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>2.6</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
<!-- Add surefire and failsafe for JUnit testing from maven -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<printSummary>true</printSummary>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</pluginManagement>
<!-- Plugins, these do things like compiling the java sources and packaging into a jar -->
<plugins>
<!-- Compiles your java sources -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source />
<target />
</configuration>
</plugin>
<!-- Packages those sources in a Jar file -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<!-- Set output .jar to be the package.name property -->
<finalName>${package.name}</finalName>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<!-- Main class for the Jar file -->
<mainClass>TopTrumps</mainClass>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!-- Looks at code to generate test coverage reports -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.5</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<!-- attached to Maven test phase -->
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<!-- Add reporting for mvn site, for shared documentation and general reporting -->
<reporting>
<plugins>
<!-- Add JaCoCo for code test coverage reports -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<reportSets>
<reportSet>
<reports>
<!-- select non-aggregate reports -->
<report>report</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<!-- For JavaDoc generation -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.1</version>
</plugin>
</plugins>
</reporting>
</project><file_sep>package model;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Pile tests
*/
class PileTest {
static final Card CARD_0 = new Card("1");
static final Card CARD_1 = new Card("2");
static final Card CARD_2 = new Card("3");
static final Card CARD_3 = new Card("4");
/**
* Adds dummy cards to a pile
*
* @param pile the pile
* @param numCards the number of empty cards to be added
*/
static void addCardHelper(Pile pile, int numCards) {
for (int i = 0; i < numCards; i++) {
pile.add(new Card("" + i));
}
}
/*
* Validation Tests
*/
@DisplayName("Initialises with an empty pile")
@Test
void initialiseWithEmptyPile() {
Pile pile = new Pile();
assertEquals(0, pile.size());
}
@DisplayName("Shows correct size and tests the add method")
@Test
void sizeAndAdd() {
Pile pile = new Pile();
addCardHelper(pile, 40);
assertEquals(40, pile.size());
}
@DisplayName("Shows correct card when peeked")
@Test
void peek() {
Pile pile = new Pile();
pile.add(CARD_0);
assertEquals(CARD_0, pile.peek());
}
@DisplayName("Can peek the top card without removing it")
@Test
void peekGetsCardAndDoesNotRemove() {
Pile pile = new Pile();
addCardHelper(pile, 40);
pile.peek();
assertEquals(40, pile.size());
}
@DisplayName("Pop removes the top card")
@Test
void popRemovesTopCardAndReturns() {
Pile pile = new Pile();
addCardHelper(pile, 40);
pile.pop();
assertEquals(39, pile.size());
}
@DisplayName("Tests pile add method")
@Test
void popAddPile() {
Pile pile = new Pile();
Pile pile2 = new Pile();
addCardHelper(pile, 40);
addCardHelper(pile2, 40);
pile.add(pile2);
assertEquals(80, pile.size());
}
@DisplayName("Tests the cards split method for non equal cards between players")
@Test
public void splitWorkingNonEqualPlayerCards() {
Pile pile = new Pile();
addCardHelper(pile, 42);
// Split the pile into 4
ArrayList<Pile> list = pile.split(4);
// The split should be the size of the split plus 1 (the remainder)
assertEquals(5, list.size());
// Check each of the splits is 42/4 (10)
for (int i = 0; i < 4; i++) {
assertEquals(10, list.get(i).size());
}
// Check the remainder is 42%4 (2)
assertEquals(2, list.get(4).size());
}
@DisplayName("Tests the cards split method for equal cards between the players")
@Test
public void splitWorkingEqualPlayerCards() {
Pile pile = new Pile();
addCardHelper(pile, 40);
ArrayList<Pile> list = pile.split(4);
assertEquals(5, list.size());
for (int i = 0; i < 4; i++) {
assertEquals(10, list.get(i).size());
}
assertEquals(0, list.get(4).size());
}
@DisplayName("Tests the toString")
@Test
public void toStringWorking() {
Pile pile = new Pile();
addCardHelper(pile, 10);
String toString = pile.toString();
assertTrue(toString.startsWith("-------- START OF PILE -------- \n")
&& toString.endsWith("-------- END OF PILE -------- \n"));
}
@DisplayName("Shuffle")
@Test
public void shuffleReturnsADifferentOrder() {
Pile pile = new Pile();
addCardHelper(pile, 5);
// Clone a copy of the original order
LinkedList<Card> initialOrder = new LinkedList<Card>(pile.getCards());
pile.shuffle();
// Check the new order doesn't equal the original
assertNotEquals(initialOrder, pile.getCards());
}
@Nested
@DisplayName("reader()")
class Reader {
private final String TEST_RESOURCE_DIRECTORY = "src/test/resources/commandline/model";
// Our test deck is 2 cards
private final String CARD_DECK_2 =
new File(TEST_RESOURCE_DIRECTORY, "cardDeckTwo.txt").toString();
@DisplayName("Returns a pile with the same properties as in the text file")
@Test
public void readerWorking() {
Pile pile = null;
try {
pile = Pile.reader(CARD_DECK_2);
} catch (IOException e) {
fail("IOException in test");
}
Card card1 = new Card("350r");
card1.add(new Attribute("Size", 1));
card1.add(new Attribute("Speed", 9));
card1.add(new Attribute("Range", 2));
card1.add(new Attribute("Firepower", 3));
card1.add(new Attribute("Cargo", 0));
Card card2 = new Card("Avenger");
card2.add(new Attribute("Size", 2));
card2.add(new Attribute("Speed", 5));
card2.add(new Attribute("Range", 4));
card2.add(new Attribute("Firepower", 5));
card2.add(new Attribute("Cargo", 2));
assertEquals(2, pile.size(), "Pile should be 2 cards");
List<Card> cardsInPile = pile.getCards();
Card pileCard1 = cardsInPile.get(0);
Card pileCard2 = cardsInPile.get(1);
// Check the cards are the same, compare by string to avoid object clash
assertEquals(card1.toString(), pileCard1.toString());
assertEquals(card2.toString(), pileCard2.toString());
}
}
}
<file_sep>package model;
/**
* Player class that represents the human player and is a superclass of the AIPlayer class. It
* allows assigning a pile of cards to the Player, creating new players and retrieving them.
*/
public class Player {
private String name;
private int roundsWon;
private Pile playerDeck = new Pile();
/**
* Create a new Player.
*
* @param name The player name.
*/
public Player(String name) {
this.name = name;
}
/**
* Used in the beginning of a game to assign a pile to a player in the game used to transfer
* cards from community pile to Player
*
* @param addedPile pile of cards
*/
public void addToDeck(Pile addedPile) {
playerDeck.add(addedPile);
}
/**
* Method that returns number of rounds that the player won
*
* @return roundsWon
*/
public int getRoundsWon() {
return this.roundsWon;
}
/**
* Increase counter of rounds for player Used when player wins a round
*/
public void wonRound() {
this.roundsWon++;
}
/**
* Method that returns the top card of the player
*
* @return topCard
*/
public Card peekCard() {
Card topCard = playerDeck.peek();
return topCard;
}
/**
* Method that returns the top card of the player and removes it from their deck.
*
* @return top card of player
*/
public Card popCard() {
return playerDeck.pop();
}
/**
* Returns name of a player
*
* @return name of the player
*/
public String toString() {
return name;
}
/**
* Returns the size of the deck of the player without their top card.
*
* @return
*/
public int getRemainingDeckSize() {
return playerDeck.size() - 1;
}
// Getter.
public Pile getDeck() {
return playerDeck;
}
}
<file_sep>package commandline;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
public abstract class IOStreamTest {
// Setup I/O for each test
// ------------------------
private final InputStream originalIn = System.in;
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@BeforeEach
protected void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@AfterEach
protected void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
System.setIn(originalIn);
}
// Helper to provide mock input
protected void provideInput(String data) {
System.setIn(new ByteArrayInputStream(data.getBytes()));
}
protected String getOut() {
// Replace Windows return carriages with unix equivilents.
return outContent.toString().replace("\r", "");
}
protected String getErr() {
// Replace Windows return carriages with unix equivilents.
return errContent.toString().replace("\r", "");
}
}
<file_sep>package model;
import commandline.utils.ListUtility;
import java.util.ArrayList;
/**
* Represents the cards in the game.
*/
public class Card {
//Fields.
protected String name;
protected ArrayList<Attribute> attributeList = new ArrayList<Attribute>();
/**
* Constructor.
* @param name name of card
*/
public Card(String name) {
if ("".equals(name) || (name == null)) {
throw new IllegalArgumentException("No empty names allowed");
}
this.name = name;
}
/**
* Adds an attribute to the card.
* @param attribute
*/
public void add(Attribute attribute) {
this.attributeList.add(attribute);
}
/**
* toString
* @return Card name: name
* bullet list of attributes
*/
@Override
public String toString() {
String attributeString = new ListUtility(attributeList).getBulletList();
return String.format("Card name: %s\n%s", name, attributeString);
}
/**
* Return the value of the attribute in the card
* with the same name as the name of the passed attribute.
* @param givenAttribute
* @return value of attribute of the same type
*/
public int getValue(Attribute givenAttribute) {
String givenAttributeName = givenAttribute.getName();
for (Attribute attribute : attributeList) {
if (attribute.getName().equals(givenAttributeName)) {
return attribute.getValue();
}
}
return 0;
}
/**
* Return the i'th attribute
* @param i
* @return
*/
public Attribute getAttribute(int i) {
return this.attributeList.get(i);
}
//Getters.
public ArrayList<Attribute> getAttributes() {
return this.attributeList;
}
public String getName() {
return this.name;
}
}
<file_sep>package commandline.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import commandline.IOStreamTest;
/**
* Logger tests
*/
public class LoggerTest {
/*
* Setup
*/
// Creates a temporary test log in the current directory
private static final String TEST_FILE_PATH_STRING = "./testLogger.log";
// A helper function for getting the contents of the test log
private String getTestFileContents() {
String fileContent = "";
try {
fileContent = new String(Files.readAllBytes(Paths.get(TEST_FILE_PATH_STRING)));
System.out.println(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
// Delete the temporary test log after each test
@AfterEach
private void removeFilesCreated() {
File testFile = new File(TEST_FILE_PATH_STRING);
testFile.delete();
}
@Nested
@DisplayName("When the logger has been enabled")
class Enabled {
/*
* Validation tests
*/
@DisplayName("A test log file is created when enabled")
@Test
public void newFileWhenEnabled() {
File outputFile = new File(TEST_FILE_PATH_STRING);
Logger logger = new Logger(TEST_FILE_PATH_STRING);
try {
logger.enable();
} catch (IOException e) {
fail("I/O error during test");
}
assertTrue(outputFile.exists());
}
@DisplayName("Logger can be used statically when enabled and in app scope")
@Test
void canBeUsedStatically() {
// Create in scope
Logger logger = new Logger(TEST_FILE_PATH_STRING);
Logger.log("Test");
}
@DisplayName("Each entry creates the message with a divider after it")
@Test
void logEntryCorrectFormat() {
// Expect that the divider string is given after each log.
String expectedOutput = "Test\n" + Logger.LOGGER_DIVIDER_STRING + "\n";
// Create in scope
Logger logger = new Logger(TEST_FILE_PATH_STRING);
try {
logger.enable();
} catch (IOException e) {
fail("I/O error during test");
}
Logger.log("Test");
assertEquals(expectedOutput, getTestFileContents());
}
@DisplayName("Can provide a header to each log easily")
@Test
void logEntryCorrectFormatWithHeader() {
// Expect that a header that is one space above the message can be provided
String expectedOutput = "Header\n\n" + "Test\n" + Logger.LOGGER_DIVIDER_STRING + "\n";
// Create in scope
Logger logger = new Logger(TEST_FILE_PATH_STRING);
try {
logger.enable();
} catch (IOException e) {
fail("I/O error during test");
}
Logger.log("Header", "Test");
assertEquals(expectedOutput, getTestFileContents());
}
}
// This class extends IOStreamTest to allow access to streams
@Nested
@DisplayName("When the logger is not enabled")
class NotEnabled extends IOStreamTest {
/*
* Defect tests
*/
@DisplayName("Logger does not throw when used statically but disabled")
@Test
void loggerIsSilentWhenNotEnabled() {
// Create in scope
Logger logger = new Logger(TEST_FILE_PATH_STRING);
Logger.log("This should not throw");
}
@DisplayName("No default behaviour to System.err")
@Test
void noOutputToSystemDotOut() {
// Create in scope
Logger logger = new Logger(TEST_FILE_PATH_STRING);
Logger.log("Test");
assertEquals("", getErr().toString());
}
@DisplayName("No file is made when logger is not enabled")
@Test
void noFileUntilEnabled() {
// Create in scope
Logger logger = new Logger(TEST_FILE_PATH_STRING);
File outputFile = new File(TEST_FILE_PATH_STRING);
assertFalse(outputFile.exists());
}
}
}
<file_sep>/**
* A psuedo class that uses closures to encapsulate information and returns an object
* with all the public methods.
*
* @param {Object} playerObj - the player object passed by the api
*/
const PlayerFactory = (playerObj) => {
// CLASS NAMES
// -----------
const NAME_BADGE = "tt-is-active";
const ATTRIBUTE_NAME = "tt-attribute-name";
const CARD_COVER = "card-hider";
const CARD_HEADER = "tt-card-header";
const DECK_SIZE = "tt-deck-size";
// TEMPLATES
// ---------
const attributeTemplate = (attribute) => {
return `<li class="list-group-item d-flex justify-content-between align-items-center">
<span class="${ATTRIBUTE_NAME}">${attribute.name}</span>
<span class="badge badge-primary badge-pill">${attribute.value}</span>
</li>`;
};
const cardTemplate = (card) => {
return `
<div class="card-body">
<div class="${CARD_COVER}">
<div class="row align-items-center" style="height: 100%">
<div class="col text-center">
<h3>Top Trumps</h3>
</div>
</div>
</div>
<h4 class="card-title">${card.name}</h4>
<ul class="list-group list-group-flush">
${card.attributes.map((a) => attributeTemplate(a)).join("")}
</ul>
</div>
`;
};
const playerTemplate = (player) => {
const icon = player.isAI
? `<i class="fa fa-desktop" aria-hidden="true"></i>`
: `<i class="fa fa-user" aria-hidden="true"></i>`;
const iconActive = player.isActive
? `<i class="fa fa-star" aria-hidden="true"></i>`
: ``;
return `
<div class="card card-player align-self-center mt-3">
<div class="${CARD_HEADER} card-header">
<div class="row">
<div class="col-12 d-flex justify-content-center">
<h3>
<span class="${NAME_BADGE} badge">
${icon}
${iconActive}
${player.name}
</span>
</h3>
</div>
<div class="col-12 d-flex justify-content-center">
<div class="col text-center">
<span class="${DECK_SIZE} badge badge-light">
Deck remaining:
<span class="badge badge-primary badge-pill">${
player.deckSize
}</span>
</span>
</div>
</div>
</div>
</div>
${cardTemplate(player.topCard)}
</div>
`;
};
// PRIVATE VARIABLES
// -----------------
// Create a jquery reference inside this 'class' as a private member (using closure)
const $this = $(playerTemplate(playerObj));
const $nameBadge = $this.find("." + NAME_BADGE);
const $cardCover = $this.find("." + CARD_COVER);
const $cardHeader = $this.find("." + CARD_HEADER);
const $deckSize = $this.find("." + DECK_SIZE);
// PRIVATE METHODS
// ---------------
const highlightAttribute = (attributeName, color) => {
$this
// Find the attribute field that has the attribute name containing the desired name
.find(`.${ATTRIBUTE_NAME}:contains(${attributeName})`)
.parent() // Get the parent list element and colorize it
.css("background-color", color)
.css("color", "white");
};
// CONSTRUCTOR
// -----------
// If the player is active, change namebadge colour to green, otherwise yellow
if (playerObj.isActive) {
$nameBadge.addClass("badge-success");
} else {
$nameBadge.addClass("badge-warning");
}
// PUBLIC METHODS
// --------------
return {
// Get the owning player's name
getName: () => {
return playerObj.name;
},
// Return if the player is a user
isUser: () => {
return playerObj.isAI ? false : true;
},
// Add to a dom element (passed by ID or class as a parameter, e.g. #card-deck)
attach: (container) => {
$(container).append($this);
},
// Makes the cardCover visible (see .card-hider in css)
// Effectively covers the contents of a card from view
hideCard: () => {
$cardCover.addClass("card-hider-hide");
},
// Makes the card attributes visible by removing the css class
showCard: () => {
$cardCover.removeClass("card-hider-hide");
},
// Highlights the namebadge green to show it is a winner.
// Also highlights the winning attribute green.
setWinner: (attributeName) => {
highlightAttribute(attributeName, "green");
$nameBadge
.removeClass("badge-danger")
.removeClass("badge-warning")
.addClass("badge-success");
},
// Highlights the namebadge red to show it is a loser.
// Also highlights the winning attribute red.
setLoser: (attributeName) => {
highlightAttribute(attributeName, "red");
$nameBadge
.removeClass("badge-warning")
.removeClass("badge-success")
.addClass("badge-danger");
},
// As above, but a lot more violent. Sets the whole header red
// and displays an IS OUT message in the name badge
eliminate: () => {
// Set header a violent red
$cardHeader.css("background-color", "red");
// Set label to eliminated
$nameBadge
.removeClass("badge-warning")
.removeClass("badge-success")
.addClass("badge-danger") // Overrides primary and warning
.empty()
.text(`${playerObj.name} IS OUT`);
// Set deck size to red for emphasis on that fat 0.
$deckSize.removeClass("badge-light").addClass("badge-danger");
},
};
};
<file_sep>/**
* API.js
*
* A module that allows encapsulation of the API calls for consumption in
* other javascript files. Allows any modifications to be isolated to this
* file so backend / frontend devs can work from 'one source of truth'.
*/
// API PATHS
const URL_GET_STATISTICS = "http://localhost:7777/toptrumps/retrieveStats";
const URL_INIT_ROUND = "http://localhost:7777/toptrumps/initRound";
const URL_INIT_GAME = "http://localhost:7777/toptrumps/initGame";
const URL_GAME_OVER_SCORES = "http://localhost:7777/toptrumps/getGameOverScores";
const URL_PLAY_ROUND_WITH_ATTRIBUTE = "http://localhost:7777/toptrumps/playRoundWithAttribute";
// CORS REQUEST HELPER FUNCTIONS
// -----------------------------
function createCORSRequest(method, url) {
let xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
// Don't need to touch this, it's DRY :D
function apiGet(url, callback, paramDictionary) {
// Add the contents of the parameter dictionary to the end of the URL
let requestString = "";
Object.keys(paramDictionary).forEach((key, index) => {
// If it is the first item, append query character, otherwise &
const queryPrefix = index === 0 ? "?" : "&";
// Return "?key1=val1&key2=val2 ... "
requestString += queryPrefix + key + "=" + paramDictionary[key];
});
// First create a CORS request, this is the message we are going to send (a get request in this case)
let xhr = createCORSRequest("GET", url + requestString); // Request type and URL
// Message is not sent yet, but we can check that the browser supports CORS
if (!xhr) {
alert("CORS not supported");
}
// CORS requests are Asynchronous, i.e. we do not wait for a response, instead we define an action
// to do when the response arrives
xhr.onload = function() {
const obj = JSON.parse(xhr.response);
callback(obj);
};
// We have done everything we need to prepare the CORS request, so send it
xhr.send();
}
// API FUNCTIONS
// -------------
/**
* apiGetStatistics
* ----------------
* Returns the game statistics as a JavaScript object/dictionary.
*
* Must be called when a player requests the game statistics.
*
* Format :
* {
* "aiWins": 5,
* "userWins": 3,
* "avgDraws": 4,
* "totGamesPlayed": 7,
* "maxRounds": 8
* }
*/
function apiGetStatistics(callback) {
apiGet(URL_GET_STATISTICS, callback, {});
}
/**
* Makes the AI choose an attribute if it is active.
* Returns the information needed to initialise a round
* as a JavaScript object/dictionary.
*
* Must be called at the beginning of a round.
*
* chosenAttributeName corresponds to null
* if the user is active and it corresponds to the
* attribute that the AI chooses otherwise.
*
* EXAMPLE:
* {
* "round": 1,
* "communalPileSize": 4,
* "chosenAttributeName": "strength"/null,
* "playersInGame" : [
* {
* "name": "USER",
* "isAI": false,
* "isActive": true,
* "deckSize": 10,
* "topCard": {
* "name": "TRex",
* "attributes": [
* {
* "name": "strength",
* "value": 5
* }
* ]
* }
* }
* ]
* }
*/
function apiInitRound(callback) {
apiGet(URL_INIT_ROUND, callback, {});
}
/**
* Initialises the game with the chosen number of AI players.
* Returns {loaded: true}.
*
* Must be called before a game begins.
* @param numAiPlayers chosen number of AI players
*/
function apiInitGame(numPlayers, callback) {
apiGet(URL_INIT_GAME, callback, {
NumAiPlayers: numPlayers,
});
}
/**
* Plays a round with the chosen attribute and auto completes the game if the user is eliminated
* and there is no winner. If there is a winner in the round or the game is auto completed this
* will be reflected in the gameWinnerName and gameAutoCompleted fields and the database will be
* updated. Returns a JavaScript object/dictionary with information for playing a round with an attribute and
* possible game over information.
*
* Must be called after initRound().
*
* If the game is auto completed roundWinnerName and eliminatedPlayersNames correspond to
* information about the last round before the autocompletion, not the last round overall.
*
* roundWinnerName corresponds to null if there was a draw and it corresponds to the name of the
* round winner otherwise.
*
* gameOver being true does not necessarily mean that the game ended in the current round, the
* game could have been auto completed. That must be checked via gameAutoCompleted in
* getGameOverScores().
*
* EXAMPLE: { "roundWinnerName": "USER"/null,
* "gameOver": true,
* "eliminatedPlayersNames": ["AI1", "AI2"] }
*/
function apiPlayRoundWithAttribute(attributeName, callback) {
apiGet(URL_PLAY_ROUND_WITH_ATTRIBUTE, callback, {
AttributeName: attributeName,
});
}
/**
* Returns the won rounds for every player during the game, the game winner name and whether the
* game auto completed.
*
* Must be called when a game has ended, i.e. there is a winner.
*
*
*
* EXAMPLE: { "playerScores": [ { "name": "USER", "score": 15}, { name: "AI1", "score": 10}, ...],
* "gameWinnerName": "USER",
* "gameAutoCompleted": true }
*/
function apiGetGameOverScores(callback) {
apiGet(URL_GAME_OVER_SCORES, callback, {});
}
<file_sep>package commandline.view;
import org.junit.jupiter.params.provider.Arguments;
import java.util.stream.Stream;
/**
* A helper class to provide arrays to ParameterizedTests (which cannot otherwise be done) Used in
* {@link CommandLineViewTest.getUserSelection#displaysErrorOnInvalidInput}
*/
public class ArrayProviderTest {
/**
* Provides a steam of string arrays of various sizes (guaranteed to be at least length 1) for
* use with parametized tests.
*
* @return a stream of <Arguments> which are string arrays
*/
public static Stream<Arguments> stringArrayProvider() {
return Stream.of(Arguments.of((Object) new String[] {"tomato", "onion"}),
Arguments.of((Object) new String[] {"1", "2", "3"}),
Arguments.of((Object) new String[] {"1", "2", "3", "5", "twenty", "blah"}));
}
}
<file_sep>package model;
import java.util.ArrayList;
import java.util.Collections;
/**
* Class that represents the AI Players in the game.
*/
public class AIPlayer extends Player {
public AIPlayer(String name) {
super(name);
}
/**
* Chooses the attribute for the AI Player and returns it.
* Uses the fact that attributes are comparable and returns the
* one with highest value.
* @return attribute
*/
public Attribute chooseAttribute() {
ArrayList<Attribute> cardAttributes = peekCard().getAttributes();
Attribute max = Collections.max(cardAttributes);
return max;
}
}<file_sep>package model;
import java.sql.*;
/**
* This class holds the database functionality for the TopTrumpsGame.
* It has methods to connect/disconnect to/from a PostgreSQL database and
* upload/download game statistics to/from it.
*/
public class Database {
// Default database Connection parameters.
private static final String URL = "jdbc:postgresql://yacata.dcs.gla.ac.uk:5432/m_19_2175499m";
private static final String USER = "m_19_2175499m";
private static final String PASS = "<PASSWORD>";
private Connection connection = null;
// Database Connection parameters.
private String url;
private String user;
private String pass;
/**
* Database constructor.
*
* @param url database url
* @param user database username
* @param pass database password
*/
public Database(String url, String user, String pass) {
this.url = url;
this.user = user;
this.pass = pass;
}
/**
* Default database constructor for TopTrumps.
*/
public Database() {
this(URL, USER, PASS);
}
/**
* Getter for the database connection.
*
* @return the database connection
*/
protected Connection getConnection() {
return connection;
}
/**
* This methods sets up a connection to the PostgreSQL database. It needs to be run prior to any
* other methods.
*/
public void connect() throws SQLException {
// Get connection.
connection = DriverManager.getConnection(url, user, pass);
// System.out.println("Connected to database.");
}
/**
* This method closes the connection to the PostgreSQL database. It needs to be run after a
* code-user has finished with the Database class.
*/
public void disconnect() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* This method uploads the persistent game statistics to the PostgreSQL database.
*
* @param draws the number of draws in the game
* @param rounds the number of rounds in the game
* @param winner the winner of the game
* @param players an array holding all of the players in the game
*/
public void uploadGameStats(int draws, int rounds, String winner, Player[] players) {
try {
// Create statement.
Statement statement = connection.createStatement();
// Default gid for first game.
int gid = 1;
// Get max gid up to now from the database
// and make the gid variable larger by 1
String sqlString = "SELECT max(gid) FROM game";
ResultSet result = statement.executeQuery(sqlString);
if (result.next()) {
gid = result.getInt("max") + 1;
}
// Add a statement to update the game relation in the statement batch.
sqlString = "INSERT INTO game(gid,draws,rounds,winner) VALUES (" + gid + "," + draws
+ "," + rounds + ",'" + winner + "'); ";
statement.addBatch(sqlString);
// Add statements to update the rounds_won relation in the statement batch.
for (Player player : players) {
sqlString = "INSERT INTO rounds_won(gid,player,r_won) VALUES (" + gid + ",'"
+ player.toString() + "'," + player.getRoundsWon() + "); ";
statement.addBatch(sqlString);
}
statement.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Method creates an object that contains the retrieved overall game stats (5 metrics)
*
* @return object containing stats
*/
public RetrievedGameStatistics retrieveGameStats() {
RetrievedGameStatistics retrievedGameStatistics = null;
try {
int gamesPlayed = 0;
int aiWins = 0;
int userWins = 0;
int maxRounds = 0;
double avgDraws = 0;
Statement statement = connection.createStatement();
// Obtains the number of games played overall
String sqlStringMaxGid = "SELECT max(gid) FROM game";
ResultSet result = statement.executeQuery(sqlStringMaxGid);
if (result.next()) {
gamesPlayed = result.getInt("max");
}
// Obtains the number of games won by AIs
String sqlStringAIWins = "select count(winner) from game where winner!='USER' ";
result = statement.executeQuery(sqlStringAIWins);
if (result.next()) {
aiWins = result.getInt("count");
}
// Obtains the number of games won by the human user
String sqlStringUserWins = "select count(winner) from game where winner='USER'";
result = statement.executeQuery(sqlStringUserWins);
if (result.next()) {
userWins = result.getInt("count");
}
// Obtains the average draw number
String sqlStringAvgDraws = "select avg(draws) from game";
result = statement.executeQuery(sqlStringAvgDraws);
if (result.next()) {
avgDraws = result.getDouble("avg");
}
// Obtains the max number of rounds
String sqlStringMaxRounds = "select max(rounds) from game";
result = statement.executeQuery(sqlStringMaxRounds);
if (result.next()) {
maxRounds = result.getInt("max");
}
retrievedGameStatistics =
new RetrievedGameStatistics(gamesPlayed, aiWins, userWins, avgDraws, maxRounds);
} catch (SQLException e) {
e.printStackTrace();
}
return retrievedGameStatistics;
}
}
<file_sep>package model;
/**
* Represents the attributes of the cards in the game.
*/
public class Attribute implements Comparable<Attribute> {
//Fields.
protected String name;
protected int value;
/**
* Constructor.
* @param name name
* @param value value
*/
public Attribute(String name, int value) {
this.name = name;
this.value = value;
}
//Getters.
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
/**
* compareTo
* @param other other attribute
* @return attribute comparison integer
*/
@Override
public int compareTo(Attribute other) {
return this.getValue() - other.getValue();
}
/**
* toString
* @return name: value
*/
@Override
public String toString() {
return String.format("%s: %d", name, value);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>Card.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">Top Trumps Application Project</a> > <a href="index.source.html" class="el_package">model</a> > <span class="el_source">Card.java</span></div><h1>Card.java</h1><pre class="source lang-java linenums">package model;
import commandline.utils.ListUtility;
import java.util.ArrayList;
/**
* Represents the cards in the game.
*/
public class Card {
//Fields.
protected String name;
<span class="fc" id="L14"> protected ArrayList<Attribute> attributeList = new ArrayList<Attribute>();</span>
/**
* Constructor.
* @param name name of card
*/
<span class="fc" id="L20"> public Card(String name) {</span>
<span class="pc bpc" id="L21" title="1 of 4 branches missed."> if ("".equals(name) || (name == null)) {</span>
<span class="fc" id="L22"> throw new IllegalArgumentException("No empty names allowed");</span>
}
<span class="fc" id="L24"> this.name = name;</span>
<span class="fc" id="L25"> }</span>
/**
* Adds an attribute to the card.
* @param attribute
*/
public void add(Attribute attribute) {
<span class="fc" id="L32"> this.attributeList.add(attribute);</span>
<span class="fc" id="L33"> }</span>
/**
* toString
* @return Card name: name
* bullet list of attributes
*/
@Override
public String toString() {
<span class="fc" id="L42"> String attributeString = new ListUtility(attributeList).getBulletList();</span>
<span class="fc" id="L43"> return String.format("Card name: %s\n%s", name, attributeString);</span>
}
/**
* Return the value of the attribute in the card
* with the same name as the name of the passed attribute.
* @param givenAttribute
* @return value of attribute of the same type
*/
public int getValue(Attribute givenAttribute) {
<span class="fc" id="L53"> String givenAttributeName = givenAttribute.getName();</span>
<span class="pc bpc" id="L54" title="1 of 2 branches missed."> for (Attribute attribute : attributeList) {</span>
<span class="pc bpc" id="L55" title="1 of 2 branches missed."> if (attribute.getName().equals(givenAttributeName)) {</span>
<span class="fc" id="L56"> return attribute.getValue();</span>
}
}
<span class="nc" id="L59"> return 0;</span>
}
/**
* Return the i'th attribute
* @param i
* @return
*/
public Attribute getAttribute(int i) {
<span class="fc" id="L68"> return this.attributeList.get(i);</span>
}
//Getters.
public ArrayList<Attribute> getAttributes() {
<span class="fc" id="L74"> return this.attributeList;</span>
}
public String getName() {
<span class="fc" id="L78"> return this.name;</span>
}
}
</pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.5.201910111838</span></div></body></html><file_sep># Top Trumps
## University of Glasgow MSc IT+ Team Project
[](https://app.codacy.com/gh/shkembe-chorba/MScIT_TeamProject?utm_source=github.com&utm_medium=referral&utm_content=shkembe-chorba/MScIT_TeamProject&utm_campaign=Badge_Grade_Settings)
This project was created as part of the IT+ programmes at the University of Glasgow, which include Software Development, Information Technology, and Information Security.
The goal of the project was to design, implement, and test a small but reasonably complex software system in a self-organised team of 5 students. The project was an opportunity to put into practice skills learned on the Programming and Database Theory and Applications courses. It also contained various developmental aspects, such as:
- Understanding and using previously unseen technologies (such as [Java's Dropwizard framework](https://www.dropwizard.io/en/latest/) and the [Maven build tools](https://maven.apache.org/)).
- Learning and applying previously unseen project management methodologies (specifically, the [Scrum framework](https://en.wikipedia.org/wiki/Scrum_(software_development))).
Further information can be found in the accompanying documentation:
- The [project specification](Project%20Specification.pdf) provided by the university.
- The [final report](Report.pdf) produced by the team.
- JavaDoc comments throughout the source code.
<file_sep>package model;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Savepoint;
import java.sql.Statement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Database tests
*/
class DatabaseTest {
private Database database = new Database();
private Connection conn;
private Savepoint savepoint;
private Player user;
private Player ai1;
private Player ai2;
private Player ai3;
private Player ai4;
private Player[] players;
@BeforeEach
void setUp() throws Exception {
// Connect to database.
database.connect();
// Get the database connection.
conn = database.getConnection();
// Turn off autoCommit for test.
conn.setAutoCommit(false);
// Set a savepoint to roll back to after test.
savepoint = conn.setSavepoint("Savepoint1");
// Create statement.
Statement statement = conn.createStatement();
// Empty rounds_won relation for test.
String sqlString = "delete from rounds_won;";
statement.addBatch(sqlString);
// Empty game relation for test.
sqlString = "delete from game;";
statement.addBatch(sqlString);
statement.executeBatch();
// Set up mock players for test.
user = mock(Player.class);
ai1 = mock(Player.class);
ai2 = mock(Player.class);
ai3 = mock(Player.class);
ai4 = mock(Player.class);
// Set up player array for test.
players = new Player[] {user, ai1, ai2, ai3, ai4};
// Set up names of players.
when(user.toString()).thenReturn("USER");
when(ai1.toString()).thenReturn("AI1");
when(ai2.toString()).thenReturn("AI2");
when(ai3.toString()).thenReturn("AI3");
when(ai4.toString()).thenReturn("AI4");
// Set the roundsWon for the players in the first game for the test.
when(user.getRoundsWon()).thenReturn(2);
when(ai1.getRoundsWon()).thenReturn(8);
when(ai2.getRoundsWon()).thenReturn(3);
when(ai3.getRoundsWon()).thenReturn(3);
when(ai4.getRoundsWon()).thenReturn(4);
// Upload the first game to the database.
database.uploadGameStats(2, 20, "AI1", players);
// Set the roundsWon for the players in the second game for the test.
when(user.getRoundsWon()).thenReturn(5);
when(ai1.getRoundsWon()).thenReturn(3);
when(ai2.getRoundsWon()).thenReturn(2);
when(ai3.getRoundsWon()).thenReturn(3);
when(ai4.getRoundsWon()).thenReturn(2);
// Upload the second game to the database.
database.uploadGameStats(3, 15, "USER", players);
}
@AfterEach
void tearDown() throws Exception {
// Roll back to savepoint1.
conn.rollback(savepoint);
// Disconnect from database.
database.disconnect();
}
/**
* @throws Exception this is done because if we do a try-catch block our test reports a false
* positive when an exception is caught. An alternative to the throws
* exception would be an Assert.fail() in the catch block.
*/
@Test
@DisplayName("Check if the game statistics are uploaded correctly to the database.")
void uploadGameStats() throws Exception {
// Create statement.
Statement statement = conn.createStatement();
// Set up the expected game relation as a String.
String game_expected = "1 2 20 AI1\n" + "2 3 15 USER\n";
// Set up the expected rounds_won relation as a String.
String rounds_won_expected =
"1 USER 2\n" + "1 AI1 8\n" + "1 AI2 3\n" + "1 AI3 3\n" + "1 AI4 4\n" + "2 USER 5\n"
+ "2 AI1 3\n" + "2 AI2 2\n" + "2 AI3 3\n" + "2 AI4 2\n";
// Get the game relation from the database as a String.
String game = "";
ResultSet resultSet = statement.executeQuery("SELECT * FROM game");
while (resultSet.next()) {
game += resultSet.getString("gid") + " " + resultSet.getString("draws") + " "
+ resultSet.getString("rounds") + " " + resultSet.getString("winner") + "\n";
}
// Get the rounds_won relation from the database as a String.
String rounds_won = "";
resultSet = statement.executeQuery("SELECT * FROM rounds_won");
while (resultSet.next()) {
rounds_won += resultSet.getString("gid") + " " + resultSet.getString("player") + " "
+ resultSet.getString("r_won") + "\n";
}
// Make Strings for the expected data and the data from the database.
String data = game + rounds_won;
String data_expected = game_expected + rounds_won_expected;
// Compare the data from the database to the expected data.
assertEquals(data_expected, data);
}
/**
* @throws Exception this is done because if we do a try-catch block our test reports a false
* positive when an exception is caught. An alternative to the throws
* exception would be an Assert.fail() in the catch block.
*/
@Test
@DisplayName("Check if the returned game statistics are as expected.")
void checkReturnedGameStats() throws Exception {
// Set the roundsWon for the players in the second game for the test.
when(user.getRoundsWon()).thenReturn(7);
when(ai1.getRoundsWon()).thenReturn(1);
when(ai2.getRoundsWon()).thenReturn(2);
when(ai3.getRoundsWon()).thenReturn(3);
when(ai4.getRoundsWon()).thenReturn(0);
// Upload the third game to the database.
database.uploadGameStats(5, 13, "AI3", players);
final RetrievedGameStatistics expectedStatistics =
new RetrievedGameStatistics(3, 2, 1, 3.333, 20);
final RetrievedGameStatistics returnedStatistics = database.retrieveGameStats();
assertEquals(expectedStatistics.getAvgDraws(), returnedStatistics.getAvgDraws(), 0.01); // 0.01
// is
// the
// error
// margin
assertEquals(expectedStatistics.getGamesWonByAi(), returnedStatistics.getGamesWonByAi());
assertEquals(expectedStatistics.getGamesWonByUser(),
returnedStatistics.getGamesWonByUser());
assertEquals(expectedStatistics.getMaxRounds(), returnedStatistics.getMaxRounds());
assertEquals(expectedStatistics.getTotalGamesPlayed(),
returnedStatistics.getTotalGamesPlayed());
}
}
<file_sep>package model;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.util.List;
/**
* Pile tests
*/
@Nested
class GameModelTest {
private static final String TEST_RESOURCE_DIRECTORY = "src/test/resources/commandline/model";
// Our test deck is 2 cards
private static final String CARD_DECK_2 =
new File(TEST_RESOURCE_DIRECTORY, "cardDeckTwo.txt").toString();
private static final String CARD_DECK_10 =
new File(TEST_RESOURCE_DIRECTORY, "cardDeckTen.txt").toString();
private static final String CARD_DECK_10_SAME_CARDS =
new File(TEST_RESOURCE_DIRECTORY, "cardDeckTenDuplicates.txt").toString();
private static final String CARD_DECK_40 =
new File(TEST_RESOURCE_DIRECTORY, "cardDeckForty.txt").toString();
@Test
void test() {
}
/**
* Validation Tests
*/
@DisplayName("Constructor and Reset")
@Nested
public class ConstructorAndReset {
@DisplayName("Reads in a deck and assigns cards to players and communal pile")
@Test
public void assignsCardsCorrectly() {
int numAIPlayers = 2;
GameModel model = new GameModel(CARD_DECK_10, numAIPlayers);
List<Player> listPlayer = model.getPlayersInGame();
for (Player player : listPlayer) {
int totalHandSize = player.getRemainingDeckSize() + 1;
assertEquals(3, totalHandSize, "Player deck sizes not as expected");
}
assertEquals(1, model.getCommunalPileSize(), "Communal pile size not as expected");
}
@DisplayName("Players assigned different cards")
@Test
public void assignsDifferentCards() {
int numAIPlayers = 1;
GameModel model = new GameModel(CARD_DECK_2, numAIPlayers);
List<Player> listPlayer = model.getPlayersInGame();
Player p1 = listPlayer.get(0);
Player p2 = listPlayer.get(1);
assertNotEquals(p1.peekCard().toString(), p2.peekCard().toString());
}
}
@Nested
public class CommunalPile {
@DisplayName("Communal Pile increments after a draw")
@Test
void communalPileIncrementsAfterDraw() {
int numAIPlayers = 1;
GameModel model = new GameModel(CARD_DECK_10_SAME_CARDS, numAIPlayers);
Attribute chosenAttribute = model.getActivePlayer().peekCard().getAttribute(0);
model.playRoundWithAttribute(chosenAttribute);
// Player plus AI card
assertEquals(2, model.getCommunalPileSize());
model.playRoundWithAttribute(chosenAttribute);
// Player plus AI card x2
assertEquals(4, model.getCommunalPileSize());
}
@DisplayName("Communal Pile does not increment when no draw is possible")
@Test
void communalPileDoesNotIncreaseAfterWin() {
int numAIPlayers = 1;
// Deck cards are guaranteed to have different attributes.
GameModel model = new GameModel(CARD_DECK_2, numAIPlayers);
Attribute chosenAttribute = model.getActivePlayer().peekCard().getAttribute(0);
model.playRoundWithAttribute(chosenAttribute);
assertEquals(0, model.getCommunalPileSize());
}
@DisplayName("Communal Pile empties after a draw.")
@Test
void communalPileResetAfterWin() {
int numAIPlayers = 3;
GameModel model = new GameModel(CARD_DECK_40, numAIPlayers);
// Play rounds until there is a draw
while (model.getDraws() < 1) {
playRound(model);
if (model.checkForWinner() != null) {
model.reset();
}
}
// After a draw, the communal pile should have cards.
assertTrue(model.getCommunalPileSize() > 0);
// Play until there is a win.
do {
playRound(model);
} while (model.getDraws() != 1);
// THEN ASSERT THAT THE COMMUNAL PILE SIZE IS 0
assertEquals(0, model.getCommunalPileSize());
}
private void playRound(GameModel model) {
Player activePlayer = model.getActivePlayer();
Card activeCard = activePlayer.peekCard();
Attribute chosenAttribute = activeCard.getAttribute(0);
model.playRoundWithAttribute(chosenAttribute);
model.checkToEliminate();
}
}
}
<file_sep>package model;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
* AIPlayer tests
*/
public class AIPlayerTest {
// Define potential attributes
final static Attribute ATTRIBUTE_LOW_VALUE = new Attribute("Strength", 1);
final static Attribute ATTRIBUTE_HIGH_VALUE = new Attribute("Stamina", 20);
final static Attribute ATTRIBUTE_MID_VALUE = new Attribute("Money", 4);
final static Attribute[] ATTRIBUTE_ARRAY =
{ATTRIBUTE_HIGH_VALUE, ATTRIBUTE_MID_VALUE, ATTRIBUTE_LOW_VALUE};
// The pile for testing
static Pile testPile;
/**
* Sets up the TEST_PILE
*/
@BeforeAll
static void setupTestItems() {
// Create a test card
Card card = new Card("Test");
for (Attribute attribute : ATTRIBUTE_ARRAY) {
card.add(attribute);
}
// Create a test pile with the card
Pile pile = new Pile();
pile.add(card);
// Set the test pile
testPile = pile;
}
@Nested
@DisplayName("chooseAttribute()")
class ChooseAttribute {
/*
* Validation Tests
*/
@Test
@DisplayName("AIPlayer makes the best choice and returns attribute")
public void chooseCorrectAttribute() {
// creates new AIPlayer
AIPlayer testAIPlayer = new AIPlayer("ai");
// adds the card to pile of the AI Player
testAIPlayer.addToDeck(testPile);
// expects attribute with highest associated value
assertEquals(ATTRIBUTE_HIGH_VALUE, testAIPlayer.chooseAttribute());
}
}
}
<file_sep>package commandline.view;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* GlobalCommand tests
*/
public class GlobalCommandTest {
@DisplayName("Constructor")
@Nested
public class Constructor {
/*
* Defect Tests
*/
@DisplayName("Throws if not one word")
@ParameterizedTest
@ValueSource(strings = {"", "test test"})
public void throwsIfInvalidCommand(String command) {
assertThrows(IllegalArgumentException.class, () -> {
new GlobalCommand(command);
});
}
@DisplayName("Accepts one word commands")
@Test
public void acceptsValidCommand() {
new GlobalCommand("test");
}
}
@DisplayName("add/remove/notify GlobalCommandListener")
@Nested
public class Listeners {
/*
* Validation Tests
*/
@DisplayName("Listener can be notified")
@Test
public void globalCommandInputNotifiesListeners() {
GlobalCommandListenerTest gcl = new GlobalCommandListenerTest();
GlobalCommand gc = new GlobalCommand("Test");
assertFalse(gcl.triggered);
gc.addCommandListener(gcl);
gc.notifyCommandListeners();
assertTrue(gcl.triggered);
}
@DisplayName("Listener can be removed and is not notified")
@Test
public void canRemoveGlobalCommandListeners() {
GlobalCommandListenerTest gcl = new GlobalCommandListenerTest();
GlobalCommand gc = new GlobalCommand("Test");
assertFalse(gcl.triggered);
gc.addCommandListener(gcl);
gc.removeCommandListener(gcl);
gc.notifyCommandListeners();
assertFalse(gcl.triggered);
}
}
@DisplayName("equals()")
@Nested
public class Equals {
/*
* Validation Tests
*/
@DisplayName("Equals is true for same command")
@Test
public void equalsWhenCommandIsSame() {
GlobalCommand gc1 = new GlobalCommand("Test");
GlobalCommand gc2 = new GlobalCommand("Test", "But with a description");
assertTrue(gc1.equals(gc2));
}
@DisplayName("Equals is false for different commands")
@Test
public void notEqualsWhenCommandIsDifferent() {
GlobalCommand gc1 = new GlobalCommand("Test", "description equal");
GlobalCommand gc2 = new GlobalCommand("Test2", "description equal");
assertFalse(gc1.equals(gc2));
}
}
@DisplayName("toString()")
@Nested
public class ToString {
/*
* Validation Tests
*/
@DisplayName("Displays expected toString() format")
@Test
public void toStringAsExpected() {
GlobalCommand gc1 = new GlobalCommand("Test");
GlobalCommand gc2 = new GlobalCommand("Test", "But with a description");
assertEquals("Test", gc1.toString());
assertEquals("Test - But with a description", gc2.toString());
}
}
}
<file_sep>package commandline.utils;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
/**
* Sets up a Logger which is enabled as long as the object remains in scope. Usual use will be to
* call the static method Logger.log(message), which will output to the target destination file.
*
* This class aims to encapsulate a lot of the java util Logger setup.
*/
public class Logger {
// The global logger name for fetching from a singleton using a static method.
public static final String LOGGER_NAME = "commandline";
// The string which seperates each log.
public static final String LOGGER_DIVIDER_STRING = "--------";
private java.util.logging.Logger javaLogger;
private String outputFilepath;
/**
* Creates a logger object which will remain active as long as it is in scope. Used within
* the main method to ensure it is not garbage collected.
*
* @param outputFilepath The target logfile destination path.
*/
public Logger(String outputFilepath) {
// Remove default logging behaviour which outputs to System.err
LogManager.getLogManager().reset();
// Store this, so it is inside the object to prevent it being garbage collected
javaLogger = java.util.logging.Logger.getLogger(LOGGER_NAME);
this.outputFilepath = outputFilepath;
}
/**
* Creates the target log file and enables printing to it using the Logger static methods.
*
* @throws SecurityException When there is a security exception while creating the file.
* @throws IOException When there is a filesystem problem while creating the file.
*/
public void enable() throws SecurityException, IOException {
Handler loggerHandler = new FileHandler(outputFilepath);
// The default format for messages is to append LOGGER_DIVIDER_STRING
// and new lines after each log.
loggerHandler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return String.format("%s\n%s\n", record.getMessage(),
LOGGER_DIVIDER_STRING);
}
});
javaLogger.addHandler(loggerHandler);
javaLogger.setLevel(java.util.logging.Level.INFO);
}
/**
* A static method which outputs a log to the target log file. This is static so it can be
* used in many different classes while there is the 'master object' within the application
* scope.
*
* @param logMessage The message to include in the log
*/
public static void log(String logMessage) {
java.util.logging.Logger.getLogger(LOGGER_NAME).info(logMessage);
}
/**
* A static method which outputs a log to the target log file. This is static so it can be
* used in many different classes while there is the 'master object' within the application
* scope.
*
* @param headerMessage A heading to include above the log
* @param logMessage The body of the log message
*/
public static void log(String headerMessage, String logMessage) {
log(String.format("%s\n\n%s", headerMessage, logMessage));
}
}
<file_sep>package commandline.view;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import commandline.IOStreamTest;
public class CommandLineViewTest extends IOStreamTest {
@DisplayName("display...() methods")
@Nested
public class DisplayMethods {
@DisplayName("displayMessage outputs string with new line")
@Test
public void displayMessageOutputsNewLine() {
CommandLineView view = new CommandLineView();
view.displayMessage("Output message");
assertEquals("Output message\n", getOut());
}
@DisplayName("display...List finishes with just one new line")
@Test
public void displayListOutputsWithOnlyOneNewLine() {
CommandLineView view = new CommandLineView();
List<String> testList = Arrays.asList(new String[] {"a", "b", "c"});
view.displayBulletList(testList);
assertFalse(getOut().endsWith("\n\n"));
view.displayIndentedList(testList);
assertFalse(getOut().endsWith("\n\n"));
}
@DisplayName("displayDivider seperates messages with a new line")
@Test
public void displayDividerSeperatesWithNewLine() {
String expectedOutput =
"first\n" + CommandLineView.DEFAULT_MESSAGE_DIVIDER + "\nsecond\n";
CommandLineView view = new CommandLineView();
view.displayMessage("first");
view.displayDivider();
view.displayMessage("second");
assertEquals(expectedOutput, getOut());
}
}
@DisplayName("getUserInput()")
@Nested
public class GetUserInput {
@DisplayName("Returns input without new line")
@Test
public void returnsInputString() {
provideInput("This is the user input\n");
CommandLineView view = new CommandLineView();
assertEquals("This is the user input", view.getUserInput());
}
@DisplayName("Trims input of white space")
@Test
public void trimsWhitespace() {
provideInput(" Test \n");
CommandLineView view = new CommandLineView();
assertEquals("Test", view.getUserInput());
}
@DisplayName("Returns input which passes acceptance function")
@Test
public void passesAcceptanceFunction() {
provideInput("test\n");
CommandLineView view = new CommandLineView();
// Lambda function checks for 'one word'.
assertEquals("test", view.getUserInput(x -> x.matches("^\\w+$")));
}
@DisplayName("Reprompts user when input fails acceptance function")
@Test
public void repromptsWhenFailsAcceptanceFunction() {
provideInput("test test\n21\n\n");
CommandLineView view = new CommandLineView();
// Lambda function checks for 'empty'
assertEquals("", view.getUserInput(x -> "".matches(x)));
}
@DisplayName("Displays provided error message if it fails error condition")
@Test
public void displaysMessageIfInputFailsErrorCondition() {
provideInput("test test\ntest\n");
CommandLineView view = new CommandLineView();
// Lambda function checks for 'one word'
view.getUserInput(x -> x.matches("^\\w+$"), "Does not match one word.");
assertTrue(getOut().contains("Does not match one word.\n"));
}
}
@DisplayName("getUserSelection() / getUserSelectionIndex()")
@Nested
public class GetUserSelection {
@DisplayName("Fails when passed an empty list")
@Test
public void failsWhenPassedEmptyList() {
List<String> list = Arrays.asList(new String[] {});
CommandLineView view = new CommandLineView();
assertThrows(IllegalArgumentException.class, () -> view.getUserSelectionIndex(list));
}
@DisplayName("Returns list index from user selection")
@Test
public void returnsListIndexFromUserSelection() {
provideInput("3\n");
List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});
CommandLineView view = new CommandLineView();
// Note, user selection is i+1
assertEquals(2, view.getUserSelectionIndex(list));
}
@DisplayName("Repeats prompt until valid range index is given")
@ParameterizedTest
@ValueSource(strings = {"5\n", "\n", "cow\n", "0\n", "-1\n"})
public void repeatsIfGivenInvalidRange(String invalidInput) {
provideInput(invalidInput + "1\n"); // Add valid input for 2nd prompt
List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});
CommandLineView view = new CommandLineView();
assertEquals(1, view.getUserSelection(list));
}
@DisplayName("Displays error message on invalid user input")
@ParameterizedTest
// This test gets its provider from the source below. This allows different arrays to be
// tested (to check the length in the message) is correct.
@MethodSource("commandline.view.ArrayProviderTest#stringArrayProvider")
public void displaysErrorOnInvalidInput(String[] input) {
provideInput("wrong\n" + "1\n"); // 1 is always a valid value
String expectedErrorMessage = "Enter a number between 1-" + input.length + ".\n";
CommandLineView view = new CommandLineView();
view.getUserSelectionIndex(Arrays.asList(input)); // Convert array to list.
assertTrue(getOut().contains(expectedErrorMessage));
}
}
@DisplayName("Global commands")
@Nested
public class GlobalCommands {
@DisplayName("Throws for repeated global commands")
@Test
public void doesNotAcceptRepeatedGlobalCommands() {
GlobalCommand gc1 = new GlobalCommand("quit");
GlobalCommand gc2 = new GlobalCommand("quit", "I should throw");
CommandLineView view = new CommandLineView();
view.addGlobalCommand(gc1);
assertThrows(IllegalArgumentException.class, () -> view.addGlobalCommand(gc2));
}
// Private class for test below
@DisplayName("Inputing a global command notifies listeners")
@Test
public void globalCommandInputNotifiesListeners() {
provideInput("quit\n\n");
GlobalCommandListenerTest gcl = new GlobalCommandListenerTest();
GlobalCommand gc = new GlobalCommand("quit");
gc.addCommandListener(gcl);
CommandLineView view = new CommandLineView();
view.addGlobalCommand(gc);
view.getUserInput();
assertTrue(gcl.triggered);
}
@DisplayName("Not inputting a global command does not notify listeners")
@Test
public void noGlobalCommandDoesNotAffectListeners() {
provideInput("x\n\n");
GlobalCommandListenerTest gcl = new GlobalCommandListenerTest();
GlobalCommand gc = new GlobalCommand("quit");
gc.addCommandListener(gcl);
CommandLineView view = new CommandLineView();
view.addGlobalCommand(gc);
view.getUserInput();
assertFalse(gcl.triggered);
}
}
}
|
3e00acfdbebaeea76036b266b0797b0c03638a35
|
[
"HTML",
"JavaScript",
"Markdown",
"Maven POM",
"Java"
] | 20 |
Maven POM
|
shkembe-chorba/MScIT_TeamProject
|
81c5ba54acb44f7cf5437b36ba139e8b6d0228f0
|
367da4194f3ac41d3b426e93419d248dcaabb6e8
|
refs/heads/master
|
<repo_name>endy21osu/jgordon-conway-gol<file_sep>/src/com/icc/Main.java
package com.icc;
import com.icc.model.Population;
import com.icc.service.LifeHelper;
public class Main {
public static void main(String[] args) {
String fName = "C:\\data\\popState1.txt";
LifeHelper lf = new LifeHelper() ;
System.out.println(" args " + args.length);
if( args.length > 1 ){
System.out.println(" file " + args[0]);
fName = args[0];
}
Population pop = new Population(fName);
System.out.println("First pop");
pop.printPopulation();
for(int i = 0; i < 10; i++){
pop = lf.processGeneration(pop);
System.out.println("pop " + i);
pop.printPopulation();
try {
Thread.sleep(300); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
|
4fa3137db8fe14c5f3f53f2508548b628df1c03a
|
[
"Java"
] | 1 |
Java
|
endy21osu/jgordon-conway-gol
|
c11ee24d54e395353f6e36e9255557d89a822e7d
|
77c20cd66d75592b1376295e2e20aafbac882b20
|
refs/heads/master
|
<repo_name>jcredding/jcr-db<file_sep>/test/unit/psql_command_test.rb
require 'assert'
class JCR::DB::PsqlCommand
class BaseTest < Assert::Context
desc "JCR::DB::PsqlCommand"
setup do
@command = JCR::DB::PsqlCommand.new("CREATE DATABASE 'something'")
end
subject{ @command }
should "include JCR::DB::Command" do
assert_includes JCR::DB::Command, subject.class.included_modules
end
should "build the expected psql command" do
expected = "psql -c \"CREATE DATABASE 'something'\""
assert_equal expected, subject.to_s
end
end
class WithOptionsTest < BaseTest
desc "with options"
setup do
@command = JCR::DB::PsqlCommand.new("DROP DATABASE 'something'", {
:host => 'localhost',
:database => 'template1',
:user => 'root'
})
end
should "build the expected psql command" do
expected = "psql -h localhost -U root -d template1 -c " \
"\"DROP DATABASE 'something'\""
assert_equal expected, subject.to_s
end
end
end
<file_sep>/lib/jcr-db/tasks/pg.rb
require 'jcr-db/configuration'
require 'jcr-db/psql_command'
require 'jcr-db/sequel_migrate_command'
module JCR::DB::Tasks
module Pg
class Base
def initialize(*args)
@configuration = JCR::DB::Configuration.new(*args).tap do |config|
@host, @database, @user = [ config.host, config.database, config.user ]
end
end
def run
command = JCR::DB::PsqlCommand.new(@sql, {
:host => @host,
:database => @database,
:user => @user
})
puts "running:"
puts " #{command}"
command.run
puts command.success? ? command.stdout : command.stderr
end
end
class Create < JCR::DB::Tasks::Pg::Base
def initialize(*passed)
super
@database = 'template1'
@sql = "CREATE DATABASE #{@configuration.database}"
end
end
class Drop < JCR::DB::Tasks::Pg::Base
def initialize(*passed)
super
@database = 'template1'
@sql = "DROP DATABASE #{@configuration.database}"
end
end
class Migrate < JCR::DB::Tasks::Pg::Base
def initialize(options)
super(options[:config_file], options[:env])
@migrations_path = options[:migrations_path]
end
def run(direction)
command = JCR::DB::SequelMigrateCommand.new(direction, @migrations_path, {
:connection_string => @configuration.connection_string
})
puts "running:"
puts " #{command}"
command.run
puts command.success? ? command.stdout : command.stderr
end
end
end
end
<file_sep>/lib/jcr-db/sequel_migrate_command.rb
require 'jcr-db/command'
module JCR
module DB
class SequelMigrateCommand
include JCR::DB::Command
def initialize(direction, migrations_path, options = {})
switches = { '-m' => migrations_path }
if options[:connection_string]
switches['-t'] = options.delete(:connection_string)
end
if direction.to_s == 'down'
switches['-M'] = options[:version] || 0
end
cmd_string = "bundle exec sequel --echo"
switches_and_values = (switches.map do |(name, value)|
"#{name} #{value}"
end).sort.join(" ")
super("#{cmd_string} #{switches_and_values}")
end
end
end
end
<file_sep>/lib/jcr-db/command.rb
require 'scmd'
module JCR
module DB
module Command
attr_reader :scmd
def initialize(cmd_string)
@scmd = Scmd.new(cmd_string)
end
def to_s
@scmd.to_s
end
def method_missing(method, *args, &block)
@scmd.send(method, *args, &block)
end
def respond_to?(method)
super || @scmd.respond_to?(method)
end
end
end
end
<file_sep>/lib/jcr-db/psql_command.rb
require 'jcr-db/command'
module JCR
module DB
class PsqlCommand
include JCR::DB::Command
def initialize(sql_command, options = nil)
options ||= {}
options[:database] ||= options.delete(:on)
cmd_string = [
'psql',
("-h #{options[:host]}" if options[:host]),
("-U #{options[:user]}" if options[:user]),
("-d #{options[:database]}" if options[:database]),
"-c \"#{sql_command}\""
].compact.join(' ')
super(cmd_string)
end
end
end
end
<file_sep>/lib/jcr-db/configuration.rb
require 'ostruct'
module JCR
module DB
class Configuration
attr_reader :hash
def initialize(*args)
file_or_hash = args.shift || {}
configurations = if file_or_hash.kind_of?(Hash)
file_or_hash
else
YAML.load(File.read(file_or_hash.to_s))
end
@hash = args.empty? ? configurations : configurations[args.first]
@ostruct = OpenStruct.new(@hash)
end
def connection_string
@connection_string ||= begin
address = "#{adapter}://#{host}/#{database}"
query = [ ("user=#{user}" if user),
("password=#{password}" if password)
].compact.join('&')
[ address, (query if !query.empty?) ].compact.join('?')
end
end
def method_missing(method, *args, &block)
@ostruct.send(method, *args, &block)
end
def respond_to?(method)
super || @ostruct.respond_to?(method)
end
end
end
end
<file_sep>/test/unit/command_test.rb
require 'assert'
module JCR::DB::Command
class BaseTest < Assert::Context
desc "JCR::DB::Command"
setup do
@command_class = Class.new do
include JCR::DB::Command
end
@command = @command_class.new("ls -la")
end
subject{ @command }
attr_reader :scmd
should "proxy missing methods to the scmd class" do
subject.run
assert_equal subject.scmd.respond_to?(:run), subject.respond_to?(:run)
assert_equal subject.scmd.success?, subject.success?
end
end
end
<file_sep>/test/unit/configuration_test.rb
require 'assert'
class JCR::DB::Configuration
class BaseTest < Assert::Context
desc "JCR::DB::Configuration"
setup do
@hash = {
'adapter' => 'mongo',
'host' => 'localhost',
'database' => 'something'
}
@configuration = JCR::DB::Configuration.new(@hash)
end
subject{ @configuration }
should have_instance_methods :hash, :connection_string
should "set it's hash attribute to the passed in hash when no env var is passed" do
assert_equal @hash, subject.hash
end
end
class WithYAMLAndEnvTest < BaseTest
desc "when passed a yml file and env"
setup do
@expected = {
'adapter' => 'jdbc:postgresql',
'host' => 'test.local',
'database' => 'db_test'
}
config_file = File.join(ROOT, 'test', 'support', 'db.yml')
@configuration = JCR::DB::Configuration.new(config_file, 'test')
end
should "load the configuration from the YAML file and pull out the env key" do
@expected.each do |key, value|
assert_equal value, subject.hash[key]
end
end
should "return a valid connection string with #connection_string" do
expected = "#{@expected['adapter']}://#{@expected['host']}/#{@expected['database']}"
assert_equal expected, subject.connection_string
end
end
class WithYAMLAndNoEnvTest < BaseTest
desc "when passed a yml file and no env"
setup do
@expected = {
'adapter' => 'postgresql',
'host' => 'other.local',
'database' => 'db_other',
'user' => 'other'
}
config_file = File.join(ROOT, 'test', 'support', 'db.yml')
@configuration = JCR::DB::Configuration.new(config_file)
end
should "load the configuration from the YAML file and use it directly" do
@expected.each do |key, value|
assert_equal value, subject.hash[key]
end
end
should "return a valid connection string with the user as a query param with " \
"#connection_string" do
expected = "#{@expected['adapter']}://#{@expected['host']}/#{@expected['database']}"
expected += "?user=#{@expected['user']}"
assert_equal expected, subject.connection_string
end
end
class WithHashAndEnvTest < BaseTest
desc "when passed a hash and env"
setup do
@expected = {
'adapter' => 'mysql',
'host' => 'dev.local',
'database' => 'db_dev',
'user' => 'dev',
'password' => '<PASSWORD>'
}
hash = { 'production' => @expected }
@configuration = JCR::DB::Configuration.new(hash, 'production')
end
should "load the configuration from the value for the env key from the passed hash" do
@expected.each do |key, value|
assert_equal value, subject.hash[key]
end
end
should "return a valid connection string with the user and password as a query param with " \
"#connection_string" do
expected = "#{@expected['adapter']}://#{@expected['host']}/#{@expected['database']}"
expected += "?user=#{@expected['user']}&password=#{@expected['<PASSWORD>']}"
assert_equal expected, subject.connection_string
end
end
end
<file_sep>/Rakefile
require 'bundler/gem_tasks'
require 'assert/rake_tasks'
Assert::RakeTasks.install
<file_sep>/test/helper.rb
require 'jcr-db'
ROOT = File.expand_path("../..", __FILE__)
<file_sep>/test/unit/sequel_migrate_command_test.rb
require 'assert'
class JCR::DB::SequelMigrateCommand
class BaseTest < Assert::Context
desc "JCR::DB::SequelMigrateCommand"
setup do
@command = JCR::DB::SequelMigrateCommand.new(:up, '/path/to/migrations')
end
subject{ @command }
should "include JCR::DB::Command" do
assert_includes JCR::DB::Command, subject.class.included_modules
end
should "build the expected sequel command" do
expected = "bundle exec sequel --echo -m /path/to/migrations"
assert_equal expected, subject.to_s
end
end
class DownAndOptionsTest < BaseTest
desc "with direction down and options"
setup do
@command = JCR::DB::SequelMigrateCommand.new(:down, '/path/to/migrations', {
:connection_string => 'postgres://localhost/something'
})
end
should "build the expected sequel command" do
expected = "bundle exec sequel --echo -M 0 -m /path/to/migrations " \
"-t postgres://localhost/something"
assert_equal expected, subject.to_s
end
end
end
<file_sep>/lib/jcr-db.rb
require 'jcr-db/version'
module JCR
module DB
autoload 'Command', 'jcr-db/command'
autoload 'Configuration', 'jcr-db/configuration'
autoload 'PsqlCommand', 'jcr-db/psql_command'
autoload 'SequelMigrateCommand', 'jcr-db/sequel_migrate_command'
end
end
|
dd8c820dd2fc8b4b37b08da4fe0a5245d678fcc4
|
[
"Ruby"
] | 12 |
Ruby
|
jcredding/jcr-db
|
81a56e42c61d89a6c23ab080a36e9868a18e2e5a
|
9c0a833f25db3d65e96e1f00e6444e48ad6a6efd
|
refs/heads/master
|
<repo_name>LalitNM/StarLex<file_sep>/starlex/star/_init_.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 6 09:37:04 2020
@author: <NAME>
"""
class stellar:
#lumin- luminousity,rad-radius,mas-mass,st-surface temperature
def __init__(self,lumin,rad,mas,time,st):
self.lumin=lumin
self.rad=rad
self.mas=mas
self.time=time
self.st=st
star1=stellar('','','','','')<file_sep>/README.md
# StarLex
## Modelling stellar Evolution
The repository is in its initial phase, developers/astrophysicists required for active contributions.
visit [Contribution guidelines](https://github.com/STAC-IITMandi/StarLex/blob/master/CONTRIBUTING.md)
if you wish to contribute.
|
7e6ae1c0dc954157a8048b8f540544e16306dec7
|
[
"Markdown",
"Python"
] | 2 |
Python
|
LalitNM/StarLex
|
fd5538d657b6fbc9d0ab82cfa62814288b70a7b8
|
695103360d78c9438e30c6296d65fb84d0d7b990
|
refs/heads/master
|
<repo_name>arpit87/SB<file_sep>/src/my/b1701/SB/Activities/StartStrangerBuddyActivity.java
package my.b1701.SB.Activities;
import my.b1701.SB.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class StartStrangerBuddyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startActivity(new Intent().setClass(this, MyMapView.class));
// startActivity(intent);
}
}
|
68fa50f005a6f598cc358f4973280e5351f3f1fe
|
[
"Java"
] | 1 |
Java
|
arpit87/SB
|
ecabb4ff253da6a66ef1d0b83a3172e3015b5bf2
|
cc7bdcc1e2560df23b2b6da57431fee7be925d69
|
refs/heads/master
|
<repo_name>jesusmlg/disaster<file_sep>/app/Http/Controllers/FileController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \App\Models\File;
use \App\Models\Note;
use Illuminate\Support\Facades\Storage;
class FileController extends Controller
{
public function destroyNoteFile(Request $request,$note_id,$file_id)
{
$note = Note::find($note_id);
$file = File::find($file_id);
if(Storage::delete($file->url))
{
$note->files()->detach($file_id);
}
if($request->ajax())
{
$html = view('file._files-notes',['note' => $note])->render();
return response()->json(['message' => 'ok', 'html' => $html]);
}
}
}
<file_sep>/tests/Browser/CRUDNoteTest.php
<?php
namespace Tests\Browser;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class CRUDNoteTest extends DuskTestCase
{
/**
* A Dusk test example.
*
* @return void
*/
use DatabaseMigrations;
public function setUp()
{
parent::setUp();
$this->browse(function(Browser $browser){
$user = factory(\App\User::class)->create(['email' => "<EMAIL>",
'password' => <PASSWORD>('<PASSWORD>'),
'name' => 'MyTestUser']);
$browser->loginAs($user);
});
}
public function testCreateUpdateDeleteNote()
{
$this->browse(function(Browser $browser){
$browser->visit(route('note_new'))
->assertSee('New Note')
->type('@note-title', '')
->press('@note-save')
->assertDontSee('Edit Task')
->type('@note-title', 'Mi title')
->type('.note-editable', 'HOLA HOLA')
->press('@note-save')
->assertSee('Edit Note')
->assertValue('@note-title','Mi title')
->assertValue('@note-text','HOLA')
->type('@note-title', 'Mi title changed')
->type('.note-editable', 'ADIOS ADIOS')
->press('@note-save')
->assertValue('@note-title','Mi title changed')
->assertValue('@note-text','ADIOS')
->press('@note-delete')
->acceptDialog()
->assertSee('Total Files: 0');
});
}
}
<file_sep>/app/Models/Note.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class Note extends Model
{
protected $fillable = ['title','note'];
public function user()
{
return $this->belongsTo('App\User');
}
public function tags()
{
return $this->belongsToMany('\App\Models\Tag', 'notes_tags','note_id','tag_id');
}
public function files()
{
return $this->belongsToMany('\App\Models\File','notes_files','note_id','file_id');
}
public function users()
{
return $this->belongsToMany('\App\User','notes_users','note_id','user_id');
}
public static function search($txt)
{
// return DB::table('notes')
// ->leftJoin('notes_tags','notes.id','=','notes_tags.note_id')
// ->leftJoin('tags','tags.id','=','notes_tags.tag_id')
// ->leftJoin('notes_files','notes.id','=','notes_files.note_id')
// ->leftJoin('files','files.id','=','notes_files.file_id')
// ->where('notes.title','ilike','%'.$txt.'%')
// ->orWhere('tags.name','ilike','%'.$txt.'%')
// ->orWhere('files.url','ilike','%'.$txt.'%')
// ->orderBy('notes.created_at', 'desc')
// ->get();
$tags = explode(" ", $txt);
$notes = Note::select('notes.*')
->distinct()
->join('notes_users','notes.id', '=', 'notes_users.note_id')
->join('users','users.id', '=', 'notes_users.user_id')
->leftJoin('notes_tags','notes.id','=','notes_tags.note_id')
->leftJoin('tags','tags.id','=','notes_tags.tag_id')
->leftJoin('notes_files','notes.id','=','notes_files.note_id')
->leftJoin('files','files.id','=','notes_files.file_id')
->where('notes_users.user_id', '=', Auth::user()->id)
->where('notes.title','like','%'.$txt.'%')
->orWhere('files.url','like','%'.$txt.'%')
->orWhere('notes.note','like','%'.$txt.'%')
//->orWhere('tags.name','ilike','%'.$txt.'%')
->orWhere(function($query) use ($tags){
foreach($tags as $t) {
$query->orWhere('tags.name','like','%'.$t.'%');
}
}
)
->orderBy('notes.created_at', 'desc')
->paginate(20);
return $notes;
}
public static function searchByTag($tag)
{
$notes = Note::whereHas('tags', function($q) use ($tag){
$q->where('name', $tag);
})->whereHas('users', function($q) {
$q->where('id', Auth::user()->id);
})->orderBy('created_at', 'desc')->paginate(20);
return $notes;
}
public function getCreatedAtAttribute($value)
{
return \Carbon\Carbon::parse($value)->format('d-m-Y');
//return \Carbon\Carbon::createFromFormat('Y-m-d', $date)->format('m-d-Y');
}
public function getUpdatedAtAttribute($value)
{
return \Carbon\Carbon::parse($value)->format('d-m-Y');
//return \Carbon\Carbon::createFromFormat('Y-m-d', $date)->format('m-d-Y');
}
public function setDateAttribute($value)
{
$this->attributes['created_at'] = \Carbon\Carbon::parse($value)->format('Y-m-d');
}
public function getDateCarbon()
{
return \Carbon\Carbon::parse($this->attributes['created_at']);
}
public function getIconAttribute()
{
if ($this->files()->count()>0)
$img = $this->files()->first()->icon;
else
$img = 'images/icons/note.png';
return $img;
}
}
<file_sep>/tests/Unit/ExampleTest.php
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use \App\Models\Note;
use \App\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Console\Command;
class ExampleTest extends TestCase
{
use DatabaseMigrations;
/**
* A basic test example.
*
* @return void
*/
public function setUp()
{
parent::setUp();
\Artisan::call('migrate');
\Artisan::call('db:seed', ['--database' => 'sqlite_testing']);
}
public function testBasicTest()
{
$this->assertTrue(true);
}
public function testCreateNewNote()
{
$allUsersBefore = User::all()->count();
$user = factory(\App\User::class)->create(['email' => "<EMAIL>",
'password' => <PASSWORD>('<PASSWORD>'),
'name' => 'MyTestUser']);
$allUsersAfter= User::all()->count();
$this->assertEquals($allUsersBefore+1 , $allUsersAfter);
$note = new Note();
$notesBefore = Note::all()->count();
$note->title ="hola";
$note->note = "que tal";
$note->user_id = $user->id;
$note->save();
$this->assertEquals($notesBefore, Note::all()->count() -1 );
}
/**
* @dataProvider tagSearchProvider
*/
public function testSearchByTag($tag,$expected)
{
$this->actingAs(User::first());
$notes = Note::searchByTag($tag)->count();
$this->assertEquals($notes,$expected);
}
public function tagSearchProvider()
{
return [
'2018 tres' => ['2018',3],
'Mayo dos' => ['Mayo',2],
'Ticket uno' => ['Ticket',1]
];
}
}
<file_sep>/tests/Browser/RegisterUserTest.php
<?php
namespace tests\Browser;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class RegisterUserTest extends DuskTestCase
{
use DatabaseMigrations;
public function testRegisterUserRedirectToHome()
{
$this->browse(function (Browser $browser){
$browser->visit('/register')
->type('name', 'usertest')
->type('email', '<EMAIL>')
->type('password','<PASSWORD>')
->type('password_confirmation','<PASSWORD>')
->press('Register')
->assertPathIs('/home')
->assertSee('usertest')
->assertSee('Total Files: 0')
->clickLink('Logout')
->assertSee('Login');
});
}
}<file_sep>/app/Http/Controllers/NoteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \App\Models\Note;
use \App\Models\Tag;
use \App\Models\File;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use \App\Http\Requests\NotesRequest;
class NoteController extends Controller
{
public function new()
{
$note = new Note();
return view('note.new',['note' => $note]);
}
public function edit(Request $request,$id)
{
$note = Note::find($id);
return view('note.edit',['note' => $note]);
}
public function index(Request $request)
{
$lastTags = Tag::orderBy('created_at','desc')->take(20)->get();
$mostUsedTags = Tag::mostUsed()->take(20)->get();
$total = Note::whereHas('users',function($q){
$q->where('user_id', Auth::user()->id);
})->count();
if($request->view != "")
session(['view' => $request->view ]);
if($request->txt)
$notes = Note::search($request->txt);
elseif($request->tag)
$notes = Note::searchByTag($request->tag);
else
$notes = Note::whereHas('users', function($q) use ($request){
$q->where('id', Auth::user()->id);
})->orderBy('created_at', 'desc')->paginate(20);
return view('note.index',['notes'=> $notes, 'total' => $total, 'lastTags' => $lastTags, 'mostUsedTags' => $mostUsedTags]);
}
public function show($id)
{
$note = Note::find($id);
return view('note.show',['note' => $note]);
}
public function create(NotesRequest $request)
{
$note = new Note();
$note->fill(
$request->only('title','note')
);
$note->user_id = Auth::user()->id;
if($note->save())
{
$note->users()->save(Auth::user());
if($request->hasFile('attachments'))
$this->saveFiles($request,$note);
}
return redirect()->route('note_edit',['note' => $note]);
}
public function update(Request $request, $id)
{
$note = Note::find($id);
$note->fill(
$request->only('title','note')
);
if($note->save())
{
if($request->hasFile('attachments'))
$this->saveFiles($request,$note);
}
return redirect()->route('note_edit',['note' => $note]);
}
public function destroy($id)
{
$note = Note::find($id);
foreach ($note->files as $f)
{
Storage::delete($f->url);
}
Note::destroy($id);
return redirect()->route('note_index');
}
private function saveFiles(Request $request, $note)
{
$path = "/public/files/".Auth::user()->id."/".date('Y')."/". date('n');
foreach ($request->attachments as $attachment)
{
if($url = $attachment->storeAs($path,$attachment->getClientOriginalName()))
{
$file = \App\Models\File::create(['url' => $url]);
$note->files()->save($file);
}
}
}
}
<file_sep>/app/Http/Controllers/TagController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \App\Models\Tag;
use \App\Models\Note;
class TagController extends Controller
{
public function index(Request $request)
{
$tags = Tag::orderBy('name','asc')->paginate(100);
return view('tag.index',['tags' => $tags]);
}
public function create(Request $request)
{
$note = Note::find($request->note_id);
$tags = explode(",", $request->tag);
foreach ($tags as $t)
{
$tag = Tag::firstOrNew(['name' => $t]);
if(!$note->tags()->where('id',$tag->id)->exists())
{
if($note->tags()->save($tag))
session()->flash('message','Tag saved succesfully');
}
}
if($request->ajax())
{
$html = view('tag._tags-note',['note' => $note])->render();
return response()->json(['message' => 'ok', 'tag' => $tag->name, 'html' => $html]);
}
//return redirect()->route('note_show',['note' => $note]);
}
public function destroyNoteTag(Request $request,$note_id,$tag_id)
{
$note = Note::find($note_id);
$note->tags()->detach($tag_id);
if($request->ajax())
{
$html = view('tag._tags-note',['note' => $note])->render();
return response()->json(['message' => 'ok', 'html' => $html]);
}
}
public function list(Request $request)
{
if($request->ajax())
{
if($request->txt != "")
{
//$tags = Tag::where('name','ilike', ''.$request->txt.'%')->get();
$tags = Tag::whereNotIn('id',function($q) use ($request,&$find){
$q->select('tag_id')->from('notes_tags')->where('note_id', $request->note_id);
})
->where('name','like', ''.$request->txt.'%')
->get();
$html='<ul>';
$html.= '<li>'. $request->txt.'</li>';
foreach ($tags as $tag)
{
$html.='<li>'. $tag->name.'</li>';
}
$html.='</ul>';
}
else
{
$html = "";
}
return response()->json(['message' => 'ok', 'html' => $html]);
}
}
}
<file_sep>/app/Models/File.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
protected $fillable = ['url'];
public function notes()
{
return $this->belongsToMany('\App\Models\Note','notes_files');
}
public function getFilenameAttribute()
{
return basename($this->url);
}
public function publicPath()
{
return preg_replace('/public/', 'storage', $this->url, 1);
}
public function getPublicPath($value)
{
return preg_replace('/public/', 'storage', $this->url, 1);
}
public function getIconAttribute()
{
$path='images/icons/';
$file = $this->url;
$ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
switch ($ext) {
case 'doc':
case 'docx':
$img = 'doc_1.png';
break;
case 'xls':
case 'xlsx':
$img = 'excel.png';
break;
case 'jpg':
case 'jpeg':
case 'png':
case 'tiff':
case 'bmp':
$img = 'jpg.png';
break;
case 'gif':
$img = 'gif.png';
break;
case 'pdf':
$img = 'pdf.png';
break;
case "rar":
case "zip":
case "7z":
case "tar":
case "bzip":
$img = 'zip.png';
break;
default:
$img = 'txt_1.png';
break;
}
return $path.$img;
}
}
<file_sep>/public/js/functions.js
$(document).ready(function(){
var typingTimer;
var doneTypingInterval = 600;
$('.summernote').summernote({
height: 300,
});
$(document).on('click','#txt',function(e){
if(e.wich == 13)
$('form-search').submit();
});
$(document).on('click','.delete-tag',function(e){
e.preventDefault();
url = $(this).attr('data-url');
$.ajax({
url: url,
type:'delete',
dataType: 'json',
data: {
'_method': 'delete',
'_token': $('meta[name="csrf-token"]').attr('content')
},
success: function(data){
$("#note-tags").html(data.html);
},
error: function(data){
alert("error");
},
complete:function(data)
{
}
});
});
$(document).on('click','#btn-add-tag',function(e){
e.preventDefault();
var tag = $("#txt-tag").val();
var note = $("#note_id").val();
var data = { 'tag' : tag,
'note_id': note,
'_token': $('meta[name="csrf-token"]').attr('content')
};
$.ajax({
url: '/tag/create',
method: 'post',
dataType: 'json',
data: data,
success: function(data)
{
$("#note-tags").html(data.html);
},
error: function(data)
{
alert("Error");
},
complete: function(data)
{
}
});
});
$(document).on('click','.delete-file',function(e){
e.preventDefault();
url = $(this).attr('data-url');
//alert(url);
$.ajax({
url: url,
type:'delete',
dataType: 'json',
data: {
'_method': 'delete',
'_token': $('meta[name="csrf-token"]').attr('content')
},
success: function(data){
$("#note-files").html(data.html);
},
error: function(data){
alert("error");
},
complete:function(data)
{
}
});
});
$(document).on('input propertychange paste keyup','#txt-tag', function(){
$("#tag-list").html("Loading ...");
clearTimeout(typingTimer);
typingTimer = setTimeout(tagList, doneTypingInterval);
});
$(document).on('keydown','#txt-tag', function(){
clearTimeout(typingTimer);
});
function tagList()
{
var pos = $('#txt-tag').position();
$('#tag-list').css({'top': pos.top - 20, 'left': pos.left });
$('#tag-list').css('display', 'block');
//$("#tag-list").html('Loading ...');
$.ajax({
url: '/tag/list',
dataType: 'json',
data:
{
'txt' : $('#txt-tag').val(),
'note_id': $("#note_id").val()
},
method: 'get',
success: function(data)
{
$("#tag-list").html(data.html);
},
error: function(data)
{
$("#tag-list").html("");
alert("error");
}
});
}
$(document).on('click','#tag-list ul li',function(e){
var txt = $(this).html();
$('#txt-tag').val(txt);
$('#btn-add-tag' ).trigger("click");
$('#txt-tag').val('');
$('#tag-list').css('display', 'none')
});
$(document).on('click','.delete-user',function(e){
e.preventDefault();
url = $(this).attr('data-url');
$.ajax({
url: url,
type:'delete',
dataType: 'json',
data: {
'_method': 'delete',
'_token': $('meta[name="csrf-token"]').attr('content')
},
success: function(data){
$("#note-users").html(data.html);
},
error: function(data){
alert("error");
},
complete:function(data)
{
}
});
});
$(document).on('input propertychange paste keyup','#txt-user', function(){
$("#user-list").html("Loading ...");
clearTimeout(typingTimer);
typingTimer = setTimeout(userList, doneTypingInterval);
});
$(document).on('keydown','#txt-user', function(){
clearTimeout(typingTimer);
});
function userList()
{
var pos = $('#txt-user').position();
$('#user-list').css({'top': pos.top - 20, 'left': pos.left });
$('#user-list').css('display', 'block');
$.ajax({
url: '/user/list',
dataType: 'json',
data:
{
'txt' : $('#txt-user').val(),
'note_id': $("#note_id").val()
},
method: 'get',
success: function(data)
{
$("#user-list").html(data.html);
},
error: function(data)
{
alert("error");
}
});
}
$(document).on('click','#user-list ul li',function(e){
var user = $(this).attr('id');
var note = $("#note_id").val();
var data = { 'user_id' : user,
'note_id': note,
'_token': $('meta[name="csrf-token"]').attr('content')
};
$.ajax({
url: '/note/user/create',
method: 'post',
dataType: 'json',
data: data,
success: function(data)
{
$("#note-users").html(data.html);
},
error: function(data)
{
alert("Error");
},
complete: function(data)
{
$('#txt-user').val('');
$('#user-list').css('display', 'none')
}
});
});
});<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
Auth::routes();
Route::middleware('auth')->group(function()
{
Route::get('/', 'NoteController@index');
Route::get('/home', 'NoteController@index')->name('home');
Route::get('/notes','NoteController@index')->name('note_index');
Route::get('/note/new','NoteController@new')->name('note_new');
Route::get('/note/{id}/show','NoteController@show')->name('note_show');
Route::get('/note/{id}/edit','NoteController@edit')->name('note_edit');
Route::post('/note/create','NoteController@create')->name('note_create');
Route::post('/note/{id}/update','NoteController@update')->name('note_update');
Route::delete('note/{id}/destroy','NoteController@destroy')->name('note_destroy');
Route::delete('/note/{note_id}/tag/{tag_id}/destroy','TagController@destroyNoteTag')->name('note_tag_destroy');
Route::delete('/note/{note_id}/file/{file_id}/destroy','FileController@destroyNoteFile')->name('note_file_destroy');
Route::post('tag/create','TagController@create')->name('tag_create');
Route::post('/note/{id}/destroy','NoteController@destroy')->name('tag_destroy');
Route::get('/tags','TagController@index')->name('tag_index');
Route::get('/tag/list','TagController@list')->name('tag_list');
Route::delete('/note/{note_id}/user/{user_id}/destroy','UserController@destroyNoteUser')->name('note_user_destroy');
Route::get('/user/list','UserController@list')->name('user_list');
Route::post('/note/user/create', 'UserController@create')->name('user_note_create');
});
<file_sep>/app/Models/Tag.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $fillable = ['name'];
public function notes()
{
return $this->belongsToMany('Note', 'notes_tags');
}
public static function mostUsed()
{
return Tag::whereIn('id', function($q){
$q->select(\DB::raw('nt.tag_id from notes_tags nt group by nt.tag_id order by count(nt.note_id) desc'));
});
}
public function setAttributeName($value)
{
$this->attributes['name'] = strtolower($value);
}
}
<file_sep>/tests/Browser/firstPageTest.php
<?php
namespace Tests\Feature;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class FirstTestPageTest extends DuskTestCase
{
use DatabaseMigrations;
/**
* A basic browser test example.
*
* @return void
*/
public function testNoLoggedGoToLogin()
{
$this->browse(function (Browser $browser) {
$browser->visit('/login')
->assertSee('Login');
});
}
public function testOKloginRedirectToNotes()
{
$this->browse(function (Browser $browser){
$user = factory(\App\User::class)->create(['email' => "<EMAIL>",
'password' => <PASSWORD>('<PASSWORD>'),
'name' => 'MyTestUser']);
$browser->visit('/login')
->type('email',$user->email)
->type('password','<PASSWORD>')
->press('Login')
->assertPathIs('/notes')
->assertSee('MyTestUser')
->clickLink('Logout');
});
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use Faker\Generator as Faker;
use Faker\Factory as FakerFactory;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = FakerFactory::create();
array_map('unlink', glob(public_path('storage/files/seed/*')));
DB::table('users')->insert([
'name' => '<NAME>',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
]);
DB::table('users')->insert([
'name' => '<NAME>',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
]);
// for($i=0;$i<20;$i++)
// {
$note = factory(\App\Models\Note::class)->create();
// for($j=0;$j<3;$i++)
// {
// $note->tags()->save(factory(\App\Models\Tag::class)->create());
// }
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'Factura']));
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'Abril']));
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'2018']));
$note->users()->save(\App\User::first());
$note = factory(\App\Models\Note::class)->create();
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'Factura']));
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'Mayo']));
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'2018']));
$note->users()->save(\App\User::first());
$note = factory(\App\Models\Note::class)->create();
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'Ticket']));
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'Mayo']));
$note->tags()->save(factory(\App\Models\Tag::class)->create(['name'=>'2018']));
$note->users()->save(\App\User::first());
$note = factory(\App\Models\Note::class)->create([ 'title' => 'aaaaaaaaaaaaaaaaa afeaf afe af' ]);
$note->users()->save(\App\User::first());
// }
for($i=0; $i<20 ; $i++)
{
$note = factory(\App\Models\Note::class)->create();
$note->users()->save(\App\User::first());
}
$note = factory(\App\Models\Note::class)->create([ 'title' => 'eefaefa afsefa sda f124142 afeaf afe af' ]);
$note->users()->save(\App\User::first());
// factory(\App\Models\Tag::class,100)->create();
// $noteids = \App\Models\Note::pluck('id')->all();
// $tagids = \App\Models\Tag::pluck('id')->all();
// $userids = \App\User::pluck('id')->all();
// for ($i=0; $i < 100 ; $i++) {
// $note_id = $faker->randomElement($noteids);
// $tag_id = $faker->randomElement($tagids);
// $user_id = $faker->randomElement($tagids);
// $data = DB::table('notes_tags')->where('note_id', '=' ,$note_id)->where('tag_id','=' ,$tag_id)->first();
// if($data == null)
// {
// DB::table('notes_tags')->insert([
// 'note_id' => $note_id,
// 'tag_id' => $tag_id
// ]);
// }
// }
// for ($i=0; $i < 20; $i++) {
// //$note_id = $faker->randomElement($noteids);
// $note = DB::table('notes')->where('id', '=', $faker->randomElement($noteids))->first();
// $path = "storage/files/seed/";
// if(!file_exists(public_path($path)))
// mkdir(public_path($path),0777,true);
// $file = $faker->file(public_path('test'),public_path($path),false);
// $file_id = DB::table('files')->insertGetId(['url' => $path.$file]);
// DB::table('notes_files')->insert([
// 'note_id' => $note->id,
// 'file_id' => $file_id
// ]);
// }
}
}
<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \App\User;
use \App\Models\Note;
class UserController extends Controller
{
public function index(Request $request)
{
}
public function create(Request $request)
{
$note = Note::find($request->note_id);
if(!$note->users()->where('id',$request->user_id)->exists())
{
$user = User::find($request->user_id);
if($note->users()->save($user))
session()->flash('message','User added succesfully');
}
if($request->ajax())
{
$html = view('user._users-notes',['note' => $note])->render();
return response()->json(['message' => 'ok','email' => $user->email, 'html' => $html]);
}
}
public function destroyNoteUser(Request $request,$note_id,$user_id)
{
$note = Note::find($note_id);
$note->users()->detach($user_id);
if($request->ajax())
{
$html = view('user._users-notes',['note' => $note])->render();
return response()->json(['message' => 'ok', 'html' => $html]);
}
}
public function list(Request $request)
{
if($request->ajax())
{
if($request->txt != "")
{
$users = User::whereNotIn('id',function($q) use ($request){
$q->select('user_id')->from('notes_users')->where('note_id',$request->note_id);
})
->where(function($q) use ($request){
$q->where('name','like', '%'.$request->txt.'%');
$q->orWhere('email', 'like', '%'.$request->txt.'%');
})
->get();
$html='<ul>';
foreach ($users as $user)
{
$html.='<li id="'.$user->id.'">'. $user->name.'</li>';
}
$html.='</ul>';
}
else
{
$html = "";
}
return response()->json(['message' => 'ok', 'html' => $html]);
}
}
}
|
2de42884d56a358bd48ad91f291d0a98eefb31de
|
[
"JavaScript",
"PHP"
] | 14 |
PHP
|
jesusmlg/disaster
|
b56516c2392d5ca69a2c7728f3ce9f6adf177066
|
e67a18b10cc287311541884f4419f4f70e0bfbd9
|
refs/heads/master
|
<repo_name>MiDaZoLP/JumpnKill<file_sep>/src/com/MiDaZo/JumpnKill/commands/Cancel.java
package com.MiDaZo.JumpnKill.commands;
import org.bukkit.entity.Player;
import com.MiDaZo.JumpnKill.JumpnKill;
import com.MiDaZo.JumpnKill.config.Messages;
public class Cancel implements SubCommand {
private Messages msg;
public Cancel(JumpnKill plugin, Messages msg) {
this.plugin = plugin;
this.msg = msg;
}
@Override
public boolean onCommand(Player p, String[] args) {
String messageprefix = (String) msg.get("messages.prefix");
if(p.hasPermission("jnk.createlobbysign.cancel")) {
if(!plugin.SignPlayers.contains(p.getName())) {
p.sendMessage(messageprefix + "&4Du hast nicht '/jnk setsign' ausgeführt!");
} else {
plugin.SignPlayers.remove(p.getName());
p.sendMessage(messageprefix + msg.get("messages.canceled"));
}
}
return false;
}
private JumpnKill plugin;
}
<file_sep>/src/com/MiDaZo/JumpnKill/commands/SetSign.java
package com.MiDaZo.JumpnKill.commands;
import org.bukkit.entity.Player;
import com.MiDaZo.JumpnKill.JumpnKill;
import com.MiDaZo.JumpnKill.config.Messages;
public class SetSign implements SubCommand {
public SetSign(JumpnKill plugin, Messages msg) {
this.plugin = plugin;
this.msg = msg;
}
@Override
public boolean onCommand(Player p, String args[]) {
String messageprefix = (String) msg.get("messages.prefix");
if(!p.hasPermission("jnk.createlobbysign") && !p.isOp()) {
p.sendMessage(messageprefix + msg.get("messages.nopermission"));
return true;
} else {
p.sendMessage(messageprefix + msg.get("messages.needrightclick"));
plugin.SignPlayers.add(p.getName());
}
return false;
}
private JumpnKill plugin;
private Messages msg;
}
<file_sep>/src/com/MiDaZo/JumpnKill/Events/PlayerInteractListener.java
package com.MiDaZo.JumpnKill.Events;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import com.MiDaZo.JumpnKill.JumpnKill;
import com.MiDaZo.JumpnKill.config.Messages;
import com.MiDaZo.JumpnKill.config.Positions;
public class PlayerInteractListener implements Listener {
private Positions pos;
private Messages msg;
public PlayerInteractListener(JumpnKill plugin, Positions pos, Messages msg) {
this.plugin = plugin;
this.pos = pos;
this.msg = msg;
}
@EventHandler
public void onInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
String messageprefix = (String)msg.get("messages.prefix");
if(event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(event.getClickedBlock().getState() instanceof Sign) {
Sign s = (Sign)event.getClickedBlock().getState();
if(s.getLine(0).equalsIgnoreCase("[JNK]")) {
if(s.getLine(1).equalsIgnoreCase("Arena")) {
String arena = s.getLine(2);
if(pos.isSet("arenas." + arena + ".lobby.x") &&
pos.isSet("arenas." + arena + ".lobby.y") &&
pos.isSet("arenas." + arena + ".lobby.z") &&
pos.isSet("arenas." + arena + ".lobby.world") &&
pos.isSet("arenas." + arena + ".spawn.x") &&
pos.isSet("arenas." + arena + ".spawn.y") &&
pos.isSet("arenas." + arena + ".spawn.z") &&
pos.isSet("arenas." + arena + ".spawn.world")) {
} else {
p.sendMessage(messageprefix + "§4Die Arena hat einen Fehler oder exestiert nicht!");
}
}
}
}
}
}
private JumpnKill plugin;
}
<file_sep>/src/com/MiDaZo/JumpnKill/config/Messages.java
package com.MiDaZo.JumpnKill.config;
import java.io.File;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.MiDaZo.JumpnKill.JumpnKill;
public class Messages {
File f;
FileConfiguration fc;
private JumpnKill plugin;
public Messages(JumpnKill plugin) {
this.plugin = plugin;
manage();
}
@SuppressWarnings("static-access")
public void manage() {
f = new File(plugin.getDataFolder() + File.separator + "messages.yml");
fc = new YamlConfiguration().loadConfiguration(f);
fc.addDefault("messages.prefix", "&c[&4JNK&c]");
fc.addDefault("messages.nopermission", "&4Du hast keine Rechte, um dies zu tun!");
fc.addDefault("messages.signset", "&4Du hast erfolgreich ein Lobbyschild erstellt!");
fc.addDefault("messages.arenaset", "&4Du hast erfolgreich eine Arena gesetzt!");
fc.addDefault("messages.arenalobbyset", "&4Du hast erfolgreich den Spawn für %arena% gesetzt!");
fc.addDefault("messages.commandnotexist", "&4Dieses Kommando existiert nicht!");
fc.addDefault("messages.canceled", "&4Du hast den Vorgang erfolgreich abgebrochen!");
fc.addDefault("messages.needrightclick", "&4Du musst jetzt ein Schild mit der richtigen Aufschrift rechtsklicken um ein Lobbyschild zu erstellen oder gib '/jnk cancel' ein!");
fc.addDefault("messages.arenaspawnteamset", "&4Du hast erfolgreich den Spawn für das Team %team% gesetzt!");
}
public Object get(String path) {
return fc.get(path);
}
}
|
08bd1e35cb36954e6f806a770718444ca1b7d05f
|
[
"Java"
] | 4 |
Java
|
MiDaZoLP/JumpnKill
|
e3582eac0f94ec590fd5948e28b852bd95ef2b9f
|
7a890afbc81fa6f5a487657c7c8151ee8ecabf7c
|
refs/heads/master
|
<repo_name>villa-version/Find_a_way<file_sep>/main.py
import pygame, sys
from random import randint as rand
CELL_NUMBER, CELL_SIZE = 20, 30
class Cell:
def __init__(self, x, y, occupied, screen, wrong):
self.x = x
self.y = y
self.occupied = occupied
self.wrong = wrong
self.screen = screen
def draw(self):
for i in range(2):
obj = pygame.Rect(int(self.x * CELL_SIZE), int(self.y * CELL_SIZE), CELL_SIZE - 5 * i,
CELL_SIZE - 5 * i)
pygame.draw.rect(self.screen, (255 * i, 255 * i, 255 * i), obj)
class StartPoint:
def __init__(self, x, y, screen):
self.x = x
self.y = y
self.screen = screen
def draw(self):
obj = pygame.Rect(int(self.x * CELL_SIZE), int(self.y * CELL_SIZE), CELL_SIZE - 5, CELL_SIZE - 5)
pygame.draw.rect(self.screen, (0, 255, 0), obj)
class FinishPoint:
def __init__(self, x, y, screen):
self.x = x
self.y = y
self.screen = screen
def draw(self):
obj = pygame.Rect(int(self.x * CELL_SIZE), int(self.y * CELL_SIZE), CELL_SIZE - 5, CELL_SIZE - 5)
pygame.draw.rect(self.screen, (255, 0, 255), obj)
class PathWay:
def __init__(self, x, y, screen, direction):
self.x = x
self.y = y
self.direction = direction
self.screen = screen
def draw(self):
obj = pygame.Rect(int(self.x * CELL_SIZE), int(self.y * CELL_SIZE), CELL_SIZE - 5, CELL_SIZE - 5)
pygame.draw.rect(self.screen, (255, 0, 0), obj)
class MainController:
def __init__(self, screen):
self.screen = screen
self.grid = []
self.spawn_grid()
self.start_point = None
self.finish_point = None
self.way = []
self.direction = [0, 1, 2, 3]
self.allow_to_spawn_first_pathway = True
self.way_out_of_a_trap_state = True
self.progress = 'SP'
self.last_dir = -1
def update(self):
self.draw_elem()
self.choose_dir()
self.chek_collision_with_finish_point()
def draw_elem(self):
for row in self.grid:
for cell in row:
cell.draw()
for pw in self.way:
pw.draw()
try:
self.start_point.draw()
self.finish_point.draw()
except AttributeError:
pass
def spawn_points(self, mx, my):
if self.progress == 'SP':
self.progress = 'FP'
x = mx//CELL_SIZE
y = my//CELL_SIZE
self.start_point = StartPoint(x, y, self.screen)
elif self.progress == 'FP':
self.progress = 'SP'
x = mx // CELL_SIZE
y = my // CELL_SIZE
self.finish_point = FinishPoint(x, y, self.screen)
def spawn_grid(self):
r = range(CELL_NUMBER)
for _ in r:
self.grid.append([])
for y in r:
for x in r:
self.grid[y].append(Cell(x, y, False, self.screen, False))
def way_out_of_a_trap(self, dir):
counter = 0
if self.way_out_of_a_trap_state:
if self.way[-1].y - 1 < 0:
counter += 1
else:
if self.grid[self.way[-1].y - 1][self.way[-1].x].occupied:
counter += 1
if self.way[-1].y + 1 > CELL_NUMBER - 1:
counter += 1
else:
if self.grid[self.way[-1].y + 1][self.way[-1].x].occupied:
counter += 1
if self.way[-1].x - 1 < 0:
counter += 1
else:
if self.grid[self.way[-1].y][self.way[-1].x - 1].occupied:
counter += 1
if self.way[-1].x + 1 > CELL_NUMBER - 1:
counter += 1
else:
if self.grid[self.way[-1].y][self.way[-1].x + 1].occupied:
counter += 1
self.last_dir = self.way[-1].direction
if counter == 4:
self.grid[self.way[-1].y][self.way[-1].x].occupied = False
self.grid[self.way[-1].y][self.way[-1].x].wrong = True
self.direction.remove(self.last_dir)
self.way.remove(self.way[-1])
self.way_out_of_a_trap_state = False
else:
if self.way[-1].y - 1 < 0:
counter += 1
else:
if self.grid[self.way[-1].y - 1][self.way[-1].x].occupied:
counter += 1
elif self.grid[self.way[-1].y - 1][self.way[-1].x].wrong:
counter += 1
if self.way[-1].y + 1 > CELL_NUMBER - 1:
counter += 1
else:
if self.grid[self.way[-1].y + 1][self.way[-1].x].occupied:
counter += 1
elif self.grid[self.way[-1].y + 1][self.way[-1].x].wrong:
counter += 1
if self.way[-1].x - 1 < 0:
counter += 1
else:
if self.grid[self.way[-1].y][self.way[-1].x - 1].occupied:
counter += 1
elif self.grid[self.way[-1].y][self.way[-1].x - 1].wrong:
counter += 1
if self.way[-1].x + 1 > CELL_NUMBER - 1:
counter += 1
else:
if self.grid[self.way[-1].y][self.way[-1].x + 1].occupied:
counter += 1
elif self.grid[self.way[-1].y][self.way[-1].x + 1].wrong:
counter += 1
self.last_dir = self.way[-1].direction
if counter < 4:
self.way_out_of_a_trap_state = True
self.last_dir = -1
else:
self.grid[self.way[-1].y][self.way[-1].x].wrong = True
self.grid[self.way[-1].y][self.way[-1].x].occupied = False
self.way.remove(self.way[-1])
if self.last_dir in self.direction:
self.direction.remove(self.last_dir)
def choose_dir(self):
new_direction = rand(self.direction[0], self.direction[-1])
if self.allow_to_spawn_first_pathway:
try:
self.way.append(PathWay(self.start_point.x, self.start_point.y + 1, self.screen, new_direction))
self.grid[self.start_point.y + 1][self.start_point.x].occupied = True
self.grid[self.start_point.y][self.start_point.x].occupied = True
self.allow_to_spawn_first_pathway = False
except AttributeError:
pass
else:
if new_direction == 0 and self.direction != [1, 2, 3]:
if self.way[-1].y - 1 < 0:
self.direction = [2, 3]
else:
if not self.grid[self.way[-1].y - 1][self.way[-1].x].occupied:
self.way.append(PathWay(self.way[-1].x, self.way[-1].y - 1, self.screen, new_direction))
self.grid[self.way[-1].y][self.way[-1].x].occupied = True
self.direction = [0, 2, 3]
else:
self.direction = [1, 2, 3]
elif new_direction == 1 and self.direction != [0, 2, 3]:
if self.way[-1].y == CELL_NUMBER - 1:
self.direction = [2, 3]
else:
if not self.grid[self.way[-1].y + 1][self.way[-1].x].occupied:
self.way.append(PathWay(self.way[-1].x, self.way[-1].y + 1, self.screen, new_direction))
self.grid[self.way[-1].y][self.way[-1].x].occupied = True
self.direction = [1, 2, 3]
else:
self.direction = [0, 2, 3]
elif new_direction == 2 and self.direction != [0, 1, 3]:
if self.way[-1].x - 1 < 0:
self.direction = [0, 1]
else:
if not self.grid[self.way[-1].y][self.way[-1].x - 1].occupied:
self.way.append(PathWay(self.way[-1].x - 1, self.way[-1].y, self.screen, new_direction))
self.grid[self.way[-1].y][self.way[-1].x].occupied = True
self.direction = [0, 1, 2]
else:
self.direction = [0, 1, 3]
elif new_direction == 3 and self.direction != [0, 1, 2]:
if self.way[-1].x + 1 > CELL_NUMBER - 1:
self.direction = [0, 1]
else:
if not self.grid[self.way[-1].y][self.way[-1].x + 1].occupied:
self.way.append(PathWay(self.way[-1].x + 1, self.way[-1].y, self.screen, new_direction))
self.grid[self.way[-1].y][self.way[-1].x].occupied = True
self.direction = [0, 1, 3]
else:
self.direction = [0, 1, 2]
self.way_out_of_a_trap(new_direction)
def chek_collision_with_finish_point(self):
try:
dx = abs(self.finish_point.x - self.way[-1].x)
dy = abs(self.finish_point.y - self.way[-1].y)
if dx == 1 and dy == 1:
print('THE PROGRAM HAS FOUND A WAY TO FINISH POINT, YOU WON')
pygame.quit()
sys.exit()
except AttributeError:
pass
def main():
screen = pygame.display.set_mode((CELL_SIZE * CELL_NUMBER, CELL_SIZE * CELL_NUMBER))
fpsClock = pygame.time.Clock()
main_controller = MainController(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
main_controller.spawn_points(mouse_x, mouse_y)
screen.fill((255, 255, 255))
main_controller.update()
pygame.display.update()
fpsClock.tick(10)
if __name__ == '__main__':
main()
|
169b7f760225f42e9189139dff25ddf3f06f1deb
|
[
"Python"
] | 1 |
Python
|
villa-version/Find_a_way
|
1f70aabb8f20c23104709a3c80865e3ffaace03e
|
8aef2fcc4188eb378e4c5ed1a62771efd66b3244
|
refs/heads/master
|
<repo_name>AlexRogalskiy/postgraphile-as-library<file_sep>/db/init/01-data.sql
\connect forum_example;
/*Create some dummy users*/
INSERT INTO public.user (username) VALUES
('Benjie'),
('Singingwolfboy'),
('Lexius');
/*Create some dummy posts*/
INSERT INTO public.post (title, body, author_id) VALUES
('First post example', 'Lorem ipsum dolor sit amet', 1),
('Second post example', 'Consectetur adipiscing elit', 2),
('Third post example', 'Aenean blandit felis sodales', 3);<file_sep>/db/init/00-database.sql
/*Connecting to the database automatically creates it*/
\connect forum_example;
/*Create user table in public schema*/
CREATE TABLE public.user (
id SERIAL PRIMARY KEY,
username TEXT,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
COMMENT ON TABLE public.user IS
'Forum users.';
/*Create post table in public schema*/
CREATE TABLE public.post (
id SERIAL PRIMARY KEY,
title TEXT,
body TEXT,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
author_id INTEGER NOT NULL REFERENCES public.user(id)
);
COMMENT ON TABLE public.post IS
'Forum posts written by a user.';<file_sep>/graphql/Dockerfile
FROM node:alpine
LABEL description="Instant high-performance GraphQL API for your PostgreSQL database https://github.com/graphile/postgraphile"
# Set Node.js app folder
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
WORKDIR /home/node/app
# Copy dependencies
COPY ./src/package*.json .
# Install dependencies
USER node
RUN npm install
# Copy application files
COPY --chown=node:node ./src .
EXPOSE 8080
CMD [ "node", "server.js" ]<file_sep>/README.md
# Postgraphile as Library
The following guide describes how to run a network of Docker containers on a local machine, including one container for a PostgreSQL database and one container running PostGraphile.
It is the same as the repository **[Docker-PostgreSQL-PostGraphile](https://github.com/alexisrolland/docker-postgresql-postgraphile)** with one difference, the PostGraphile container runs a **Node.js application using PostGraphile as library** instead of running PostGraphile via CLI. Running PostGraphile as a library opens doors to greater customization possibilities.
Follow the steps provided in the repository **[Docker-PostgreSQL-PostGraphile](https://github.com/alexisrolland/docker-postgresql-postgraphile)** and come back to this guide to create the GraphQL container.
# Table of Contents
- [Create PostGraphile Container](#create-postgraphile-container)
- [Update Environment Variables](#update-environment-variables)
- [Create Node.js Application](#create-nodejs-application)
- [Create PostGraphile Dockerfile](#create-postgraphile-dockerfile)
- [Update Docker Compose File](#update-docker-compose-file)
- [Build Images And Run Containers](#build-images-and-run-containers)
- [Build Images](#build-images)
- [Run Containers](#run-containers)
- [Re-initialize The Database](#re-initialize-the-database)
# Create PostGraphile Container
At this stage, the repository should look like this.
```
/
├─ db/
| ├─ init/
| | ├─ 00-database.sql
| | └─ 01-data.sql
| └─ Dockerfile
├─ .env
└─ docker-compose.yml
```
## Update Environment Variables
Update the file `.env` to add the `PORT` and `DATABASE_URL` which will be used by PostGraphile to connect to the PostgreSQL database. Note the `DATABASE_URL` follows the syntax `postgres://<user>:<password>@db:5432/<db_name>`.
```
[...]
# GRAPHQL
# Parameters used by graphql container
DATABASE_URL=postgres://postgres:change_me@db:5432/forum_example
PORT=5433
```
## Create Node.js Application
Create a new folder `graphql` at the root of the repository. It will be used to store the files necessary to create the PostGraphile container. In the `graphql` folder, create a subfolder `src` and add a file `package.json` into it with the following content.
```json
{
"name": "postgraphile-as-library",
"version": "0.0.1",
"description": "PostGraphile as a library in a dockerized Node.js application.",
"author": "<NAME>",
"license": "Apache-2.0",
"main": "server.js",
"keywords": ["nodejs", "postgraphile"],
"dependencies": {
"postgraphile": "^4.5.5",
"postgraphile-plugin-connection-filter": "^1.1.3"
}
}
```
This file will be used by NPM package manager to install the dependencies in the Node.js container. In particular `postgraphile` and the excellent plugin `postgraphile-plugin-connection-filter`.
In the same `src` folder, create a new file `server.js` with the following content.
```js
const http = require("http");
const { postgraphile } = require("postgraphile");
http.createServer(
postgraphile(process.env.DATABASE_URL, "public", {
watchPg: true,
graphiql: true,
enhanceGraphiql: true
})
).listen(process.env.PORT);
```
## Create PostGraphile Dockerfile
Create a new file `Dockerfile` in the `graphql` folder (not in the folder `src`) with the following content.
```dockerfile
FROM node:alpine
LABEL description="Instant high-performance GraphQL API for your PostgreSQL database https://github.com/graphile/postgraphile"
# Set Node.js app folder
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
WORKDIR /home/node/app
# Copy dependencies
COPY ./src/package*.json .
# Install dependencies
USER node
RUN npm install
# Copy application files
COPY --chown=node:node ./src .
EXPOSE 8080
CMD [ "node", "server.js" ]
```
## Update Docker Compose File
Update the file `docker-compose.yml` under the `services` section to include the GraphQL service.
```yml
version: "3.3"
services:
db: [...]
graphql:
container_name: forum-example-graphql
restart: always
image: forum-example-graphql
build:
context: ./graphql
env_file:
- ./.env
depends_on:
- db
networks:
- network
ports:
- 5433:5433
[...]
```
At this stage, the repository should look like this.
```
/
├─ db/
| ├─ init/
| | ├─ 00-database.sql
| | └─ 01-data.sql
| └─ Dockerfile
├─ graphql/
| ├─ src/
| | ├─ package.json
| | └─ server.js
| └─ Dockerfile
├─ .env
└─ docker-compose.yml
```
# Build Images And Run Containers
## Build Images
You can build the Docker images by executing the following command from the root of the repository.
```
# Build all images in docker compose
$ docker-compose build
# Build database image only
$ docker-compose build db
# Build graphql image only
$ docker-compose build graphql
```
## Run Containers
You can run the Docker containers by executing the following command from the root of the repository. Note when running the database container for the first time, Docker will automatically create a Docker Volume to persist the data from the database. The Docker Volume is automatically named as `<your_repository_name>_db`.
```
# Run all containers
$ docker-compose up
# Run all containers as daemon (in background)
$ docker-compose up -d
# Run database container as daemon
$ docker-compose up -d db
# Run graphql container as daemon
$ docker-compose up -d graphql
```
Each container can be accessed at the following addresses. Note if you run Docker Toolbox on Windows Home, you can get your Docker machine IP address with the command `$ docker-machine ip default`.
<table>
<tr>
<th>Container</th>
<th>Docker on Linux / Windows Pro</th>
<th>Docker on Windows Home</th>
</tr>
<tr>
<td>GraphQL API Documentation</td>
<td>https://localhost:5433/graphiql</td>
<td>https://your_docker_machine_ip:5433/graphiql</td>
</tr>
<tr>
<td>GraphQL API</td>
<td>https://localhost:5433/graphql</td>
<td>https://your_docker_machine_ip:5433/graphql</td>
</tr>
<tr>
<td>PostgreSQL Database</td>
<td>host: localhost, port: 5432</td>
<td>host: your_docker_machine_ip, port: 5432</td>
</tr>
</table>
## Re-initialize The Database
In case you do changes to the database schema by modifying the files in `/db/init`, you will need to re-initialize the database to see these changes. This means you need to delete the Docker Volume, the database Docker Image and rebuild it.
```shell
# Stop running containers
$ docker-compose down
# List Docker volumes
$ docker volume ls
# Delete volume
$ docker volume rm <your_repository_name>_db
# Delete database image to force rebuild
$ docker rmi db
# Run containers (will automatically rebuild the image)
$ docker-compose up
```
|
ca72bc9e899d3cae6452358f4652498b5dd48a10
|
[
"Markdown",
"SQL",
"Dockerfile"
] | 4 |
SQL
|
AlexRogalskiy/postgraphile-as-library
|
712f6eac8fa7e5af755f29bd7c9fb4d403a95ee3
|
78d3cbf1068f2f3645221efa7eaff14a163a7cbd
|
refs/heads/master
|
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Connection;
use Brightzone\GremlinDriver\RequestMessage;
use Brightzone\GremlinDriver\Serializers\Gson3;
use stdClass;
/**
* Unit testing of Gremlin-php
* This actually runs tests against the server
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class GraphSon3Test extends RexsterTestCase
{
/**
* Gets the int type (32b-64b) for this system
*
* @return string int type, either g:Int32 or g:Int64
*/
protected function getIntType()
{
if(PHP_INT_SIZE == 4)
{
return "g:Int32";
}
else if(PHP_INT_SIZE == 8)
{
return "g:Int64";
}
else
{
$this->fail("PHP_IN_SIZE is " . PHP_INT_SIZE . "and is not supported by the serializer");
}
return FALSE;
}
/**
* Test converting a String to graphson 3.0 format
*
* @return void
*/
public function testConvertString()
{
$serializer = new Gson3;
$converted = $serializer->convertString("testing");
$this->assertEquals("testing", $converted, "Incorrect GS3 conversion for String");
}
/**
* Test converting a Boolean to graphson 3.0 format
*
* @return void
*/
public function testConvertBoolean()
{
$serializer = new Gson3;
$converted = $serializer->convertBoolean(TRUE);
$this->assertEquals(TRUE, $converted, "Incorrect GS3 conversion for Bool");
}
/**
* Test converting an Integer to graphson 3.0 format
*
* @return void
*/
public function testConvertInteger()
{
$serializer = new Gson3;
$intType = $this->getintType();
$converted = $serializer->convertInteger(5);
$this->assertEquals(["@type" => $intType, "@value" => 5], $converted, "Incorrect GS3 conversion for Integer");
}
/**
* Test converting an float/double to graphson 3.0 format
*
* @return void
*/
public function testConvertDouble()
{
$serializer = new Gson3;
$converted = $serializer->convertDouble(5.3);
$this->assertEquals(["@type" => "g:Double", "@value" => 5.3], $converted, "Incorrect GS3 conversion for Double");
}
/**
* Test converting an object to graphson 3.0 format
* This is unsupported and should throw an error.
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*/
public function testConvertObject()
{
$serializer = new Gson3;
$object = new stdClass();
$object->title = 'Test Object';
// List
$serializer->convertObject($object);
}
/**
* Test converting a Request message object to graphson 3.0 format
*
* @return void
*/
public function testConvertObjectRequestMessage()
{
$serializer = new Gson3;
$intType = $this->getintType();
$object = new RequestMessage([3 => [123, TRUE, 5.34, "string"]]);
$converted = $serializer->convertObject($object);
$this->assertEquals([
3 => [
"@type" => "g:List",
"@value" => [
["@type" => $intType, "@value" => 123],
TRUE,
["@type" => "g:Double", "@value" => 5.34],
"string",
],
],
], $converted, "Incorrect GS3 conversion for RequestMessage object");
}
/**
* Test converting an NULL to graphson 3.0 format
*
* @return void
*/
public function testConvertNull()
{
$serializer = new Gson3;
$deconverted = $serializer->convertNULL(NULL);
$this->assertEquals(NULL, $deconverted, "Incorrect deconversion for Double");
}
/**
* Test converting a List to graphson 3.0 format
*
* @return void
*/
public function testConvertList()
{
$serializer = new Gson3;
$converted = $serializer->convertList(["test", "test2"]);
$this->assertEquals(["@type" => "g:List", "@value" => ["test", "test2"]], $converted, "Incorrect GS3 conversion for List");
}
/**
* Test converting an empty List to graphson 3.0 format
*
* @return void
*/
public function testConvertEmptyList()
{
$serializer = new Gson3;
$converted = $serializer->convertList([]);
$this->assertEquals(["@type" => "g:List", "@value" => []], $converted, "Incorrect GS3 conversion for an empty List");
}
/**
* Test converting a Map with string keys to graphson 3.0 format
*
* @return void
*/
public function testConvertListWithMixValue()
{
$serializer = new Gson3;
$intType = $this->getintType();
$converted = $serializer->convertList([123, TRUE, 5.34, "string"]);
$this->assertEquals([
"@type" => "g:List",
"@value" => [
["@type" => $intType, "@value" => 123],
TRUE,
["@type" => "g:Double", "@value" => 5.34],
"string",
],
], $converted, "Incorrect GS3 conversion for List with mixed values");
}
/**
* Test converting a Map with no keys to graphson 3.0 format
*
* @return void
*/
public function testConvertMapWithNoKey()
{
$serializer = new Gson3;
$intType = $this->getintType();
$converted = $serializer->convertMap(["test", "test2"]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [
["@type" => $intType, "@value" => 0], "test",
["@type" => $intType, "@value" => 1], "test2",
],
], $converted, "Incorrect GS3 conversion for Map without keys");
}
/**
* Test converting an empty Map with no keys to graphson 3.0 format
*
* @return void
*/
public function testConvertEmptyMap()
{
$serializer = new Gson3;
$converted = $serializer->convertMap([]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [],
], $converted, "Incorrect GS3 conversion for an empty Map");
}
/**
* Test converting a Map with string keys to graphson 3.0 format
*
* @return void
*/
public function testConvertMapWithStringKey()
{
$serializer = new Gson3;
$converted = $serializer->convertMap(["string1" => "test", "02" => "test2"]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [
"string1", "test",
"02", "test2",
],
], $converted, "Incorrect GS3 conversion for Map with string keys");
}
/**
* Test converting a Map with string keys to graphson 3.0 format
*
* @return void
*/
public function testConvertMapWithMixKey()
{
$serializer = new Gson3;
$intType = $this->getintType();
$converted = $serializer->convertMap(["string1" => "test", 2 => "test2"]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [
"string1", "test",
["@type" => $intType, "@value" => 2], "test2",
],
], $converted, "Incorrect GS3 conversion for Map with mixed keys");
}
/**
* Test converting a Map with string keys to graphson 3.0 format
*
* @return void
*/
public function testConvertMapWithMixValue()
{
$serializer = new Gson3;
$intType = $this->getintType();
$converted = $serializer->convertMap(["string1" => 123, "02" => TRUE, "03" => 5.34]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [
"string1", ["@type" => $intType, "@value" => 123],
"02", TRUE,
"03", ["@type" => "g:Double", "@value" => 5.34],
],
], $converted, "Incorrect GS3 conversion for Map with mixed values");
}
/**
* Test converting a Map to graphson 3.0 format
*
* @return void
*/
public function testConvertMapWithIntKey()
{
$serializer = new Gson3;
$intType = $this->getintType();
$converted = $serializer->convertMap([2 => "test", 7 => "test2"]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [
["@type" => $intType, "@value" => 2], "test",
["@type" => $intType, "@value" => 7], "test2",
],
], $converted, "Incorrect GS3 conversion for Map with int keys");
}
/**
* Test converting an array to map to graphson 3.0 format
*
* @return void
*/
public function testConvertArrayToMap()
{
$serializer = new Gson3;
$intType = $this->getintType();
$converted = $serializer->convertArray([2 => "test", 7 => "test2"]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [
["@type" => $intType, "@value" => 2], "test",
["@type" => $intType, "@value" => 7], "test2",
],
], $converted, "Incorrect GS3 conversion for Map");
}
/**
* Test converting an Array to List to graphson 3.0 format
*
* @return void
*/
public function testConvertArrayToList()
{
$serializer = new Gson3;
$converted = $serializer->convertArray(["test", "test2"]);
$this->assertEquals(["@type" => "g:List", "@value" => ["test", "test2"]], $converted, "Incorrect GS3 conversion for List");
}
/**
* Test converting any item
*
* @return void
*/
public function testConvert()
{
$serializer = new Gson3;
$intType = $this->getintType();
// List
$converted = $serializer->convert(["test", "test2"]);
$this->assertEquals(["@type" => "g:List", "@value" => ["test", "test2"]], $converted, "Incorrect GS3 conversion for List");
// Map
$converted = $serializer->convert([2 => "test", 7 => "test2"]);
$this->assertEquals([
"@type" => "g:Map",
"@value" => [
["@type" => $intType, "@value" => 2], "test",
["@type" => $intType, "@value" => 7], "test2",
],
], $converted, "Incorrect GS3 conversion for Map");
// String
$converted = $serializer->convert("testing");
$this->assertEquals("testing", $converted, "Incorrect GS3 conversion for String");
// bool
$converted = $serializer->convert(TRUE);
$this->assertEquals(TRUE, $converted, "Incorrect GS3 conversion for Bool");
// Double
$converted = $serializer->convert(5.3);
$this->assertEquals(["@type" => "g:Double", "@value" => 5.3], $converted, "Incorrect GS3 conversion for Double");
// Int
$converted = $serializer->convert(5);
$this->assertEquals(["@type" => $intType, "@value" => 5], $converted, "Incorrect GS3 conversion for Integer");
}
/**
* Test converting an unsupported object
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*/
public function testConvertUnsupportedObject()
{
$serializer = new Gson3;
$object = new stdClass();
$object->title = 'Test Object';
$serializer->convert($object);
}
/**
* Test converting an unsupported type
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*/
public function testConvertUnsupportedType()
{
$serializer = new Gson3;
$type = stream_context_create();
$serializer->convert($type);
}
/**
* Test converting a complex item
*
*/
public function testConvertComplex()
{
$serializer = new Gson3;
$converted = $serializer->convert([
[
"something",
32,
],
TRUE,
[
"lala",
33 => 21,
"key" => [
"lock",
"door",
[
"again" => "inside",
],
],
],
30,
]);
$this->assertEquals([
"@type" => "g:List",
"@value" => [
[
"@type" => "g:List",
"@value" => [
"something",
["@type" => "g:Int64", "@value" => 32],
],
],
TRUE,
[
"@type" => "g:Map",
"@value" => [
["@type" => "g:Int64", "@value" => 0],
"lala",
["@type" => "g:Int64", "@value" => 33],
["@type" => "g:Int64", "@value" => 21],
"key",
[
"@type" => "g:List",
"@value" => [
"lock",
"door",
[
"@type" => "g:Map",
"@value" => [
"again",
"inside",
],
],
],
],
],
],
["@type" => "g:Int64", "@value" => 30],
],
], $converted, "Incorrect GS3 conversion for Complex object");
}
/**
* Test serializing array to GraphSON 3.0
*
* @return void
*/
public function testSerialize()
{
$serializer = new Gson3;
$data = [
[
"something",
32,
],
TRUE,
[
"lala",
33 => 21,
"key" => [
"lock",
"door",
[
"again" => "inside",
],
],
],
30,
];
$length = $serializer->serialize($data);
$this->assertEquals($length, strlen($data), "serialized message length was incorrect");
$this->assertEquals('{"@type":"g:List","@value":[{"@type":"g:List","@value":["something",{"@type":"g:Int64","@value":32}]},true,{"@type":"g:Map","@value":[{"@type":"g:Int64","@value":0},"lala",{"@type":"g:Int64","@value":33},{"@type":"g:Int64","@value":21},"key",{"@type":"g:List","@value":["lock","door",{"@type":"g:Map","@value":["again","inside"]}]}]},{"@type":"g:Int64","@value":30}]}', $data, "incorrect GraphSON 3.0 was generated");
}
/**
* Test deconverting an Int32 from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertInt32()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertInt32(5);
$this->assertEquals(5, $deconverted, "Incorrect deconversion for Int32");
}
/**
* Test deconverting an Int64 from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertInt64()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertInt64(5);
$this->assertEquals(5, $deconverted, "Incorrect deconversion for Int64");
}
/**
* Test deconverting an Date from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertDate()
{
$serializer = new Gson3;
$time = time();
$deconverted = $serializer->deconvertTimestamp($time);
$this->assertEquals($time, $deconverted, "Incorrect deconversion for Date");
}
/**
* Test deconverting an Timestamp from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertTimestamp()
{
$serializer = new Gson3;
$time = time();
$deconverted = $serializer->deconvertTimestamp($time);
$this->assertEquals($time, $deconverted, "Incorrect deconversion for Timestamp");
}
/**
* Test deconverting an Double from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertDouble()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertDouble(5.34);
$this->assertEquals(5.34, $deconverted, "Incorrect deconversion for Double");
}
/**
* Test deconverting an Float from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertFloat()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertFloat(5.34);
$this->assertEquals(5.34, $deconverted, "Incorrect deconversion for Float");
}
/**
* Test deconverting an UUID from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertUUID()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertUUID("41d2e28a-20a4-4ab0-b379-d810dede3786");
$this->assertEquals("41d2e28a-20a4-4ab0-b379-d810dede3786", $deconverted, "Incorrect deconversion for UUID");
}
/**
* Test deconverting an VertexProperty from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertVertexProperty()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertVertexProperty([
"id" => [
"@type" => "g:Int64",
"@value" => 0,
],
"value" => "marko",
"label" => "name",
]);
$this->assertEquals([
"id" => 0,
"value" => "marko",
"label" => "name",
], $deconverted, "Incorrect deconversion for VertexProperty");
}
/**
* Test deconverting an Property from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertProperty()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertProperty([
"key" => "since",
"value" => [
"@type" => "g:Int32",
"@value" => 2009,
],
]);
$this->assertEquals([
"key" => "since",
"value" => 2009,
], $deconverted, "Incorrect deconversion for Property");
}
/**
* Test deconverting an Vertex from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertVertex()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertVertex([
"label" => "person",
"value" => [
"@type" => "g:Int32",
"@value" => 2009,
],
]);
$this->assertEquals([
"label" => "person",
"value" => 2009,
"type" => 'vertex',
], $deconverted, "Incorrect deconversion for Vertex");
}
/**
* Test deconverting an Edge from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertEdge()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertEdge([
"label" => "friend",
"value" => [
"@type" => "g:Int32",
"@value" => 2009,
],
]);
$this->assertEquals([
"label" => "friend",
"value" => 2009,
"type" => 'edge',
], $deconverted, "Incorrect deconversion for Edge");
}
/**
* Test deconverting a List from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertList()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertList([
"friend",
[
"@type" => "g:Int32",
"@value" => 2009,
],
TRUE,
]);
$this->assertEquals([
"friend",
2009,
TRUE,
], $deconverted, "Incorrect deconversion for List");
}
/**
* Test deconverting a Path from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertPath()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertPath([
"@type" => "g:Path",
"@value" => [
"labels" => [[], [], []],
"objects" => [
[
"@type" => "g:Vertex",
"@value" => [
"id" => [
"@type" => "g:Int32",
"@value" => 1,
],
"label" => "person",
],
], [
"@type" => "g:Vertex",
"@value" => [
"id" => [
"@type" => "g:Int32",
"@value" => 10,
],
"label" => "software",
"properties" => [
"name" => [
[
"@type" => "g:VertexProperty",
"@value" => [
"id" => [
"@type" => "g:Int64",
"@value" => 4,
],
"value" => "gremlin",
"vertex" => [
"@type" => "g:Int32",
"@value" => 10,
],
"label" => "name",
],
],
],
],
],
], [
"@type" => "g:Vertex",
"@value" => [
"id" => [
"@type" => "g:Int32",
"@value" => 11,
],
"label" => "software",
"properties" => [
"name" => [
[
"@type" => "g:VertexProperty",
"@value" => [
"id" => [
"@type" => "g:Int64",
"@value" => 5,
],
"value" => "tinkergraph",
"vertex" => [
"@type" => "g:Int32",
"@value" => 11,
],
"label" => "name",
],
],
],
],
],
],
],
],
]);
$this->assertEquals([
"labels" => [[], [], []],
"objects" => [
[
"id" => 1,
"label" => "person",
"type" => "vertex",
], [
"id" => 10,
"label" => "software",
"properties" => [
"name" => [
[
"id" => 4,
"value" => "gremlin",
"vertex" => 10,
"label" => "name",
],
],
],
"type" => "vertex",
], [
"id" => 11,
"label" => "software",
"properties" => [
"name" => [
[
"id" => 5,
"value" => "tinkergraph",
"vertex" => 11,
"label" => "name",
],
],
],
"type" => "vertex",
],
],
], $deconverted, "Incorrect deconversion for Path");
}
/**
* Test deconverting a Tree from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertTree()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertTree([
'@type' => 'g:List',
'@value' => [
0 => [
'@type' => 'g:Tree',
'@value' => [
0 => [
'key' => [
'@type' => 'g:Vertex',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 1,
],
'label' => 'vertex',
'properties' => [
'name' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 0,
],
'value' => 'marko',
'label' => 'name',
],
],
],
'age' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 2,
],
'value' => [
'@type' => 'g:Int32',
'@value' => 29,
],
'label' => 'age',
],
],
],
],
],
],
'value' => [
'@type' => 'g:Tree',
'@value' => [
0 => [
'key' => [
'@type' => 'g:Vertex',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 2,
],
'label' => 'vertex',
'properties' => [
'name' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 3,
],
'value' => 'vadas',
'label' => 'name',
],
],
],
'age' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 4,
],
'value' => [
'@type' => 'g:Int32',
'@value' => 27,
],
'label' => 'age',
],
],
],
],
],
],
'value' => [
'@type' => 'g:Tree',
'@value' => [
0 => [
'key' => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 3,
],
'value' => 'vadas',
'label' => 'name',
],
],
'value' => [
'@type' => 'g:Tree',
'@value' => [],
],
],
],
],
],
1 => [
'key' => [
'@type' => 'g:Vertex',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 3,
],
'label' => 'vertex',
'properties' => [
'name' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 5,
],
'value' => 'lop',
'label' => 'name',
],
],
],
'lang' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 6,
],
'value' => 'java',
'label' => 'lang',
],
],
],
],
],
],
'value' => [
'@type' => 'g:Tree',
'@value' => [
0 => [
'key' => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 5,
],
'value' => 'lop',
'label' => 'name',
],
],
'value' => [
'@type' => 'g:Tree',
'@value' => [],
],
],
],
],
],
2 => [
'key' => [
'@type' => 'g:Vertex',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 4,
],
'label' => 'vertex',
'properties' => [
'name' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 7,
],
'value' => 'josh',
'label' => 'name',
],
],
],
'age' => [
0 => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 8,
],
'value' => [
'@type' => 'g:Int32',
'@value' => 32,
],
'label' => 'age',
],
],
],
],
],
],
'value' => [
'@type' => 'g:Tree',
'@value' => [
0 => [
'key' => [
'@type' => 'g:VertexProperty',
'@value' => [
'id' => [
'@type' => 'g:Int64',
'@value' => 7,
],
'value' => 'josh',
'label' => 'name',
],
],
'value' => [
'@type' => 'g:Tree',
'@value' => [],
],
],
],
],
],
],
],
],
],
],
],
'meta' => [
'@type' => 'g:Map',
'@value' => [],
],
]);
$this->assertEquals([
[
1 => [
'key' => [
'id' => 1,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 0, 'value' => 'marko', 'label' => 'name']],
'age' => [['id' => 2, 'value' => 29, 'label' => 'age']],
],
],
'value' => [
2 => [
'key' => [
'id' => 2,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 3, 'value' => 'vadas', 'label' => 'name']],
'age' => [['id' => 4, 'value' => 27, 'label' => 'age']],
],
],
'value' => [
3 => [
'key' => ['id' => 3, 'value' => 'vadas', 'label' => 'name'],
'value' => [],
],
],
],
3 => [
'key' => [
'id' => 3,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 5, 'value' => 'lop', 'label' => 'name']],
'lang' => [['id' => 6, 'value' => 'java', 'label' => 'lang']],
],
],
'value' => [
5 => [
'key' => ['id' => 5, 'value' => 'lop', 'label' => 'name'],
'value' => [],
],
],
],
4 => [
'key' => [
'id' => 4,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 7, 'value' => 'josh', 'label' => 'name']],
'age' => [['id' => 8, 'value' => 32, 'label' => 'age']],
],
],
'value' => [
7 => [
'key' => ['id' => 7, 'value' => 'josh', 'label' => 'name'],
'value' => [],
],
],
],
],
],
],
], $deconverted, "Incorrect deconversion for Path");
}
/**
* Test deconverting a Complex List from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertComplexList()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertList([
"friend",
[
"@type" => "g:Int32",
"@value" => 2009,
],
[
"@type" => "g:List",
"@value" => [
"friend",
[
"@type" => "g:Int32",
"@value" => 2009,
],
],
],
TRUE,
]);
$this->assertEquals([
"friend",
2009,
["friend", 2009],
TRUE,
], $deconverted, "Incorrect deconversion for ComplexList");
}
/**
* Test deconverting a Set from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertSet()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertSet([
"friend",
[
"@type" => "g:Int32",
"@value" => 2009,
],
TRUE,
]);
$this->assertEquals([
"friend",
2009,
TRUE,
], $deconverted, "Incorrect deconversion for Set");
}
/**
* Test deconverting an empty Set from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertEmptySet()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertSet([]);
$this->assertEquals([], $deconverted, "Incorrect deconversion for Empty Set");
}
/**
* Test deconverting a Complex Set from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertComplexSet()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertSet([
"friend",
[
"@type" => "g:Int32",
"@value" => 2009,
],
[
"@type" => "g:List",
"@value" => [
"friend",
[
"@type" => "g:Int32",
"@value" => 2009,
],
],
],
TRUE,
]);
$this->assertEquals([
"friend",
2009,
["friend", 2009],
TRUE,
], $deconverted, "Incorrect deconversion for Complex Set");
}
/**
* Test deconverting a Map from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertMap()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertMap([
"test",
"friend",
["@type" => "g:Int32", "@value" => 2009],
["@type" => "g:Int32", "@value" => 20],
["@type" => "g:Int32", "@value" => 20],
TRUE,
"time",
["@type" => "g:Date", "@value" => 456789],
]);
$this->assertEquals([
"test" => "friend",
2009 => 20,
20 => TRUE,
"time" => 456789,
], $deconverted, "Incorrect deconversion for Map");
}
/**
* Test deconverting a broken Map from graphson 3.0 format to native
* If a map has an odd number of items it should throw an error
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*/
public function testDeconvertOddNumberMap()
{
$serializer = new Gson3;
$serializer->deconvertMap([
"test",
"friend",
["@type" => "g:Int32", "@value" => 2009],
["@type" => "g:Int32", "@value" => 20],
["@type" => "g:Int32", "@value" => 20],
TRUE,
"time",
]);
}
/**
* Test deconverting a broken Map from graphson 3.0 format to native
* If a map has a key other than int or string
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*/
public function testDeconvertNonStandardKeyMap()
{
$serializer = new Gson3;
$serializer->deconvertMap([
"test",
"friend",
["@type" => "g:List", "@value" => [20]],
["@type" => "g:Int32", "@value" => 2009],
["@type" => "g:Int32", "@value" => 20],
TRUE,
"time",
]);
}
/**
* Test deconverting a complex Map from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertComplexMap()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertMap([
"test",
"friend",
["@type" => "g:Int32", "@value" => 2009],
["@type" => "g:Int64", "@value" => 20],
"test",
TRUE,
"time",
[
"@type" => "g:Map", "@value" => [
"test",
"friend",
["@type" => "g:Int32", "@value" => 2009],
["@type" => "g:Int32", "@value" => 20],
],
],
]);
$this->assertEquals([
"test" => "friend",
2009 => 20,
"test" => TRUE,
"time" => [
"test" => "friend",
2009 => 20,
],
], $deconverted, "Incorrect deconversion for Map");
}
/**
* Test deconverting a Empty Map from graphson 3.0 format to native
*
* @return void
*/
public function testDeconvertEmptyMap()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertMap([]);
$this->assertEquals([], $deconverted, "Incorrect deconversion for Empty Map");
}
/**
* Test deconverting a Empty Map from graphson 3.0 format to native
*
* @return void
* @expectedException \Brightzone\GremlinDriver\InternalException
*/
public function testDeconvertMapOddElements()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvertMap([
"test",
"friend",
["@type" => "g:Int32", "@value" => 2009],
]);
}
/**
* Test deconverting any item
*
* @return void
*/
public function testDeconvert()
{
$serializer = new Gson3;
$intType = $this->getintType();
// List
$deconverted = $serializer->deconvert(["@type" => "g:List", "@value" => ["test", "test2"]]);
$this->assertEquals(["test", "test2"], $deconverted, "Incorrect GS3 deconversion for List");
// Map
$deconverted = $serializer->deconvert([
"@type" => "g:Map",
"@value" => [
["@type" => $intType, "@value" => 2], "test",
["@type" => $intType, "@value" => 7], "test2",
],
]);
$this->assertEquals([2 => "test", 7 => "test2"], $deconverted, "Incorrect GS3 deconversion for Map");
// String
$deconverted = $serializer->deconvert("testing");
$this->assertEquals("testing", $deconverted, "Incorrect GS3 deconversion for String");
// bool
$deconverted = $serializer->deconvert(TRUE);
$this->assertEquals(TRUE, $deconverted, "Incorrect GS3 deconversion for Bool");
// Double
$deconverted = $serializer->deconvert(["@type" => "g:Double", "@value" => 5.3]);
$this->assertEquals(5.3, $deconverted, "Incorrect GS3 deconversion for Double");
// Int
$deconverted = $serializer->deconvert(["@type" => $intType, "@value" => 5]);
$this->assertEquals(5, $deconverted, "Incorrect GS3 deconversion for Integer");
}
/**
* Test deconverting an unsupported item
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*/
public function testDeconvertUnsupported()
{
$serializer = new Gson3;
$serializer->deconvert(["@type" => "g:Unknown", "@value" => 5]);
}
/**
* Test deconverting a complex item
*
*/
public function testDeconvertComplex()
{
$serializer = new Gson3;
$deconverted = $serializer->deconvert([
"@type" => "g:List",
"@value" => [
[
"@type" => "g:List",
"@value" => [
"something",
["@type" => "g:Int64", "@value" => 32],
],
],
TRUE,
[
"@type" => "g:Map",
"@value" => [
["@type" => "g:Int64", "@value" => 0],
"lala",
["@type" => "g:Int64", "@value" => 33],
["@type" => "g:Int64", "@value" => 21],
"key",
[
"@type" => "g:List",
"@value" => [
"lock",
"door",
[
"@type" => "g:Map",
"@value" => [
"again",
"inside",
],
],
],
],
],
],
["@type" => "g:Int64", "@value" => 30],
],
]);
$this->assertEquals([
[
"something",
32,
],
TRUE,
[
"lala",
33 => 21,
"key" => [
"lock",
"door",
[
"again" => "inside",
],
],
],
30,
], $deconverted, "Incorrect GS3 deconversion for Complex object");
}
/**
* Test unserializing array to GraphSON 3.0
*
* @return void
*/
public function testUnserialize()
{
$serializer = new Gson3;
$data = '{"@type":"g:List","@value":[{"@type":"g:List","@value":["something",{"@type":"g:Int64","@value":32}]},true,{"@type":"g:Map","@value":[{"@type":"g:Int64","@value":0},"lala",{"@type":"g:Int64","@value":33},{"@type":"g:Int64","@value":21},"key",{"@type":"g:List","@value":["lock","door",{"@type":"g:Map","@value":["again","inside"]}]}]},{"@type":"g:Int64","@value":30}]}';
$data = $serializer->unserialize($data);
$this->assertEquals([
[
"something",
32,
],
TRUE,
[
"lala",
33 => 21,
"key" => [
"lock",
"door",
[
"again" => "inside",
],
],
],
30,
], $data, "incorrect GraphSON 3.0 was generated");
}
/**
* Test a basic graphson3 client-server exchange
* @return void
*/
public function testConnect()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(new Gson3, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE, 'Failed to connect to db');
$result = $db->send('5+5');
$this->assertEquals(10, $result[0], 'Script response message is not the right type. (Maybe it\'s an error)');
$result = $db->send('g.V()');
$this->assertEquals(6, count($result), 'Script response message is not the right type. (Maybe it\'s an error)');
//check disconnection
$db->close();
$this->assertFALSE($db->isConnected(), 'Despite not throwing errors, Socket connection is not established');
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Connection;
use Brightzone\GremlinDriver\Message;
use Brightzone\GremlinDriver\Exceptions;
use Brightzone\GremlinDriver\Helper;
/**
* Unit testing of Gremlin-php documentation examples
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
* @link https://github.com/tinkerpop/rexster/wiki
*/
class RexsterTestExamples extends RexsterTestCase
{
/**
* Testing Example 1
*
* @return void
*/
public function testExample1()
{
$db = new Connection([
'host' => 'localhost',
'graph' => 'graph',
]);
//you can set $db->timeout = 0.5; if you wish
$db->open();
$db->send('g.V(2)');
//do something with result
$db->close();
}
/**
* Testing Example 1 bis
*
* @return void
*/
public function testExample1B()
{
$db = new Connection([
'host' => 'localhost',
'graph' => 'graph',
]);
//you can set $db->timeout = 0.5; if you wish
$db->open();
$db->message->gremlin = 'g.V(2)';
$db->send(); //automatically fetches the message
//do something with result
$db->close();
}
/**
* Testing Example 2
*
* @return void
*/
public function testExample2()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
]);
$db->open();
$db->message->bindValue('CUSTO_BINDING', 2);
$db->send('g.V(CUSTO_BINDING)'); //mix between Example 1 and 1B
//do something with result
$db->close();
}
/**
* Testing Example 3
*
* @return void
*/
public function testExample3()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
]);
$db->open();
$db->send('cal = 5+5', 'session');
$result = $db->send('cal', 'session'); // result = [10]
$this->assertEquals($result[0], 10, 'Error asserting proper result for example 3');
//do something with result
$db->close();
}
/**
* Testing Example 4
*
* @return void
*/
public function testExample4()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graphT',
]);
$db->open();
$originalCount = $db->send('n.V().count()');
$db->transactionStart();
$db->send('n.addVertex("name","michael")');
$db->send('n.addVertex("name","john")');
$db->transactionStop(FALSE); //rollback changes. Set to true to commit.
$newCount = $db->send('n.V().count()');
$this->assertEquals($newCount, $originalCount, 'Rollback was not done for eample 4');
$db->close();
}
/**
* Testing Example 5
*
* @return void
*/
public function testExample5()
{
$message = new Message;
$message->gremlin = 'g.V()';
$message->op = 'eval';
$message->processor = '';
$message->setArguments([
'language' => 'gremlin-groovy',
// ... etc
]);
$message->registerSerializer('\Brightzone\GremlinDriver\Serializers\Json');
$db = new Connection();
$db->open();
$db->send($message);
//do something with result
$db->close();
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Serializers\Json;
use Brightzone\GremlinDriver\Serializers\SerializerInterface;
/**
* Unit testing test case
* Allows for developpers to use command line args to set username and password for test database
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class RexsterTestCase extends \PHPUnit\Framework\TestCase
{
/**
* @var mixed the database username to use with tests, if any
*/
protected $username;
/**
* @var mixed the database password to use with tests, if any
*/
protected $password;
/**
* @var SerializerInterface the serializer to use
*/
protected static $serializer;
/**
* Set the serializer up here
*
* @return void
*/
public static function setUpBeforeClass()
{
static::$serializer = new Json();
}
/**
* Overriding setup to catch database arguments if set.
*
* @return void
*/
protected function setUp()
{
$this->username = getenv('DBUSER') ? getenv('DBUSER') : NULL;
$this->password = getenv('DBPASS') ? getenv('DBPASS') : NULL;
parent::setUp();
}
/**
* Call protected/private method of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $methodName Method name to call
* @param array $parameters Array of parameters to pass into method.
*
* @return mixed Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = [])
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(TRUE);
return $method->invokeArgs($object, $parameters);
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Serializers;
use Brightzone\GremlinDriver\InternalException;
use Brightzone\GremlinDriver\RequestMessage;
/**
* Gremlin-server PHP JSON Serializer class
* Builds and parses message body for Messages class
*
* @category DB
* @package Serializers
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class Gson3 implements SerializerInterface
{
/**
* @var string the name of the serializer
*/
public static $name = 'GRAPHSON3';
/**
* @var int Value of this serializer. Will be deprecated in TP3
*/
public static $mimeType = 'application/json';
/**
* @var array The native supported types that the serializer can convert to graphson
*/
protected static $supportedFromTypes = [
"string",
"boolean",
"double",
"integer",
"array",
"object",
"NULL",
];
/**
* @var array The GraphSON supported types that the serializer can deconvert from
*/
protected static $supportedGSTypes = [
"g:Int32",
"g:Int64",
"g:Date",
"g:Timestamp",
"g:UUID",
"g:Float",
"g:Double",
"g:List",
"g:Map",
"g:Set",
"g:Class",
"g:Path",
"g:Tree",
"g:Vertex",
"g:VertexProperty",
"tinker:graph",
"g:Edge",
"g:Property",
"g:T",
];
/**
* Serializes the data
*
* @param array &$data data to be serialized
*
* @return int length of generated string
* @throws InternalException
*/
public function serialize(&$data)
{
//convert the array into the correct format
$data = $this->convert($data);
$jsonEncoder = new Json;
return $jsonEncoder->serialize($data);
}
/**
* Unserializes the data
*
* @param mixed $data data to be unserialized
*
* @return array unserialized message
* @throws InternalException
*/
public function unserialize($data)
{
$jsonEncoder = new Json;
$data = $jsonEncoder->unserialize($data);
return $this->deconvert($data);
}
/**
* Get this serializer's Name
*
* @return string name of serializer
*/
public function getName()
{
return self::$name;
}
/**
* Get this serializer's value
* This will be deprecated with TP3 Gremlin-server
*
* @return string name of serializer
*/
public function getMimeType()
{
return self::$mimeType;
}
/**
* Transforms a variable into it's graphson 3.0 counterpart structure
*
* @param mixed $item the variable to convert to the graphson 3 structure
*
* @return array|string The same element in it's new form.
* @throws InternalException
*/
public function convert($item)
{
$converted = [];
$type = gettype($item);
if(in_array($type, self::$supportedFromTypes))
{
//use the type name to run the proper method
$method = "convert" . ucfirst($type);
$converted = $this->$method($item);
}
else
{
throw new InternalException("Item type '{$type}' is not currently supported by the serializer (" . __CLASS__ . ")", 500);
}
return $converted;
}
/**
* Convert a string into it's graphson 3.0 form
*
* @param string $string The string to convert
*
* @return string converted string (same as original currently)
*/
public function convertString($string)
{
return $string;
}
/**
* Convert an integer into it's graphson 3.0 form
*
* @param int $int The integer to convert
*
* @return array converted integer
*/
public function convertInteger($int)
{
$intSize = [
4 => "g:Int32",
8 => "g:Int64",
];
return [
"@type" => $intSize[PHP_INT_SIZE],
"@value" => $int,
];
}
/**
* Convert a NULL into it's graphson 3.0 form
*
* @param null $null The NULL to convert
*
* @return null converted NULL
*/
public function convertNULL($null)
{
return $null;
}
/**
* Convert an float/double into it's graphson 3.0 form
*
* @param double $double The float/double to convert
*
* @return array converted double
*/
public function convertDouble($double)
{
return [
"@type" => "g:Double",
"@value" => $double,
];
}
/**
* Convert a boolean into it's graphson 3.0 form
*
* @param bool $bool The boolean to convert
*
* @return bool converted boolean (same as original)
*/
public function convertBoolean($bool)
{
return $bool;
}
/**
* Convert an array into it's corresponding graphson 3.0 form(List or Map)
* This differentiates between Maps and Lists (we do not convert to Set)
*
* @param array $array The array to convert
*
* @return array converted array
* @throws InternalException
*/
public function convertArray($array)
{
$isList = (empty($array) || array_keys($array) === range(0, count($array) - 1));
return ($isList ? $this->convertList($array) : $this->convertMap($array));
}
/**
* Convert an array into a graphson 3.0 List
*
* @param array $array The array to convert
*
* @return array converted to GS3 List
* @throws InternalException
*/
public function convertList($array)
{
$converted = [
"@type" => "g:List",
"@value" => [],
];
foreach($array as $key => $value)
{
$converted["@value"][] = $this->convert($value);
}
return $converted;
}
/**
* Convert an array into a graphson 3.0 Map
*
* @param array $array The array to convert
*
* @return array converted to GS3 Map
* @throws InternalException
*/
public function convertMap($array)
{
$converted = [
"@type" => "g:Map",
"@value" => [],
];
foreach($array as $key => $value)
{
$converted["@value"][] = $this->convert($key);
$converted["@value"][] = $this->convert($value);
}
return $converted;
}
/**
* Convert an object into a graphson 3.0 Map
* Currently unsuported
*
* @param object $object The array to convert
*
* @return array the converted object
* @throws InternalException
*/
public function convertObject($object)
{
if($object instanceof RequestMessage)
{
$converted = [];
foreach($object->jsonSerialize() as $key => $value)
{
$converted[$key] = $this->convert($value);
}
return $converted;
}
else
{
throw new InternalException("Objects other than RequestMessage aren't currently supported by the " . self::$name . " serializer (" . __CLASS__ . "). Error produced by: " . get_class($object), 500);
}
}
/**
* Transforms a graphson 3.0 "variable" into it's native structure
*
* @param mixed $item the variable to convert to php native
*
* @return mixed The same element in it's new form.
* @throws InternalException
*/
public function deconvert($item)
{
$deconverted = [];
if(is_array($item) && isset($item["@type"]) && in_array($item["@type"], self::$supportedGSTypes))
{
//type exists in array and is found in our supported types
$method = "deconvert" . ucfirst(str_replace(["g:", "gx:", ":"], "", $item["@type"]));
$deconverted = $this->$method($item["@value"]);
}
elseif(is_array($item) && isset($item["@type"]) && !in_array($item["@type"], self::$supportedGSTypes))
{
//type exists in array but is not currently supported
throw new InternalException("Item type '{$item["@type"]}' is not currently supported by the serializer (" . __CLASS__ . ")", 500);
}
elseif(is_array($item) && !isset($item["@type"]))
{
//regular array, just pass it along
foreach($item as $key => $value)
{
$deconverted[$key] = $this->deconvert($value);
}
}
else
{
//regular variable, just pass it along.
$deconverted = $item;
}
return $deconverted;
}
/**
* Deconvert an Int32 into it's native form
*
* @param int $int The int to convert
*
* @return int deconverted Int32
*/
public function deconvertInt32($int)
{
return $int;
}
/**
* Deconvert an Int64 into it's native form
*
* @param int $int The int to convert
*
* @return int deconverted Int64
* @throws InternalException
*/
public function deconvertInt64($int)
{
if(PHP_INT_SIZE == 4)
{
throw new InternalException("You are running a 32bit PHP and cannot convert the 64bit Int provided in the GraphSON 3.0");
}
return $int;
}
/**
* Deconvert a Double into it's native form
*
* @param double $double The double to convert
*
* @return double deconverted Double
*/
public function deconvertDouble($double)
{
return $double;
}
/**
* Deconvert a Float into it's native form
*
* @param double $float The float to convert
*
* @return double deconverted Float
*/
public function deconvertFloat($float)
{
return $this->deconvertDouble($float);
}
/**
* Deconvert a Timestamp into it's native form
*
* @param int $timestamp The Timestamp to convert
*
* @return int deconverted Timestamp
*/
public function deconvertTimestamp($timestamp)
{
return $this->deconvertInt32($timestamp);
}
/**
* Deconvert a Date into it's native form
*
* @param int $date The date to convert
*
* @return int deconverted Date
*/
public function deconvertDate($date)
{
return $this->deconvertInt32($date);
}
/**
* Deconvert a UUID into it's native form
*
* @param string $uuid The UUID to convert
*
* @return string deconverted UUID
*/
public function deconvertUUID($uuid)
{
return $uuid;
}
/**
* Deconvert a List into it's native form (Array)
*
* @param array $list The List to convert
*
* @return array deconverted List
* @throws InternalException
*/
public function deconvertList($list)
{
$deconverted = [];
foreach($list as $value)
{
$deconverted[] = $this->deconvert($value);
}
return $deconverted;
}
/**
* Deconvert a Set into it's native form (Array)
*
* @param array $set The Set to convert
*
* @return array deconverted Set
* @throws InternalException
*/
public function deconvertSet($set)
{
return $this->deconvertList($set);
}
/**
* Deconvert a Map into it's native form (Array)
*
* @param array $map The Map to convert
*
* @return array deconverted Map
* @throws InternalException
*/
public function deconvertMap($map)
{
$deconverted = [];
if(count($map) % 2 != 0)
{
throw new InternalException("Failed to deconvert Map item from graphson 3.0. Odd number of elements found (should be even)", 500);
}
while(0 < count($map))
{
$key = $this->deconvert(array_shift($map));
$value = $this->deconvert(array_shift($map));
if(!is_numeric($key) && !is_string($key))
{
throw new InternalException("Failed to deconvert Map item from graphson 3.0. A key was of type [" . gettype($key) . "], only Integers and Strings are supported", 500);
}
$deconverted[$key] = $value;
}
return $deconverted;
}
/**
* Deconvert a Property into it's native form
*
* @param array $prop The Property to convert
*
* @return mixed deconverted Property
* @throws InternalException
*/
public function deconvertProperty($prop)
{
return $this->deconvert($prop);
}
/**
* Deconvert a VertexProperty into it's native form
*
* @param array $vertexProp The VertexProperty to convert
*
* @return mixed deconverted VertexProperty
* @throws InternalException
*/
public function deconvertVertexProperty($vertexProp)
{
return $this->deconvert($vertexProp);
}
/**
* Deconvert a Path into it's native form
*
* @param array $path The Path to convert
*
* @return array deconverted Path
* @throws InternalException
*/
public function deconvertPath($path)
{
return $this->deconvert($path);
}
/**
* Deconvert a TinkerGraph into it's native form
*
* @param array $tinkergraph The TinkerGraph to convert
*
* @return array deconverted TinkerGraph
* @throws InternalException
*/
public function deconvertTinkergraph($tinkergraph)
{
return $this->deconvert($tinkergraph);
}
/**
* Deconvert a Tree into it's native form
*
* @param array $tree The Tree to convert
*
* @return array deconverted Tree
* @throws InternalException
*/
public function deconvertTree($tree)
{
$deconvert = [];
$result = $this->deconvert($tree);
foreach($result as $value)
{
if(isset($value["key"]) && isset($value["key"]["id"]))
{
$deconvert[$value["key"]["id"]] = $value;
}
else
$deconvert[] = $value;
}
return $deconvert;
}
/**
* Deconvert a Class into it's native form
*
* @param string $classname The class to convert
*
* @return void
* @throws InternalException
*/
public function deconvertClass($classname)
{
throw new InternalException("The GraphSON 3.0 contained a Class element ({$classname}). Classes are not currently supported");
}
/**
* Deconvert a Vertex into it's native form
*
* @param array $vertex The Vertex to convert
*
* @return array deconverted Vertex
* @throws InternalException
*/
public function deconvertVertex($vertex)
{
$vertex["type"] = "vertex";
return $this->deconvert($vertex);
}
/**
* Deconvert a Edge into it's native form
*
* @param array $edge The Edge to convert
*
* @return array deconverted Edge
* @throws InternalException
*/
public function deconvertEdge($edge)
{
$edge["type"] = "edge";
return $this->deconvert($edge);
}
/**
* Deconvert a Token (T) into it's string form
*
* @param string $t the token to deconvert
*
* @return string either "id" or "label"
*/
public function deconvertT($t)
{
return $t;
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver;
use Brightzone\GremlinDriver\Serializers\SerializerInterface;
/**
* Gremlin-server PHP Driver client Messages class
* Builds and parses binary messages for communication with Gremlin-server
* Use example:
*
* ~~~
* $message = new Message;
* $message->gremlin = 'g.V';
* $message->op = 'eval';
* $message->processor = '';
* $message->setArguments(['language'=>'gremlin-groovy']);
* $message->registerSerializer('\Brightzone\GremlinDriver\Serializers\Json');
* // etc ...
* $db = new Connection;
* $db->open();
* $db->send($message);
* ~~~
*
* @category DB
* @package GremlinDriver
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*
* @property string $gremlin The gremlin query for this message
* @property string $op The operation that should be performed by this message
* @property string $processor The opProcessor to use for this message
* @property string $requestUuid The UUID for the individual request
*
*/
class Message
{
/**
* @var array basic message configuration
* ie: op,processor,requestId, etc..
*/
public $configuration = [];
/**
* @var array args of the message
*/
public $args = [];
/**
* @var array list of serializers loaded for this instance
*/
private $_serializers = [];
/**
* Overriding construct to populate _serializer
*/
public function __construct()
{
//set default values for message
$this->setDefaults();
}
/**
* Sets default values to this message
* The values are :
* - gremlin : ''
* - op : 'eval'
* - processor : ''
*
* @return void
*/
private function setDefaults()
{
$this->gremlin = '';
$this->op = 'eval';
$this->processor = '';
}
/**
* magic setter to populate $this->configuration + gremlin arg
*
* @param string $name name of the variable you want to set
* @param string $value value of the variable you want to set
*
* @return void
*/
public function __set($name, $value)
{
if($name == 'gremlin')
{
$this->args['gremlin'] = $value;
}
else
{
$this->configuration[$name] = $value;
}
}
/**
* magic getter to fetch $this->configuration + gremlin arg
*
* @param string $name name of the variable you want to get
*
* @return string
* @throws InternalException
*/
public function __get($name)
{
if($name == 'gremlin' && isset($this->args['gremlin']))
{
return $this->args['gremlin'];
}
else
{
if(isset($this->configuration[$name]))
{
return $this->configuration[$name];
}
}
throw new InternalException ("Property {$name} is not defined");
}
/**
* magic isset to return proper setting of $this->configuration + gremlin arg
*
* @param string $name name of the variable you want to check
*
* @return bool
*/
public function __isset($name)
{
if($name == 'gremlin')
{
return isset($this->args['gremlin']);
}
else
{
return isset($this->configuration[$name]);
}
}
/**
* Setter method for arguments
* This will replace existing entries.
*
* @param array $array collection of arguments
*
* @return void
*/
public function setArguments($array)
{
$this->args = array_merge($this->args, $array);
}
/**
* Create and set request UUID
*
* @return string the UUID
*/
public function createUuid()
{
return $this->requestUuid = Helper::createUuid();
}
/**
* Constructs full binary message for use in script execution
*
* @return string Returns binary data to be packed and sent to socket
* @throws InternalException
*/
public function buildMessage()
{
//lets start by packing message
$this->createUuid();
//build message array
$message = new RequestMessage([
'requestId' => $this->requestUuid,
'processor' => $this->processor,
'op' => $this->op,
'args' => $this->args,
]);
//serialize message
if(!isset($this->_serializers['default']))
{
throw new InternalException("No default serializer set", 500);
}
$this->_serializers['default']->serialize($message);
$mimeType = $this->_serializers['default']->getMimeType();
$finalMessage = pack('C', strlen($mimeType)) . $mimeType . $message;
return $finalMessage;
}
/**
* Parses full message (including outter envelope)
*
* @param string $payload payload from the server response
* @param bool $isBinary whether we should expect binary data (TRUE) or plein text (FALSE)
*
* @return array Array containing all results
*/
public function parse($payload, $isBinary)
{
if($isBinary)
{
list($mimeLength) = array_values(unpack('C', $payload[0]));
$mimeType = substr($payload, 1, $mimeLength);
$serializer = $this->getSerializer($mimeType);
$payload = substr($payload, $mimeLength + 1, strlen($payload));
return $serializer->unserialize($payload);
}
return $this->_serializers['default']->unserialize($payload);
}
/**
* Get the serializer object depending on a provided mimeType
*
* @param string $mimeType the mimeType of the serializer you want to retrieve
*
* @return SerializerInterface serializer object or throw error if none exist.
* @throws InternalException if no serializer is set for the provided mimeType
*/
public function getSerializer($mimeType = '')
{
if($mimeType == '')
{
return $this->_serializers['default'];
}
foreach($this->_serializers as $serializer)
{
if($serializer->getMimeType() == $mimeType)
{
return $serializer;
}
}
throw new InternalException("No serializer found for mimeType: [" . $mimeType . "]", 500);
}
/**
* Register a new serializer to this object
*
* @param mixed $value either a serializer object or a string of the class name (with namespace)
* @param bool $default whether or not to use this serializer as the default one
*
* @return void
* @throws InternalException
*/
public function registerSerializer($value, $default = TRUE)
{
if(is_string($value))
{
if(class_exists($value))
{
$value = new $value();
}
else
{
throw new InternalException("Class [" . $value . "] doesn't exist", 500);
}
}
if(in_array('Brightzone\GremlinDriver\Serializers\SerializerInterface', class_implements($value)))
{
if($default)
{
$this->_serializers['default'] = $value;
}
$this->_serializers[$value->getMimeType()] = $value;
}
else
{
throw new InternalException("Serializer could not be set to [" . get_class($value) . "]. Check that the class implements SerializerInterface", 500);
}
}
/**
* Binds a value to be used inside gremlin script
*
* @param string $bind The binding name
* @param mixed $value the value that the binding name refers to
*
* @return void
*/
public function bindValue($bind, $value)
{
if(!isset($this->args['bindings']))
{
$this->args['bindings'] = [];
}
$this->args['bindings'][$bind] = $value;
}
/**
* Clear this message and start anew
*
* @return void
*/
public function clear()
{
$this->configuration = [];
$this->args = [];
$this->setDefaults();
}
}
<file_sep><?php
/**
* This file is meant to run PHPUNIT from a web interface. (ie: by running this file)
* It is useful for those who do not have access to the command line (wamp, etc.)
*
* Just make the gremlin-php folder accessible on the web path and load this php file in your browser
*/
require_once(__DIR__ . '/../vendor/autoload.php');
echo "<pre>";
if(class_exists("PHPUnit_TextUI_Command"))
{
$command = new \PHPUnit_TextUI_Command;
}
else
{
$command = new \PHPUnit\TextUI\Command;
}
$command->run(['phpunit', '--conf', '../build/phpunit.xml'], TRUE);
echo "</pre>";<file_sep><?php
namespace Brightzone\GremlinDriver\Tests\Stubs;
use \Brightzone\GremlinDriver\Connection;
/**
* Class IncorrectlyFormattedConnection
* Will incorrectly pack the websocket message
*
* @author <NAME> <<EMAIL>>
* @package Brightzone\GremlinDriver\Tests\Stubs
*/
class IncorrectlyFormattedConnection extends Connection
{
/**
* Incorrectly packing the message
*
* @param string $payload
* @param string $type
* @param bool $masked
*
* @return string
*/
protected function webSocketPack($payload, $type = 'binary', $masked = TRUE)
{
return "not a correctly formatted message";
}
}<file_sep><?php
namespace Brightzone\GremlinDriver;
use \Exception;
/**
* Gremlin-server PHP Driver client Exception class
*
* @category DB
* @package GremlinDriver
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
* @link http://tinkerpop.incubator.apache.org/docs/3.0.1-incubating/#_developing_a_driver
*/
class ServerException extends Exception
{
const NO_CONTENT = 204;
const UNAUTHORIZED = 401;
const MALFORMED_REQUEST = 498;
const INVALID_REQUEST_ARGUMENTS = 499;
const SERVER_ERROR = 500;
const SCRIPT_EVALUATION_ERROR = 597;
const SERVER_TIMEOUT = 598;
const SERVER_SERIALIZATION_ERROR = 599;
/**
* Overriding construct
*
* @param string $message The error message to throw
* @param int $code The error code to throw
* @param Exception $previous The previous exception if there is one that triggered this error
*
* @return void
*/
public function __construct($message, $code = 0, Exception $previous = NULL)
{
$message = $this->getMessagePerCode($code) . ' : ' . $message;
parent::__construct($message, $code, $previous);
}
/**
* Lets add more information to the error message thrown by using the Error Code
*
* @param int $code The error code we want to generate a message for.
*
* @return string The error message that corresponds to the error code
*/
private function getMessagePerCode($code)
{
$messages = [
self::NO_CONTENT => "The server processed the request but there is no result to return (e.g. an {@link Iterator} with no elements).",
self::UNAUTHORIZED => "The request attempted to access resources that the requesting user did not have access to.",
self::MALFORMED_REQUEST => "The request message was not properly formatted which means it could not be parsed at all or the 'op' code was not recognized such that Gremlin Server could properly route it for processing. Check the message format and retry the request.",
self::INVALID_REQUEST_ARGUMENTS => "The request message was parseable, but the arguments supplied in the message were in conflict or incomplete. Check the message format and retry the request.",
self::SERVER_ERROR => "A general server error occurred that prevented the request from being processed.",
self::SCRIPT_EVALUATION_ERROR => "The script submitted for processing evaluated in the ScriptEngine with errors and could not be processed. Check the script submitted for syntax errors or other problems and then resubmit.",
self::SERVER_TIMEOUT => "The server exceeded one of the timeout settings for the request and could therefore only partially responded or did not respond at all.",
self::SERVER_SERIALIZATION_ERROR => "The server was not capable of serializing an object that was returned from the script supplied on the request. Either transform the object into something Gremlin Server can process within the script or install mapper serialization classes to Gremlin Server.",
];
return isset($messages[$code]) ? $messages[$code] : '';
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
/**
* Unit testing of Gremlin-php
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class RexsterTestWithGS3 extends GraphSon3Test
{
}
<file_sep><?php
namespace Brightzone\GremlinDriver;
use Brightzone\GremlinDriver\Serializers\Json;
use Brightzone\GremlinDriver\Serializers\SerializerInterface;
/**
* Gremlin-server PHP Driver client Connection class
*
* Example of basic use:
*
* ~~~
* $connection = new Connection(['host' => 'localhost']);
* $connection->open();
* $resultSet = $connection->send('g.V'); //returns array with results
* ~~~
*
* Some more customising of message to send can be done with the message object
*
* ~~~
* $connection = new Connection(['host' => 'localhost']);
* $connection->open();
* $connection->message->gremlin = 'g.V';
* $connection->send();
* ~~~
*
* See Message for more details
*
* @category DB
* @package GremlinDriver
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
* @link https://github.com/tinkerpop/rexster/wiki
*/
class Connection
{
/**
* @var string Contains the host information required to connect to the database.
*
* Default: localhost
*/
public $host = 'localhost';
/**
* @var string Contains port information to connect to the database
*
* Default : 8182
*/
public $port = 8182;
/**
* @var string the username for establishing DB connection. Defaults to NULL.
*/
public $username;
/**
* @var string the password for establishing DB connection. Defaults to NULL.
*/
public $password;
/**
* @var string the graph to use.
*/
public $graph;
/**
* @var float timeout to use for connection to Rexster. If not set the timeout set in php.ini will be used:
* ini_get("default_socket_timeout")
*/
public $timeout;
/**
* @var Message Message object
*/
public $message;
/**
* @var array Aliases to be used for this connection.
* Allows users to set up whichever character on the db end such as "g" and reference it with another alias.
*/
public $aliases = [];
/**
* @var bool whether or not the driver should return empty result sets as an empty array
* (the default behavior is to propagate the exception from the server - yes the server throws exceptions on empty
* result sets.)
*/
public $emptySet = FALSE;
/**
* @var bool tells us if we're inside a transaction
*/
protected $_inTransaction = FALSE;
/**
* @var string The session ID for this connection.
* Session ID allows us to access variable bindings made in previous requests. It is binary data
*/
protected $_sessionUuid;
/**
* @var resource rexpro socket connection
*/
protected $_socket;
/**
* @var bool|array whether or not we're using ssl. If an array is set it should correspond to a
* stream_context_create() array.
*/
public $ssl = FALSE;
/**
* @var string which sasl mechanism to use for authentication. Can be either PLAIN or GSSAPI.
* This is ignored by gremlin-server by default but some custom server implementations may use this
*/
public $saslMechanism = "PLAIN";
/**
* @var string the strategy to use for retry
*/
public $retryStrategy = 'linear';
/**
* @var int the number of attempts before total failure
*/
public $retryAttempts = 1;
/**
* @var bool whether or not to accept different return formats from the one the message was sent with.
* This is an extremely rare occurrence. Only happens if using a custom serializer.
*/
private $_acceptDiffResponseFormat = FALSE;
/**
* Overloading constructor to instantiate a Message instance and
* provide it with a default serializer.
*
* @param array $options The class options
*/
public function __construct($options = [])
{
foreach($options as $key => $value)
{
$this->$key = $value;
}
//create a message object
$this->message = new Message();
//assign a default serializer to it
$this->message->registerSerializer(new Json, TRUE);
}
/**
* Connects to socket and starts a session with gremlin-server
*
* @return bool TRUE on success FALSE on error
*/
public function open()
{
if($this->_socket === NULL)
{
$this->connectSocket(); // will throw error on failure.
return $this->makeHandshake();
}
return FALSE;
}
/**
* Sends data over socket
*
* @param Message $msg Object containing the message to send
*
* @return bool TRUE if success
*/
private function writeSocket($msg = NULL)
{
if($msg === NULL)
{
$msg = $this->message;
}
$msg = $this->webSocketPack($msg->buildMessage());
$write = @fwrite($this->_socket, $msg);
if($write === FALSE)
{
$this->error(__METHOD__ . ': Could not write to socket', 500, TRUE);
}
return TRUE;
}
/**
* Make Original handshake with the server
*
* @param bool $origin whether or not to provide the origin header. currently unsupported
*
* @return bool TRUE on success FALSE on failure
*/
protected function makeHandshake($origin = FALSE)
{
try
{
$protocol = 'http';
if($this->ssl)
{
$protocol = 'ssl';
}
$key = base64_encode(Helper::generateRandomString(16, FALSE, TRUE));
$header = "GET /gremlin HTTP/1.1\r\n";
$header .= "Upgrade: websocket\r\n";
$header .= "Connection: Upgrade\r\n";
$header .= "Sec-WebSocket-Key: " . $key . "\r\n";
$header .= "Host: " . $this->host . "\r\n";
if($origin !== TRUE)
{
$header .= "Sec-WebSocket-Origin: " . $protocol . "://" . $this->host . ":" . $this->port . "\r\n";
}
$header .= "Sec-WebSocket-Version: 13\r\n\r\n";
@fwrite($this->_socket, $header);
$response = @fread($this->_socket, 1500);
if(!$response)
{
$this->error("Couldn't get a response from server", 500);
}
preg_match('#Sec-WebSocket-Accept:\s(.*)$#miU', $response, $matches);
$keyAccept = trim($matches[1]);
$expectedResponse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
return ($keyAccept === $expectedResponse) ? TRUE : FALSE;
}
catch(\Exception $e)
{
$this->error("Could not finalise handshake, Maybe the server was unreachable", 500, TRUE);
return FALSE;
}
}
/**
* Get and parse message from the socket
*
* @return array the message returned from the db
*/
private function socketGetMessage()
{
$data = $head = $this->streamGetContent(1);
$head = unpack('C*', $head);
//extract opcode from first byte
$isBinary = (($head[1] & 15) == 2) && $this->_acceptDiffResponseFormat;
$data .= $maskAndLength = $this->streamGetContent(1);
list($maskAndLength) = array_values(unpack('C', $maskAndLength));
//set first bit to 0
$length = $maskAndLength & 127;
$maskSet = FALSE;
if($maskAndLength & 128)
{
$maskSet = TRUE;
}
if($length == 126)
{
$data .= $payloadLength = $this->streamGetContent(2);
list($payloadLength) = array_values(unpack('n', $payloadLength)); // S for 16 bit int
}
elseif($length == 127)
{
$data .= $payloadLength = $this->streamGetContent(8);
//lets save it as two 32 bit integers and reatach using bitwise operators
//we do this as pack doesn't support 64 bit packing/unpacking.
list($higher, $lower) = array_values(unpack('N2', $payloadLength));
$payloadLength = $higher << 32 | $lower;
}
else
{
$payloadLength = $length;
}
//get mask
if($maskSet)
{
$data .= $mask = $this->streamGetContent(4);
}
// get payload
$data .= $payload = $this->streamGetContent($payloadLength);
if($maskSet)
{
//unmask payload
$payload = $this->unmask($mask, $payload);
}
//ugly code but we can seperate the two errors this way
if($head === FALSE || $payload === FALSE || $maskAndLength === FALSE
|| $payloadLength === FALSE || ($maskSet === TRUE && $mask === FALSE)
)
{
$this->error('Could not stream contents', 500);
}
if(empty($head) || empty($payload) || empty($maskAndLength)
|| empty($payloadLength) || ($maskSet === TRUE && empty($mask)))
{
$this->error('Empty reply. Most likely the result of an irregular request. (Check custom Meta, or lack of in the case of a non-isolated query)', 500);
}
//now that we have the payload lets parse it
try
{
$unpacked = $this->message->parse($payload, $isBinary);
}
catch(\Exception $e)
{
$this->error($e->getMessage(), $e->getCode(), TRUE);
}
return $unpacked;
}
/**
* Recieves binary data over the socket and parses it
*
* @return array PHP native result from server
*/
protected function socketGetUnpack()
{
$fullData = [];
do
{
$unpacked = $this->socketGetMessage();
// If this is an authentication challenge, lets meet it and return the result
if($unpacked['status']['code'] === 407)
{
return $this->authenticate();
}
if($unpacked['status']['code'] === 204 && $this->emptySet)
{
return [];
}
//handle errors
if($unpacked['status']['code'] !== 200 && $unpacked['status']['code'] !== 206)
{
$this->error($unpacked['status']['message']
. "\n\n =================== SERVER TRACE ========================= \n"
. var_export($unpacked['status']['attributes'], TRUE)
. "\n ============================================================ \n", $unpacked['status']['code']);
}
foreach($unpacked['result']['data'] as $row)
{
$fullData[] = $row;
}
}
while($unpacked['status']['code'] === 206);
return $fullData;
}
/**
* Opens socket
*
* @return bool TRUE on success
*/
private function connectSocket()
{
$protocol = 'tcp';
$context = stream_context_create([]);
if($this->ssl)
{
$protocol = 'ssl';
if(is_array($this->ssl) && !empty($this->ssl))
{
$context = stream_context_create($this->ssl);
}
}
$fp = @stream_socket_client(
$protocol . '://' . $this->host . ':' . $this->port,
$errno,
$errorMessage,
$this->timeout ? $this->timeout : ini_get("default_socket_timeout"),
STREAM_CLIENT_CONNECT,
$context
);
if(!$fp)
{
$this->error($errorMessage, $errno, TRUE);
return FALSE;
}
$this->_socket = $fp;
return TRUE;
}
/**
* Constructs and sends a Message entity or gremlin script to the server without waiting for a response.
*
*
* @param mixed $msg (Message|String|NULL) the message to send, NULL means use $this->message
* @param string $processor opProcessor to use.
* @param string $op Operation to run against opProcessor.
* @param array $args Arguments to overwrite.
* @param bool $expectResponse Arguments to overwrite.
*
* @return void
* @throws \Exception
*/
public function run($msg = NULL, $processor = '', $op = 'eval', $args = [], $expectResponse = TRUE)
{
try
{
$this->prepareWrite($msg, $processor, $op, $args);
if($expectResponse)
{
$this->socketGetUnpack();
}
}
catch(\Exception $e)
{
// on run lets ignore anything coming back from the server
if(!($e instanceof ServerException))
{
throw $e;
}
}
//reset message and remove binds
$this->message->clear();
}
/**
* Private function that Constructs and sends a Message entity or gremlin script to the server and then waits for
* response
*
* The main use here is to centralise this code for run() and send()
*
*
* @param mixed $msg (Message|String|NULL) the message to send, NULL means use $this->message
* @param string $processor opProcessor to use.
* @param string $op Operation to run against opProcessor.
* @param array $args Arguments to overwrite.
*
* @return array reply from server.
*/
private function prepareWrite($msg, $processor, $op, $args)
{
if(!($msg instanceof Message) || $msg === NULL)
{
//lets make a script message:
$this->message->gremlin = $msg === NULL ? $this->message->gremlin : $msg;
$this->message->op = $op === 'eval' ? $this->message->op : $op;
$this->message->processor = $processor === '' ? $this->message->processor : $processor;
if($this->_inTransaction === TRUE || $this->message->processor == 'session')
{
$this->getSession();
$this->message->processor = $processor == '' ? 'session' : $processor;
$this->message->setArguments(['session' => $this->_sessionUuid]);
}
if((isset($args['aliases']) && !empty($args['aliases'])) || !empty($this->aliases))
{
$args['aliases'] = isset($args['aliases']) ? array_merge($args['aliases'], $this->aliases) : $this->aliases;
}
$this->message->setArguments($args);
}
else
{
$this->message = $msg;
}
$this->writeSocket();
}
/**
* Constructs and sends a Message entity or gremlin script to the server and then waits for response
*
*
* @param mixed $msg (Message|String|NULL) the message to send, NULL means use $this->message
* @param string $processor opProcessor to use.
* @param string $op Operation to run against opProcessor.
* @param array $args Arguments to overwrite.
*
* @return array reply from server.
* @throws ServerException
*/
public function send($msg = NULL, $processor = '', $op = 'eval', $args = [])
{
try
{
$workload = new Workload(function($db, $msg, $processor, $op, $args) {
$db->prepareWrite($msg, $processor, $op, $args);
//lets get the response
return $db->socketGetUnpack();
}, [$this, $msg, $processor, $op, $args]);
$response = $workload->linearRetry($this->retryAttempts);
//reset message and remove binds
$this->message->clear();
return $response;
}
catch(\Exception $e)
{
if(!($e instanceof ServerException))
{
$this->error($e->getMessage(), $e->getCode(), TRUE);
}
throw $e;
}
}
/**
* Close connection to server
* This closes the current session on the server then closes the socket
*
* @return bool TRUE on success
*/
public function close()
{
if(is_resource($this->_socket))
{
if($this->_inTransaction === TRUE)
{
//do not commit changes changes;
$this->transactionStop(FALSE);
}
$this->closeSession();
$write = @fwrite($this->_socket, $this->webSocketPack("", 'close'));
if($write === FALSE)
{
$this->error('Could not write to socket', 500, TRUE);
}
@stream_socket_shutdown($this->_socket, STREAM_SHUT_RDWR); //ignore error
$this->_socket = NULL;
return TRUE;
}
return FALSE;
}
/**
* Closes an open session if it exists
* You can use this to close open sessions on the server end. This allows to free up threads on the server end.
*
* @return void
*/
public function closeSession()
{
if($this->isSessionOpen())
{
$msg = new Message();
$msg->op = "close";
$msg->processor = "session";
$msg->setArguments(['session' => $this->getSession()]);
$msg->registerSerializer(new Json());
$this->run($msg, NULL, NULL, NULL, FALSE); // Tell run not to expect a return
$this->_sessionUuid = NULL;
}
}
/**
* Start a transaction.
* Transaction start only makes sens if committing is set to manual on the server.
* Manual is not the default setting so we will assume a session UUID must exists
*
* @return bool TRUE on success FALSE on failure
*/
public function transactionStart()
{
if(!isset($this->graph) || (isset($this->graph) && $this->graph == ''))
{
$this->error("A graph object needs to be specified", 500, TRUE);
}
if($this->_inTransaction)
{
$this->message->gremlin = $this->graph . '.tx().rollback()';
$this->send();
$this->_inTransaction = FALSE;
$this->error(__METHOD__ . ': already in transaction, rolling changes back.', 500, TRUE);
}
//if we aren't in transaction we need to start a session
$this->getSession();
$this->message->setArguments(['session' => $this->_sessionUuid]);
$this->message->processor = 'session';
$this->message->gremlin = $this->graph . '.tx().open()';
$this->send();
$this->_inTransaction = TRUE;
return TRUE;
}
/**
* Run a callback in a transaction.
* The advantage of this is that it allows for fail-retry strategies
*
* @param callable $callback the code to execute within the scope of this transaction
* @param array $params The params to pass to the callback
*
* @return mixed the return value of the provided callable
*/
public function transaction(callable $callback, $params = [])
{
//create a callback from the callback to introduce transaction handling
$workload = new Workload(function($db, $callback, $params) {
try
{
$db->transactionStart();
$result = call_user_func_array($callback, $params);
if($db->_inTransaction)
{
$db->transactionStop(TRUE);
}
return $result;
}
catch(\Exception $e)
{
/**
* We need to catch the exception again before the workload catches it
* this allows us to terminate the transaction properly before each retry attempt
*/
if($db->_inTransaction)
{
$db->transactionStop(FALSE);
}
throw $e;
}
},
[$this, $callback, $params]
);
$result = $workload->linearRetry($this->retryAttempts);
return $result;
}
/**
* End a transaction
*
* @param bool $success should the transaction commit or revert changes
*
* @return bool TRUE on success FALSE on failure.
*/
public function transactionStop($success = TRUE)
{
if(!$this->_inTransaction || !isset($this->_sessionUuid))
{
$this->error(__METHOD__ . ' : No ongoing transaction/session.', 500, TRUE);
}
//send message to stop transaction
if($success)
{
$this->message->gremlin = $this->graph . '.tx().commit()';
}
else
{
$this->message->gremlin = $this->graph . '.tx().rollback()';
}
$this->send();
$this->_inTransaction = FALSE;
return TRUE;
}
/**
* Checks if the socket is currently open
*
* @return bool TRUE if it is open FALSE if not
*/
public function isConnected()
{
return $this->_socket !== NULL;
}
/**
* Make sure the session is closed on destruction of the object
*
* @return void
*/
public function __destruct()
{
$this->close();
}
/**
* Constructs the Websocket packet frame
*
* @param string $payload string or binary, the message to insert into the packet.
* @param string $type the type of frame you send (usualy text or string) ie: opcode
* @param bool $masked whether to mask the packet or not.
*
* @return string Binary message to pump into the socket
*/
private function webSocketPack($payload, $type = 'binary', $masked = TRUE)
{
$frameHead = [];
$payloadLength = strlen($payload);
switch($type)
{
case 'text':
// first byte indicates FIN, Text-Frame (10000001):
$frameHead[0] = 129;
break;
case 'binary':
// first byte indicates FIN, Binary-Frame (10000010):
$frameHead[0] = 130;
break;
case 'close':
// first byte indicates FIN, Close Frame(10001000):
$frameHead[0] = 136;
break;
case 'ping':
// first byte indicates FIN, Ping frame (10001001):
$frameHead[0] = 137;
break;
case 'pong':
// first byte indicates FIN, Pong frame (10001010):
$frameHead[0] = 138;
break;
}
// set mask and payload length (using 1, 3 or 9 bytes)
if($payloadLength > 65535)
{
$payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
$frameHead[1] = ($masked === TRUE) ? 255 : 127;
for($i = 0; $i < 8; $i++)
{
$frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
}
// most significant bit MUST be 0 (close connection if frame too big)
if($frameHead[2] > 127)
{
$this->close();
return FALSE;
}
}
elseif($payloadLength > 125)
{
$payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
$frameHead[1] = ($masked === TRUE) ? 254 : 126;
$frameHead[2] = bindec($payloadLengthBin[0]);
$frameHead[3] = bindec($payloadLengthBin[1]);
}
else
{
$frameHead[1] = ($masked === TRUE) ? $payloadLength + 128 : $payloadLength;
}
// convert frame-head to string:
foreach(array_keys($frameHead) as $i)
{
$frameHead[$i] = chr($frameHead[$i]);
}
if($masked === TRUE)
{
// generate a random mask:
$mask = [];
for($i = 0; $i < 4; $i++)
{
$mask[$i] = chr(rand(0, 255));
}
$frameHead = array_merge($frameHead, $mask);
}
$frame = implode('', $frameHead);
// append payload to frame:
for($i = 0; $i < $payloadLength; $i++)
{
$frame .= ($masked === TRUE) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}
return $frame;
}
/**
* Unmask data. Usualy the payload
*
* @param string $mask binary key to use to unmask
* @param string $data data that needs unmasking
*
* @return string unmasked data
*/
private function unmask($mask, $data)
{
$unmaskedPayload = '';
for($i = 0; $i < strlen($data); $i++)
{
if(isset($data[$i]))
{
$unmaskedPayload .= $data[$i] ^ $mask[$i % 4];
}
}
return $unmaskedPayload;
}
/**
* Custom error throwing method.
* We use this to run rollbacks when errors occur
*
* @param string $description Description of the error
* @param int $code The error code
* @param bool $internal true for internal, false for server error
*
* @return void
* @throws InternalException
* @throws ServerException
*/
private function error($description, $code, $internal = FALSE)
{
//Errors will rollback once the connection is destroyed. No need to rollback here.
if($internal)
{
throw new InternalException($description, $code);
}
else
{
throw new ServerException($description, $code);
}
}
/**
* Return whether or not this cnnection object is in transaction mode
*
* @return bool TRUE if in transaction, FALSE otherwise
*/
public function inTransaction()
{
return $this->_inTransaction;
}
/**
* Retrieve the current session UUID
*
* @return string current UUID
*/
public function getSession()
{
if(!$this->isSessionOpen())
{
$this->_sessionUuid = Helper::createUuid();
}
return $this->_sessionUuid;
}
/**
* Checks if the session is currently open
*
* @return bool TRUE if it's open is FALSE if not.
*/
public function isSessionOpen()
{
if(!isset($this->_sessionUuid))
{
return FALSE;
}
return TRUE;
}
/**
* Builds an authentication message when challenged by the server
* Once you respond and authenticate you will receive the response for the request you made prior to the challenge
*
* @return array The server response.
*/
protected function authenticate()
{
$msg = new Message();
$msg->op = "authentication";
$args = [
'sasl' => base64_encode(utf8_encode("\x00" . trim($this->username) . "\x00" . trim($this->password))),
'saslMechanism' => $this->saslMechanism,
];
if($this->isSessionOpen())
{
$msg->processor = "session";
$args["session"] = $this->getSession();
}
else
{
$msg->processor = "";
}
$msg->setArguments($args);
//['session' => $this->_sessionUuid]
$msg->registerSerializer($this->message->getSerializer());
return $this->send($msg);
}
/**
* Custom stream get content that will wait for the content to be ready before streaming it
* This corrects an issue with hhvm handling streams in non-blocking mode.
*
* @param int $limit the length of the data we want to get from the stream
* @param int $offset the offset to start reading the stream from
*
* @return string the data streamed from the socket
*/
private function streamGetContent($limit, $offset = -1)
{
$buffer = NULL;
$bufferedSize = 0;
do
{
$buffer .= stream_get_contents($this->_socket, $limit - $bufferedSize, $offset);
$bufferedSize = strlen($buffer);
}
while($bufferedSize < $limit);
return $buffer;
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests\Stubs;
use Brightzone\GremlinDriver\InternalException;
use \Brightzone\GremlinDriver\Message;
use Brightzone\GremlinDriver\RequestMessage;
/**
* Class IncorrectlyFormattedMessage
* Will incorrectly pack the message
*
* @author <NAME> <<EMAIL>>
* @package Brightzone\GremlinDriver\Tests\Stubs
*/
class IncorrectlyFormattedMessage extends Message
{
/**
* @var bool throw an error on parse or not
*/
public $throwErrorOnParse = FALSE;
/**
* incorrectly format sent message
* @return string
*/
public function buildMessage()
{
$finalMessage = pack('C', strlen("application/json")) . 5 . "somethinglongerthan5";
return $finalMessage;
}
/**
* Throw an error for testing purposes
*
* @param string $payload
* @param bool $isBinary
*
* @return void
* @throws InternalException
*/
public function parse($payload, $isBinary)
{
if($this->throwErrorOnParse)
{
throw new InternalException("Some test error", 500);
}
return parent::parse($payload, $isBinary);
}
}<file_sep><?php
namespace Brightzone\GremlinDriver\Tests\Stubs;
use Brightzone\GremlinDriver\Connection as BaseConnection;
class Connection extends BaseConnection
{
/**
* Allow stub to set socket with any data
*
* @param string $frame binary data to set up as stream.
*/
public function setSocket($frame)
{
$stream = fopen('php://memory', 'r+');
fwrite($stream, $frame);
rewind($stream);
$this->_socket = $stream;
}
/**
* Close connection to server
* This closes the current session on the server then closes the socket
*
* @return bool TRUE on success
*/
public function close()
{
if($this->_socket !== NULL)
{
fclose($this->_socket); //ignore error
$this->_socket = NULL;
$this->_sessionUuid = NULL;
return TRUE;
}
return TRUE;
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Serializers\Gson3;
use Brightzone\GremlinDriver\Connection;
/**
* Unit testing of Gremlin-php
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class GremlinServerGS3Test extends GremlinServerTest
{
/**
* Set the serializer up here
*
* @return void
*/
public static function setUpBeforeClass()
{
static::$serializer = new Gson3;
}
/**
* Test the vertex format for changes
* Different from GSON 1 because serializing server end adds data
*/
public function testVertexFormat()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.V(1)");
$vertex = [
0 => [
"id" => 1,
"label" => "vertex",
"properties" => [
"name" => [
0 => [
"id" => 0,
"value" => "marko",
"label" => "name",
],
],
"age" => [
0 => [
"id" => 2,
"value" => 29,
"label" => "age",
],
],
],
"type" => "vertex",
],
];
$this->ksortTree($vertex);
$this->ksortTree($result);
$this->assertEquals($vertex, $result, "vertex property wasn't as expected");
}
/**
* Test the edge format for changes
*/
public function testEdgeFormat()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.E(12)");
$edge = [
0 => [
"id" => 12,
"label" => "created",
"inVLabel" => "vertex",
"outVLabel" => "vertex",
"inV" => 3,
"outV" => 6,
"properties" => [
"weight" => [
"key" => "weight",
"value" => 0.2,
],
],
"type" => "edge",
],
];
$this->ksortTree($edge);
$this->ksortTree($result);
$this->assertEquals($edge, $result, "vertex property wasn't as expected");
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver;
use \Exception;
/**
* Gremlin-server PHP Driver client Exception class for internal exceptions
*
* @category DB
* @package GremlinDriver
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class InternalException extends Exception
{
/**
* Overriding construct
*
* @param string $message The error message to throw
* @param int $code The error code to throw
* @param Exception $previous The previous exception if there is one that triggered this error
*
* @return void
*/
public function __construct($message, $code = 0, Exception $previous = NULL)
{
$message = 'gremlin-php driver has thrown the following error : ' . $message;
parent::__construct($message, $code, $previous);
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver;
use JsonSerializable;
/**
* Class RequestMessage
* The frame object that we use to make requests to the server.
* This class allows us to specify different serializing for this class.
* It's a glorified map.
*
* @author <NAME> <<EMAIL>>
* @package Brightzone\GremlinDriver
*/
class RequestMessage implements JsonSerializable
{
/**
* @var array the information contained in the message
*/
private $data;
/**
* Overriding construct to populate data
*
* @param array $data the data contained in this message
*/
public function __construct($data)
{
$this->setData($data);
}
/**
* Getter for data
*
* @return array the data contained in the RequestMessage
*/
public function getData()
{
return $this->data;
}
/**
* Setter for data
*
* @return void
*/
public function setData($data)
{
$this->data = $data;
}
/**
* The json serialize method
* @return mixed
*/
public function jsonSerialize()
{
return $this->getData();
}
}<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Serializers\Gson3;
/**
* Unit testing of Gremlin-php
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class AuthGS3Test extends AuthTest
{
/**
* Set the serializer up here
*
* @return void
*/
public static function setUpBeforeClass()
{
static::$serializer = new Gson3;
}
}
<file_sep>#!/bin/bash
if [ "$TRAVIS_BRANCH" == "master" ] && [ "$TRAVIS_PHP_VERSION" == "5.6" ] && [ "$GRAPHSON_VERSION" == "3.0" ]; then
# run coveralls
php $TRAVIS_BUILD_DIR/vendor/bin/php-coveralls -v
# configure git
git config --global user.name "Travis CI"
git config --global user.email "<EMAIL>"
git config --global push.default simple
#clone doc repo
git clone -b master --depth 1 https://github.com/PommeVerte/PommeVerte.github.io.git $TRAVIS_BUILD_DIR/build/logs/PommeVerte.github.io
#generate docs
$TRAVIS_BUILD_DIR/vendor/bin/apidoc api --interactive=0 $TRAVIS_BUILD_DIR/src/ $TRAVIS_BUILD_DIR/build/logs/PommeVerte.github.io/gremlin-php/
[ -f $HOME/PommeVerte.github.io/gremlin-php/errors.txt ] && cat $HOME/PommeVerte.github.io/gremlin-php/errors.txt
fi
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Connection;
/**
* Unit testing of gremlin-php for transactional graph
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class RexsterTransactionTest extends RexsterTestCase
{
/**
* Testing transactions
*
*
* @return void
*/
public function testTransactions()
{
$db = new Connection([
'graph' => 'graphT',
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$this->assertNotEquals($result, FALSE, 'Script request throws an error in transaction mode');
$elementCount = $result[0];
$db->transactionStart();
$db->message->gremlin = 't.addV()';
$db->send();
$db->transactionStop(FALSE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount2 = $result[0];
$this->assertNotEquals($result, FALSE, 'Script request throws an error in transaction mode');
$this->AssertEquals($elementCount, $elementCount2, 'Transaction rollback didn\'t work');
$db->transactionStart();
$db->send('t.addV().property("name","stephen").next()');
$db->transactionStop(TRUE);
$elementCount2 = $db->send('t.V().count()');
$this->AssertEquals($elementCount + 1, $elementCount2[0], 'Transaction submition didn\'t work');
}
/**
* Testing transactions accross multiple script launches
*
* @return void
*/
public function testTransactionsMultiRun()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>-><PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$result = $db->send('t.V().count()');
$elementCount = $result[0];
$db->transactionStart();
$db->send('t.addV().property("name","michael").next()');
$db->send('t.addV().property("name","michael").next()');
$db->transactionStop(FALSE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount2 = $result[0];
$this->AssertEquals($elementCount, $elementCount2, 'Transaction rollback didn\'t work');
$db->transactionStart();
$db->send('t.addV().property("name","michael").next()');
$db->send('t.addV().property("name","michael").next()');
$db->transactionStop(TRUE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount2 = $result[0];
$this->AssertEquals($elementCount + 2, $elementCount2, 'Transaction submition didn\'t work');
}
/**
* Testing Transaction without graphObj
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*
* @return void
*/
public function testTransactionWithNoGraphObj()
{
$db = new Connection();
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$db->transactionStart();
}
/**
* Testing transactionStart() with an other running transaction
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*
* @return void
*/
public function testSeveralRunningTransactionStart()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$db->transactionStart();
$db->transactionStart();
}
/**
* Testing db close during transaction running transaction
*
* @return void
*/
public function testClosingDbOnRunningTransaction()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$db->transactionStart();
$db->close();
$this->assertTrue(TRUE); // should execute this without hitting any errors
}
/**
* Testing transactionStop() with no running transaction
*
* @expectedException \Brightzone\GremlinDriver\InternalException
*
* @return void
*/
public function testTransactionStopWithNoTransaction()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$db->transactionStop();
}
/**
* Testing transaction retry error on already open transaction
*
* @expectedException \Brightzone\GremlinDriver\InternalException
* @return void
* @throws \Exception
*/
public function testTransactionRetryAlreadyOpen()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$db->transactionStart();
$count = 0;
try
{
$db->transaction(function(&$c) {
$c++;
}, [&$count]);
}
catch(\Exception $e)
{
$this->assertEquals(0, $count, "the workload has been executed when it shouldn't have");
throw $e;
}
}
/**
* Testing transaction retry
*
* @expectedException \Brightzone\GremlinDriver\ServerException
* @return void
* @throws \Exception
*/
public function testTransactionRetry()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graphT',
'retryAttempts' => 5,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$count = 0;
try
{
$db->transaction(function(&$c) {
$c++;
throw new \Brightzone\GremlinDriver\ServerException('transaction test error', 597);
}, [&$count]);
}
catch(\Exception $e)
{
$this->assertEquals(5, $count, "the workload has been executed when it shouldn't have");
throw $e;
}
}
/**
* Test callable transaction
*
* @return void
*/
public function testCallableTransaction()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graphT',
'retryAttempts' => 5,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount = $result[0];
$count = 0;
try
{
$db->transaction(function(&$db, &$c) {
$db->message->gremlin = 't.addV()';
$db->send();
$c++;
throw new \Brightzone\GremlinDriver\ServerException('transaction callable test error', 597);
}, [&$db, &$count]);
}
catch(\Exception $e)
{
$this->assertEquals(5, $count, "the code didn't execute properly");
}
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount2 = $result[0];
$this->assertNotEquals($result, FALSE, 'Script request throws an error in transaction mode');
$this->AssertEquals($elementCount, $elementCount2, 'Transaction rollback didn\'t work');
$count = 0;
$db->transaction(function(&$db, &$c) {
$db->send('t.addV().property("name","michael").next()');
$c++;
if($c < 3)
{
throw new \Brightzone\GremlinDriver\ServerException('transaction callable test error', 597);
}
}, [&$db, &$count]);
$this->assertEquals(3, $count, "the code didn't execute the proper amount of times");
$elementCount2 = $db->send('t.V().count()');
$this->AssertEquals($elementCount + 1, $elementCount2[0], 'Transaction submition didn\'t work');
}
/**
* Testing combination of session and sessionless requests
*/
public function testSessionSessionlessTransactionIsOpenSingleClient()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$db->transactionStart();
$db->send('t.addV().property("name","stephen").next()');
$db->transactionStop(TRUE);
$isOpen = $db->send("graphT.tx().isOpen()", "session")[0];
$this->assertTrue(!$isOpen, "transaction should be closed");
$db->message->gremlin = 'graphT.traversal().V()';
$result = $db->send();
$isOpen = $db->send("graphT.tx().isOpen()", "session")[0];
$this->assertTrue(!$isOpen, "transaction should still be closed after sessionless request");
}
/**
* Testing combination of session and sessionless requests
*/
public function testSessionSessionlessTransactionIsOpenMultiClient()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db2 = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db2->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$db->transactionStart();
$db->send('t.addV().property("name","stephen").next()');
$db->transactionStop(TRUE);
$isOpen = $db->send("graphT.tx().isOpen()", "session")[0];
$this->assertTrue(!$isOpen, "transaction should be closed");
$db2->message->gremlin = 'graphT.traversal().V()';
$result = $db->send();
$isOpen = $db->send("graphT.tx().isOpen()", "session")[0];
$this->assertTrue(!$isOpen, "transaction should still be closed after sessionless request");
}
/**
* Testing combination of session and sessionless requests
*/
public function testSessionSessionlessCombinationConcurrentCommit()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$db2 = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db2->message->registerSerializer(static::$serializer, TRUE);
$message = $db2->open();
$this->assertNotEquals($message, FALSE);
$result = $db->send('t.V().count()');
$elementCount = $result[0];
$db->transactionStart();
$db->send('t.addV().property("name","michael").next()');
$db2->message->gremlin = 't.V()';
$db2->send();
$db->send('t.addV().property("name","michael").next()');
$db->transactionStop(TRUE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount2 = $result[0];
$this->AssertEquals($elementCount + 2, $elementCount2, 'Transaction submition didn\'t work');
}
/**
* Testing combination of session and sessionless requests
*/
public function testSessionSessionlessCombinationConcurrentRollback()
{
$db = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$db2 = new Connection([
'graph' => 'graphT',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db2->message->registerSerializer(static::$serializer, TRUE);
$message = $db2->open();
$this->assertNotEquals($message, FALSE);
$result = $db->send('t.V().count()');
$elementCount = $result[0];
$db->transactionStart();
$db->send('t.addV().property("name","michael").next()');
$db2->message->gremlin = 't.V()';
$db2->send();
$db->send('t.addV().property("name","michael").next()');
$db->transactionStop(FALSE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount2 = $result[0];
$this->AssertEquals($elementCount, $elementCount2, 'Transaction rollback didn\'t work');
}
/**
* Test transaction management
* This was introduced in GS 3.1.2. It should make session requests handle like sessionless
* Thus keeping bindings but managing transactions automatically
*/
public function testAutoTransactionManagement()
{
$db = new Connection([
'graph' => 'graphT',
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$this->assertNotEquals($result, FALSE, 'Script request throws an error in transaction mode');
$elementCount = $result[0];
$db->transactionStart();
$db->message->setArguments([
'manageTransaction' => TRUE,
]);
$db->message->gremlin = 't.addV()';
$db->send();
$db->transactionStop(FALSE);
$db->message->gremlin = 't.V().count()';
$result = $db->send();
$elementCount2 = $result[0];
$this->assertNotEquals($result, FALSE, 'Script request throws an error in transaction mode');
$this->AssertNotEquals($elementCount, $elementCount2, 'Transaction rollback worked when instead the transaction should have been committed prior to that.');
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Connection;
use Brightzone\GremlinDriver\Serializers\Gson3;
/**
* Unit testing of Gremlin-php
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class RexsterGS3Test extends RexsterTest
{
/**
* Set the serializer up here
*
* @return void
*/
public static function setUpBeforeClass()
{
static::$serializer = new Gson3;
}
/**
* Lets test returning a large set back from the database
*
* @return void
*/
public
function testTree()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'retryAttempts' => 5,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$expected = [
[
1 => [
'key' => [
'id' => 1,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 0, 'value' => 'marko', 'label' => 'name']],
'age' => [['id' => 2, 'value' => 29, 'label' => 'age']],
],
],
'value' => [
2 => [
'key' => [
'id' => 2,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 3, 'value' => 'vadas', 'label' => 'name']],
'age' => [['id' => 4, 'value' => 27, 'label' => 'age']],
],
],
'value' => [
3 => [
'key' => ['id' => 3, 'value' => 'vadas', 'label' => 'name'],
'value' => [],
],
],
],
3 => [
'key' => [
'id' => 3,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 5, 'value' => 'lop', 'label' => 'name']],
'lang' => [['id' => 6, 'value' => 'java', 'label' => 'lang']],
],
],
'value' => [
5 => [
'key' => ['id' => 5, 'value' => 'lop', 'label' => 'name'],
'value' => [],
],
],
],
4 => [
'key' => [
'id' => 4,
'label' => 'vertex',
'type' => 'vertex',
'properties' => [
'name' => [['id' => 7, 'value' => 'josh', 'label' => 'name']],
'age' => [['id' => 8, 'value' => 32, 'label' => 'age']],
],
],
'value' => [
7 => [
'key' => ['id' => 7, 'value' => 'josh', 'label' => 'name'],
'value' => [],
],
],
],
],
],
],
];
$result = $db->send('g.V(1).out().properties("name").tree()');
$this->ksortTree($result);
$this->ksortTree($expected);
$this->assertEquals($expected, $result, "the response is not formated as expected.");
$db->close();
}
private function ksortTree(&$array)
{
if(!is_array($array))
{
return FALSE;
}
ksort($array);
foreach($array as $k => $v)
{
$this->ksortTree($array[$k]);
}
return TRUE;
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Connection;
use Brightzone\GremlinDriver\Helper;
use Brightzone\GremlinDriver\Message;
use Brightzone\GremlinDriver\Workload;
/**
* Unit testing of Gremlin-php
* This actually runs tests against the server
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class GremlinServerTest extends RexsterTestCase
{
/**
* Sends a param, saves it to a node then retrieves it and compares it to the original
*
* @param mixed $param the parameter we would like to submit
*
* @return void
*/
private function sendParam($param)
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$message = $db->message;
$message->gremlin = "graph.addVertex('paramTest', B_PARAM_VALUE);";
$message->bindValue('B_PARAM_VALUE', $param);
$db->send();
$result = $db->send("g.V().has('paramTest').values('paramTest')");
$db->run("g.V().has('paramTest').sideEffect{it.get().remove()}.iterate()");
$this->assertTrue(!empty($result), "the result should contain a vertex");
$this->assertSame($param, $result[0], "the param retrieved was different from the one sent");
}
/**
* Test sending a mixed List param
*/
public function testListParam()
{
$this->sendParam(["string1", "string2", "12", 3]);
}
/**
* Test sending a mixed Map param
*/
public function testMapParam()
{
$this->sendParam(["key1" => "string1", "key2" => "string2", "1" => "12", 2 => 3]);
}
/**
* Test sending a mixed Map param containing other maps
*/
public function testMapofMapsParam()
{
$this->sendParam([
"key1" => "string1",
"key2" => "string2",
"1" => "12",
2 => 3,
"map" => [
"map" => [
"map" => [
"id" => "lala",
],
],
],
]);
}
/**
* Test sending a mixed Map param
*/
public function testListofMapsAndListParam()
{
$this->sendParam([
[
"map" => [
"map" => [
"id" => "first",
],
],
],
[
"map" => [
"map" => [
"id" => "second",
],
],
],
[1, 2, 3, 4],
[
"map" => [
"map" => [
"id" => "third",
],
],
],
]);
}
/**
* Test sending a mixed Map param
*/
public function testListofMixedParam()
{
$this->sendParam([
"string1",
"string2",
"12",
3,
["item1", "item2"],
[
"map" => [
"map" => [
"id" => "lala",
],
],
],
]);
}
/**
* Test the vertex format for changes
*/
public function testVertexPropertyFormat()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.V(1).properties('name')");
$vertexProperty = [
0 => [
"id" => 0,
"value" => "marko",
"label" => "name",
],
];
$this->ksortTree($vertexProperty);
$this->ksortTree($result);
$this->assertEquals($vertexProperty, $result, "vertex property wasn't as expected");
}
/**
* Test the vertex format for changes
*/
public function testVertexFormat()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $this-><PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.V(1)");
$vertex = [
0 => [
"id" => 1,
"label" => "vertex",
"properties" => [
"name" => [
0 => [
"id" => 0,
"value" => "marko",
],
],
"age" => [
0 => [
"id" => 2,
"value" => 29,
],
],
],
"type" => "vertex",
],
];
$this->ksortTree($vertex);
$this->ksortTree($result);
$this->assertEquals($vertex, $result, "vertex property wasn't as expected");
}
/**
* Test the edge format for changes
*/
public function testEdgeFormat()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $this-><PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.E(12)");
$edge = [
0 => [
"id" => 12,
"label" => "created",
"inVLabel" => "vertex",
"outVLabel" => "vertex",
"inV" => 3,
"outV" => 6,
"properties" => [
"weight" => 0.2,
],
"type" => "edge",
],
];
$this->ksortTree($edge);
$this->ksortTree($result);
$this->assertEquals($edge, $result, "vertex property wasn't as expected");
}
/**
* Test the property format for changes
*/
public function testPropertyFormat()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.E(12).properties('weight')");
$property = [
0 => [
"key" => "weight",
"value" => 0.2,
],
];
$this->ksortTree($property);
$this->ksortTree($result);
$this->assertEquals($property, $result, "vertex property wasn't as expected");
}
/**
* Test the valuemap() with empty param
*/
public function testValueMap()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.V(1).valueMap()");
$property = [
0 => [
"name" => ["marko"],
"age" => [29],
],
];
$this->ksortTree($property);
$this->ksortTree($result);
$this->assertEquals($property, $result, "Not the expected value map");
}
/**
* Test valueMap(true) which should return id and label
*/
public function testValueMapTrue()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
'username' => $this->username,
'password' => $<PASSWORD>,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("g.V(1).valueMap(true)");
$property = [
0 => [
"name" => ["marko"],
"age" => [29],
"id" => 1,
"label" => "vertex",
],
];
$this->ksortTree($property);
$this->ksortTree($result);
$this->assertEquals($property, $result, "Not the expected value map");
}
/**
* Protected ksort for tree that helps with testing.
*
* @param $array
*
* @return bool
*/
protected function ksortTree(&$array)
{
if(!is_array($array))
{
return FALSE;
}
ksort($array);
foreach($array as $k => $v)
{
$this->ksortTree($array[$k]);
}
return TRUE;
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Connection;
use Brightzone\GremlinDriver\Message;
use Brightzone\GremlinDriver\Exceptions;
use Brightzone\GremlinDriver\Helper;
/**
* Unit testing of Gremlin-php documentation examples
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
* @link https://github.com/tinkerpop/rexster/wiki
*/
class RexsterExamplesTest extends RexsterTestCase
{
/**
* Testing Basic feature example 1
*
* @return void
*/
public function testBasicFeatures1()
{
$db = new Connection([
'host' => 'localhost',
'graph' => 'graph',
]);
$db->message->registerSerializer(static::$serializer, TRUE);
//you can set $db->timeout = 0.5; if you wish
$db->open();
$result = $db->send('g.V(2)');
//do something with result
$db->close();
$this->assertTrue(TRUE); // should always get here
}
/**
* Testing Basic feature example 2 bis
*
* @return void
*/
public function testBasicfeatures2()
{
$db = new Connection([
'host' => 'localhost',
'graph' => 'graph',
'port' => 8184,
'username' => 'stephen',
'password' => '<PASSWORD>',
'ssl' => [
"ssl" => [
"verify_peer" => FALSE,
"verify_peer_name" => FALSE,
],
],
]);
$db->message->registerSerializer(static::$serializer, TRUE);
//you can set $db->timeout = 0.5; if you wish
$db->open();
$db->send('g.V(2)');
//do something with result
$db->close();
$this->assertTrue(TRUE); // should always get here
}
/**
* Testing Binding example 1
*
* @return void
*/
public function testBindings1()
{
$unsafeUserValue = 2; //This could be anything submitted via form.
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graph',
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$db->message->bindValue('CUSTO_BINDING', $unsafeUserValue); // protects from injections
$result1 = $db->send('g.V(CUSTO_BINDING)'); // The server compiles this script and adds it to cache
$this->assertNotEmpty($result1, "the result should be populated by vertex 2");
$db->message->bindValue('CUSTO_BINDING', 5);
$result2 = $db->send('g.V(CUSTO_BINDING)'); // The server already has this script so gets it from cache without compiling it, but runs it with 5 instead of $unsafeUserValue
$result3 = $db->send('g.V(5)'); // The script is different so the server compiles this script and adds it to cache
$this->assertEquals($result2, $result3, "both results should be equivalent");
//do something with result
$db->close();
}
/**
* Testing Sessions example 1
*
* @return void
*/
public function testSessions1()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$db->send('cal = 5+5', 'session'); // first query sets the `cal` variable
$result = $db->send('cal', 'session'); // result = [10]
//do something with result
$this->assertEquals(10, $result[0], "should equal 10"); // should always get here
$db->close();
}
/**
* Testing Transaction Example 1
*
* @return void
*/
public function testTransaction1()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graphT',
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("t.V().count()");
$db->transactionStart();
$db->send('graphT.addVertex("name","michael")');
$db->send('graphT.addVertex("name","john")');
$db->transactionStop(FALSE); //rollback changes. Set to TRUE to commit.
$result2 = $db->send("t.V().count()");
$this->assertEquals($result, $result2, "Vertices were added when they should've been rolled back");
$db->close();
}
/**
* Testing Transaction example 2
*
* @return void
*/
public function testTransaction2()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8182,
'graph' => 'graphT',
'emptySet' => TRUE,
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$db->open();
$result = $db->send("t.V().count()");
$db->transaction(function($db) {
$db->send('t.addV().property("name","crazy")');
$db->send('t.addV().property("name","crazy")');
}, [$db]);
$result2 = $db->send("t.V().count()");
$db->run("t.V().has('name', 'crazy').drop()");
$this->assertEquals($result[0], $result2[0] - 2, "vertices were not properly added");
$db->close();
}
/**
* Testing Message objects example 1
*
* @return void
*/
public function testMessage1()
{
$message = new Message;
$message->gremlin = 'custom.V()'; // note that custom refers to the graph traversal set on the server as g (see alias bellow)
$message->op = 'eval'; // operation we want to run
$message->processor = ''; // the opProcessor the server should use
$message->setArguments([
'language' => 'gremlin-groovy',
'aliases' => ['custom' => 'g'],
// ... etc
]);
$message->registerSerializer(static::$serializer);
$db = new Connection();
$db->open();
$db->send($message);
//do something with result
$db->close();
$this->assertTrue(TRUE); // should always get here
}
/**
* Testing Serializer example 1
*
* @return void
*/
public function testSerializer1()
{
$db = new Connection;
$s = static::$serializer;
$db->message->registerSerializer($s, TRUE);
$serializer = $db->message->getSerializer(); // returns an instance of the default serializer
$this->assertEquals($s->getName(), $serializer->getName(), "incorrect serializer name");
$this->assertEquals("application/json", $serializer->getMimeType(), "incorrect mimtype found. should be application/json");
$db->message->registerSerializer('\Brightzone\GremlinDriver\Tests\Stubs\TestSerializer', TRUE);
$this->assertEquals("Brightzone\GremlinDriver\Tests\Stubs\TestSerializer", get_class($db->message->getSerializer()), "incorrect serializer found");
$this->assertEquals(get_class(static::$serializer), get_class($db->message->getSerializer('application/json')), "incorrect serializer found");
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver;
/**
* Gremlin-server PHP Driver client Workload class
*
* Workload class will store some executable code and run it against the database.
* It also allows for fail-retry strategies in the event of concurrency errors
*
* ~~~
* $workload = new Workload(function(&$db, $msg, $processor, $op, $args){
* return $db->send($msg, $processor, $op, $args);
* },
* [&$this, $msg, $processor, $op, $args]
* );
*
* $response = $workload->linearRetry($this->retryAttempts);
* ~~~
*
* @category DB
* @package GremlinDriver
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
* @link https://github.com/tinkerpop/rexster/wiki
*/
class Workload
{
/**
* @var callable the callback code to be executed
* Bellow is a common example:
* ~~~
* function(&db, $msg, $processor, $op, $processor, $args){}
* ~~~
* It must return something other than void. (the desired result)
*/
protected $callback;
/**
* @var array paramteres required for the workload
*
* Ideas of params would be :
* - Connection &db connection object to operate on
* - Message $msg possible message to operate on (optional defaults to NULL)
* - String $processor processor to use (optional defaults to "")
* - String $op operation to perform (optional defaults to "eval")
* - array $args arguments for the message. (optional defaults to [])
*/
protected $params;
/**
* Override Constructor
*
* @param callable $callback the portion of code to execute within the scope of this workload
* @param array $params the paramters to pass to the callback.
*
* @return void
*/
public function __construct(callable $callback, $params)
{
$this->callback = $callback;
$this->params = $params;
}
/**
* Linear retry strategy.
*
* @param int $attempts the number of times to retry
*
* @return mixed the result of the executable code
* @throws ServerException
*/
public function linearRetry($attempts)
{
$result = NULL;
while($attempts >= 1)
{
try
{
$result = call_user_func_array($this->callback, $this->params);
break;
}
catch(\Exception $e)
{
if($e instanceof ServerException && $e->getCode() == 597 && $attempts > 1)
{
usleep(200);
$attempts--;
}
else
{
throw $e;
}
}
}
return $result;
}
}
<file_sep><?php
namespace Brightzone\GremlinDriver\Tests;
use Brightzone\GremlinDriver\Connection;
/**
* Unit testing of Gremlin-php authentication
*
* @category DB
* @package Tests
* @author <NAME> <<EMAIL>>
* @license http://www.apache.org/licenses/LICENSE-2.0 apache2
*/
class AuthTest extends RexsterTestCase
{
/**
* Testing a simple authentication
* @return void
*/
public function testAuthenticationSimple()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8184,
'graph' => 'graph',
'username' => 'stephen',
'password' => '<PASSWORD>',
'ssl' => [
"ssl" => [
"verify_peer" => FALSE,
"verify_peer_name" => FALSE,
],
],
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$result = $db->send('5+5');
$this->assertEquals($result[0], 10, 'Script response message is not the right type. (Maybe it\'s an error)'); //check it's a session script reply
}
/**
* Test a simple auth with a more complex query
* @return void
*/
public function testAuthenticationComplex()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8184,
'graph' => 'graph',
'username' => 'stephen',
'password' => '<PASSWORD>',
'ssl' => [
"ssl" => [
"verify_peer" => FALSE,
"verify_peer_name" => FALSE,
],
],
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$result = $db->send('g.V().emit().repeat(__.both()).times(5)');
$this->assertEquals(count($result), 714, 'Did not find the correct amounts of vertices'); //check it's a session script reply
}
/**
* testing an in session authentication
* @return void
*/
public function testAuthenticationSession()
{
$db = new Connection([
'host' => 'localhost',
'port' => 8184,
'graph' => 'graph',
'username' => 'stephen',
'password' => '<PASSWORD>',
'ssl' => [
"ssl" => [
"verify_peer" => FALSE,
"verify_peer_name" => FALSE,
],
],
]);
$db->message->registerSerializer(static::$serializer, TRUE);
$message = $db->open();
$this->assertNotEquals($message, FALSE, 'Failed to connect to db');
$result = $db->send('cal = 5+5', 'session', 'eval');
$this->assertEquals($result[0], 10, 'Script response message is not the right type. (Maybe it\'s an error)'); //check it's a session script reply
$result = $db->send('cal', 'session', 'eval');
$this->assertEquals($result[0], 10, 'Script response message is not the right type. (Maybe it\'s an error)'); //check it's a session script reply
//check disconnection
$db->close();
$this->assertFALSE($db->isConnected(), 'Despite not throwing errors, Socket connection is not established');
$this->assertFALSE($db->inTransaction(), 'Despite closing, transaction not closed');
}
}
|
a9fd3f7ea17e939924a23e757d13b9759f48462d
|
[
"PHP",
"Shell"
] | 23 |
PHP
|
amore012/gremlin-php
|
507eb6d1c6719c65f1ecb13b9f5d1032edd3ff8b
|
648864014805a5645251f0cb02df364b10524b7a
|
refs/heads/main
|
<repo_name>pasqualebasile/java1<file_sep>/src/main/java/helloword/HelloWorld.java
package helloword;
public class HelloWorld {
private static String HELLOWORLD="<NAME>";
public static void main(String[] args) {
String SALVEMONDO="<NAME>";
/*
Questo è un commento
*/
// Questo è un commento
System.out.println(HELLOWORLD);
System.out.println(SALVEMONDO);
// Variabili
Integer x ;
x = 10;
System.out.println(HELLOWORLD + x.toString());
}
}
|
25dc8cee1430bf572b409cf38adf65da3a18bcab
|
[
"Java"
] | 1 |
Java
|
pasqualebasile/java1
|
381ae732b84b846b5f8fad75862fe70009995f58
|
09edd7881e9f7380ab9754f86014b26f8f150c9d
|
refs/heads/master
|
<repo_name>astephensen/Tock<file_sep>/Tock/Controllers/MainViewController.swift
//
// MainViewController.swift
// Tock
//
// Created by <NAME> on 11/05/2015.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Cocoa
import WebKit
let TICK_MAIN_URL = "https://chrome-extension.tickspot.com/extension"
class MainViewController: NSViewController {
@IBOutlet var rightClickMenu: NSMenu?
@IBOutlet var webView: WebView?
override func viewDidLoad() {
super.viewDidLoad()
// Load the tick URL.
let request = NSURLRequest(URL: NSURL(string: TICK_MAIN_URL)!)
webView?.mainFrame.loadRequest(request)
}
@IBAction func refreshClicked(sender: AnyObject?) {
webView?.reload(nil)
}
@IBAction func quitSelected(sender: AnyObject?) {
if let app = NSApp as? NSApplication {
app.terminate(nil)
}
}
}
<file_sep>/Tock/Extensions/NSStatusBarButton+Tools.swift
//
// NSStatusBarButton+Tools.swift
// Tock
//
// Created by <NAME> on 11/05/2015.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Cocoa
extension NSStatusBarButton {
public override func rightMouseDown(theEvent: NSEvent) {
if let menubarController = target as? MenubarController {
menubarController.rightMouseClicked()
}
}
}<file_sep>/Tock/Controllers/MenubarController.swift
//
// MenubarController.swift
// Tock
//
// Created by <NAME> on 11/05/2015.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Cocoa
class MenubarController: NSObject, NSPopoverDelegate {
var statusItem: NSStatusItem
var statusItemButton: NSStatusBarButton
var viewController: NSViewController?
var popover: NSPopover?
var menu: NSMenu?
let statusItemViewWidth = 22.0
override init() {
// Create the status item and assign local variables.
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(CGFloat(statusItemViewWidth))
statusItemButton = statusItem.button!
super.init()
// Setup status item button.
statusItemButton.image = NSImage(named: "menubar_icon")
statusItemButton.alternateImage = NSImage(named: "menubar_icon_selected")
statusItemButton.target = self
statusItemButton.action = "statusButtonClicked:"
}
func statusButtonClicked(sender: AnyObject) {
if popover?.shown == true {
popover?.performClose(sender)
} else {
showViewController()
}
}
func showViewController() {
// Create the popover and show it from the status item button.
popover = NSPopover()
popover?.delegate = self
// popover?.behavior = .Transient
popover?.contentViewController = viewController
popover?.appearance = NSAppearance(named: NSAppearanceNameAqua)
popover?.showRelativeToRect(statusItemButton.frame, ofView: statusItemButton.superview!, preferredEdge: NSMaxYEdge)
popover?.contentSize = NSSize(width: 590.0, height: 500.0)
// We need to make the application active so the popover is in control.
NSApplication.sharedApplication().activateIgnoringOtherApps(true)
}
func rightMouseClicked() {
statusItem.popUpStatusItemMenu(menu!)
}
// MARK: NSPopoverDelegate
func popoverDidClose(notification: NSNotification) {
popover = nil
}
}
<file_sep>/README.md
# Tock

Tock is a simple menubar app for Tick.
<file_sep>/Tock/AppDelegate.swift
//
// AppDelegate.swift
// Tock
//
// Created by <NAME> on 11/05/2015.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var menubarController: MenubarController?
var mainViewController: MainViewController?
@IBOutlet var menu: NSMenu?
func applicationDidFinishLaunching(aNotification: NSNotification) {
menubarController = MenubarController()
// Create the main view controller.
mainViewController = NSStoryboard(name: "Main", bundle: nil)?.instantiateControllerWithIdentifier("MainViewController")! as? MainViewController
menubarController?.viewController = mainViewController
// Assign the menu.
menubarController?.menu = mainViewController?.rightClickMenu
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
|
531845ed7d398db91db9644a0b8479273713aa69
|
[
"Swift",
"Markdown"
] | 5 |
Swift
|
astephensen/Tock
|
f52b588c7d528fe992cb8027538bede16d5804e5
|
101a427c0549e519a52fabc55e0cf0f55cce24ea
|
refs/heads/main
|
<repo_name>Rakibul2tr/create-slider<file_sep>/app.js
const images = [
'img/bick-1.jpg',
'img/bick-2.jpg',
'img/bick-1.jpg',
'img/bick-2.jpg',
'img/bick-1.jpg',
'img/bick-2.jpg',
]
let imgindex= 0;
const imagesElement = document.getElementById('img');
setInterval( function(){
if(imgindex>=images.length){
imgindex = 0;
}
let imgurl = images[imgindex];
imagesElement.setAttribute('src',imgurl);
imgindex++
} ,2000)
|
c5f11814bbe49d52e7955914d3c1ca5181e1e245
|
[
"JavaScript"
] | 1 |
JavaScript
|
Rakibul2tr/create-slider
|
036e56f950bbd6234b72dacf649e59bd107b06e3
|
87fe7ab4aea7d4a263edd37e5544f6ce8493d600
|
refs/heads/master
|
<repo_name>sebpouteau/2048<file_sep>/README.md
# PROJET 2048
(Licence 2 Informatique - Année 2015)
Réalisé par:
- <NAME>,
- <NAME>,
- <NAME>,
- <NAME>.
## LE JEU
Aller dans Projet-Jeu/
/!\ WARNING /!\
Vérifiez au préalable que vous avez bien les bibliothèques ncurses et SDL d'installées.
Ainsi que deux bibliothèques tierces (SDL_image et SDL_ttf).
Compilation du Projet 2048 grace à la commande make :
make
Pour vérifier que toutes les fonctions fonctionnent, lancer le test avec :
make check
Les librairies créées sont placées dans lib/
Les exécutables sont placés dans bin/ (jeu_ncurses ou jeu_sdl)
## L'IA
Compilation des IA grace à la commande make :
make
Les librairies créées sont placées dans lib/
Les exécutables sont dans bin/ (IA-repetition-fast/low "nombre de repetition" && IA-graphique-fast/low)
## DOCUMENTATION
Commande pour obtenir la Documentation:
make doc
La documentation en html:
- Aller dans le dossier html/
- Ouvrir le fichier index.html
La documentation en pdf:
- Aller dans le dossier latex/
- 'make'
- Ouvrir le fichier refman.pdf
<file_sep>/Projet-Jeu/src/ncurses/gridNcurses.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <grid.h>
#include <ncurses.h>
#include <curses.h>
#include <gridNcurses.h>
#include <time.h>
#define PATH_HIGHSCORE "../src/ncurses/highscore_ncurses.txt"
#define MARGIN_LEFT 3
#define MARGIN_TOP 3
#define HEIGHT_CASE 4
#define WIDTH_CASE 8
#define NUMBER_COLOR 8
#define BELOW_CASE 8
#define RIGHT_CASE 4
#define X_DISPLAY_GAME_OVER 9
#define Y_DISPLAY_GAME_OVER 11*GRID_SIDE+1
#define X_DISPLAY_REPLAY 11
#define Y_DISPLAY_REPLAY 9*GRID_SIDE+1
#define X_DISPLAY_2048 1
#define Y_DISPLAY_2048 4*GRID_SIDE-1
#define X_DISPLAY_SCORE 5
#define Y_DISPLAY_SCORE 9*GRID_SIDE+1
#define X_DISPLAY_HIGHSCORE 6
#define Y_DISPLAY_HIGHSCORE 9*GRID_SIDE+1
#define X_RETRY_QUIT_GAME 4*GRID_SIDE+5
#define Y_RETRY_QUIT_GAME 3
#define KEY_Y 110
#define KEY_Q 113
#define KEY_N 121
#define KEY_R 114
void display_game_over(bool *continue_game, int *valid_answer){
keypad(stdscr, TRUE);
int ch = 0;
mvprintw(X_DISPLAY_GAME_OVER, Y_DISPLAY_GAME_OVER , "GAME OVER");
mvprintw(X_DISPLAY_REPLAY, Y_DISPLAY_REPLAY, "Voulez-vous rejouer? y or n ? ");
refresh();
cbreak();
ch = getch();
if(ch == KEY_Y){
*continue_game = false; // Arrete le programme et sort de la boucle
*valid_answer = 1;
}
if(ch == KEY_N)
*valid_answer = 1; // Relance le programme du debut
endwin();
}
void display_grid(grid g){
initscr();
clear();
keypad(stdscr, TRUE);
// Mise en forme de la grille
int x = MARGIN_TOP;
int y = MARGIN_LEFT-1;
for(int i = 0; i <= GRID_SIDE; i++){
// tracer des lignes horizontales
mvhline(x, MARGIN_LEFT, ACS_HLINE, 8*GRID_SIDE-1);
x += HEIGHT_CASE;
}
for(int i = 0; i <= GRID_SIDE; i++){
//tracer des lignes verticales
mvvline(MARGIN_TOP+1, y, ACS_VLINE, 4*GRID_SIDE-1);
y += WIDTH_CASE;
}
start_color();
// Definition des couleurs (rouge, vert, jaune, bleu fonce, violet, bleu turquoise, blanc)
for(int i = 1; i < NUMBER_COLOR; i++){
init_pair(i, i, 0);
}
// Mise des valeurs dans la grille
x = 5;
int t[] = {COLOR_RED, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_MAGENTA, COLOR_WHITE};
for(int i = 0; i < GRID_SIDE; i++){
y = 5;
for(int j = 0; j < GRID_SIDE; j++){
if(get_tile(g, j, i) != 0){
// coloration active
attron(COLOR_PAIR(t[(get_tile(g, j, i) - 1) % (NUMBER_COLOR-1)]));
// Recuperation d'un nombre et de la coloration
char buff[5];
sprintf(buff, "%d", (unsigned int)pow(2, get_tile(g, j, i)));
mvprintw(x, y, buff);
// coloration desactive
attroff(COLOR_PAIR(1));
}
y += BELOW_CASE;
}
x += RIGHT_CASE;
}
mvprintw(X_DISPLAY_2048, Y_DISPLAY_2048, "2048");
mvprintw(X_DISPLAY_SCORE, Y_DISPLAY_SCORE, "Score: %lu ", grid_score(g));
unsigned long int read_highscore();
if(grid_score(g) > read_highscore()){
write_highscore(grid_score(g));
}
mvprintw(X_DISPLAY_HIGHSCORE, Y_DISPLAY_HIGHSCORE, "High Score: %lu ", read_highscore());
mvprintw(X_RETRY_QUIT_GAME, Y_RETRY_QUIT_GAME , "Recommencer Partie / Quitter Partie (r / q)");
refresh();
}
unsigned long int read_highscore(){
unsigned long int score[1];
FILE *highscore = NULL;
highscore = fopen(PATH_HIGHSCORE,"r");
if(highscore == NULL)
return 0;
else{
fscanf(highscore, "%lu", &score[0]);
fclose(highscore);
}
return score[0];
}
void write_highscore(unsigned long int score){
FILE *highscore = NULL;
highscore = fopen(PATH_HIGHSCORE,"w");
fprintf(highscore, "%lu", score);
fclose(highscore);
}
<file_sep>/Projet-Jeu/src/strategy/main-graphique-fast.c
#include <ncurses.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <grid.h>
#include <strategy.h>
#include <math.h>
#include <gridNcurses.h>
/**
* \file main-graphique-fast.c
* \brief fait jouer en graphique l'IA Rapide
*/
/**
* \brief Strategie utilisé
* \return stretegy
*/
strategy A2_emery_gouraud_kirov_pouteau_fast();
int main(int argc, char *argv[]){
keypad(stdscr, TRUE);
bool continuer = true;
srand(time(NULL));
strategy str = A2_emery_gouraud_kirov_pouteau_fast();
while(continuer){
grid g = new_grid();
add_tile(g);
add_tile(g);
int ch = 0;
display_grid(g);
int reponse_valide = 0;
while(!game_over(g) && reponse_valide == 0){
dir direction;
ch=getch();
switch(ch){
case KEY_UP:
direction = str->play_move(str,g);
if ( can_move(g,direction))
play(g,direction);
break;
case 113: // "q" pour quitter
continuer = false;
reponse_valide = 1;
break;
case 114: // "r" pour rejouer
reponse_valide = 1;
break;
}
display_grid(g);
}
delete_grid(g);
while(reponse_valide == 0 && continuer == true)
display_game_over(&continuer, &reponse_valide);
endwin();
}
str->free_strategy(str);
return EXIT_SUCCESS;
}
<file_sep>/Projet-Jeu/src/ncurses/Makefile
CC = gcc
CFLAGS = -std=c99 -g -Wall -I../../include
LDLIBS = -lgridNcurses -lncurses -lgrid -lgcov -lm -L ../../lib/
CPPFLAGS=
PATH_LIB=../../lib
PATH_BIN=../../bin
all:$(PATH_BIN)/jeu_ncurses
$(PATH_BIN)/jeu_ncurses: main-jeu.o $(PATH_LIB)/*
$(CC) -o $(PATH_BIN)/jeu_ncurses main-jeu.o $(LDLIBS)
install: $(PATH_LIB)/libgridNcurses.a
$(PATH_LIB)/libgridNcurses.a: gridNcurses.o
ar -cr $(PATH_LIB)/libgridNcurses.a gridNcurses.o
include dep
.PHONY: clean
clean:
rm -f dep *.o *~ jeu *.g*
dep:
$(CC) $(CPPFLAGS) -MM *.c >dep
<file_sep>/Projet-Jeu/src/grid/Makefile
CC = gcc
CFLAGS = -std=c99 -g -ftest-coverage -fprofile-arcs -Wall -I../../include
LDLIBS = -lm -lgcov -L ../../lib/
CPPFLAGS=
PATH_INCLUDE=../../include
PATH_LIB=../../lib
PATH_BIN=../../bin
all: $(PATH_LIB)/libgrid.a
install: $(PATH_LIB)/libgrid.a
$(PATH_LIB)/libgrid.a: grid.o
ar -cr $(PATH_LIB)/libgrid.a grid.o
include dep
.PHONY: clean
clean:
rm -f dep *.o *~ *.g*
dep:
$(CC) $(CPPFLAGS) -MM *.c >dep
<file_sep>/Projet-Jeu/include/gridSDL.h
#ifndef _GRID_SDL_H_
#define _GRID_SDL_H_
/**
* \file gridSDL.h
* \brief interface de notre affichage SDL
**/
/**
* \brief Jeu en SDL
* \return
*/
void game_sdl();
#endif
<file_sep>/Projet-Jeu/include/gridNcurses.h
#ifndef _GRIDNCURSES_H_
#define _GRIDNCURSES_H_
/**
* \brief affiche la grille
* \param g grille
* \return
*/
extern void display_grid(grid g);
/**
* \brief affiche le game_over
* \param *continue_game,*valid_answer pointeur sur un bool
* \return
*/
extern void display_game_over(bool *continue_game, int *valid_answer);
/**
* \brief recupere le highscore
* \return unsigned long int
*/
extern unsigned long int read_highscore();
/**
* \brief ecrit le highscore
* \param score le score a ecrire
* \return
*/
extern void write_highscore(unsigned long int score);
#endif
<file_sep>/Projet-Jeu/src/ncurses/main-jeu.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <grid.h>
#include <ncurses.h>
#include <curses.h>
#include <gridNcurses.h>
#include <time.h>
/**
* \file main-jeu.c
* \brief fichier permetant le jeu en ncurses
**/
#define KEY_Y 110
#define KEY_Q 113
#define KEY_N 121
#define KEY_R 114
int main(int argc, char *argv[]){
keypad(stdscr, TRUE);
bool continue_game = true;
srand(time(NULL));
while(continue_game){
grid g = new_grid();
add_tile(g);
add_tile(g);
int ch = 0;
display_grid(g);
int valid_answer = 0;
while(!game_over(g) && valid_answer == 0){
ch=getch();
switch(ch){
case KEY_UP:
if (can_move(g, UP))
play(g, UP);
break;
case KEY_DOWN:
if (can_move(g, DOWN))
play(g, DOWN);
break;
case KEY_RIGHT:
if (can_move(g, RIGHT))
play(g, RIGHT);
break;
case KEY_LEFT:
if (can_move(g, LEFT))
play(g, LEFT);
break;
case KEY_Q: // "q" pour quitter
continue_game = false;
valid_answer = 1;
break;
case KEY_R: // "r" pour rejouer
valid_answer = 1;
break;
}
display_grid(g);
}
while(valid_answer == 0 && continue_game == true)
display_game_over(&continue_game, &valid_answer);
delete_grid(g);
endwin();
}
return EXIT_SUCCESS;
}
<file_sep>/Projet-Jeu/src/grid/grid.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <grid.h>
/**
* \file grid.c
* \brief Implementation de grid.h
* \author <NAME>, \n
* <NAME>, \n
* <NAME>, \n
* <NAME>.
* \date Licence 2 d'informatique - Mars 2015
**/
/**
* \brief Choix d'implementaion de la structure:
* - tableau 2D de tile
* - score de la grille
**/
struct grid_s{
tile **grid;
unsigned long int score;
};
// Declaration des fonctions static
static void move(grid g, int x, int y, int addx, int addy);
static void fusion(grid g, int x1, int y1, int x2, int y2);
static bool possible(grid g, int x, int y, int addx, int addy);
static void set_grid_score(grid g, unsigned long int add_score);
/* ==========================================
== IMPLEMENTATION DE L'INTERFACE GRID.H ==
========================================== */
grid new_grid(){
grid g = malloc(sizeof(struct grid_s));
assert(g != NULL);
g->grid = malloc(sizeof(tile*) * GRID_SIDE);
assert(g->grid != NULL);
// Initialisation de chaque case du tableau a 0
for(int i = 0; i < GRID_SIDE; i++){
g->grid[i] = malloc(sizeof(tile) * GRID_SIDE);
assert(g->grid[i] != NULL);
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, 0);
}
g->score = 0;
return g;
}
void delete_grid(grid g){
assert(g != NULL && g->grid != NULL);
// Destruction du tableau grid
for(int i = 0; i < GRID_SIDE; i++){
assert(g->grid[i] != NULL);
free(g->grid[i]);
}
free(g->grid);
// Destruction de la structure grid
free(g);
}
void copy_grid(grid src, grid dst){
assert(src != NULL && dst != NULL);
// Copie du tableau grid
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(dst, i, j, get_tile(src, i, j));
dst->score = src->score;
}
unsigned long int grid_score(grid g){
assert(g != NULL);
return g->score;
}
tile get_tile(grid g, int x, int y){
assert(g != NULL && g->grid != NULL);
assert(0 <= x && x < GRID_SIDE && 0 <= y && y < GRID_SIDE);
return g->grid[x][y];
}
void set_tile(grid g, int x, int y, tile t){
assert(g != NULL && g->grid != NULL);
assert(0 <= x && x < GRID_SIDE && 0 <= y && y < GRID_SIDE);
g->grid[x][y] = t;
}
bool game_over(grid g){
assert(g != NULL);
return (can_move(g, UP) == false && can_move(g, LEFT) == false && can_move(g, RIGHT) == false && can_move(g, DOWN) == false);
}
bool can_move(grid g, dir d){
assert(g != NULL);
switch(d){
case UP:
return possible(g, 0, 0, 0, 1);
case DOWN:
return possible(g, 0, GRID_SIDE-1, 0, -1);
case LEFT:
return possible(g, 0, 0, 1, 0);
case RIGHT:
return possible(g, GRID_SIDE-1, 0, -1, 0);
default:
return false;
}
}
void do_move(grid g, dir d){
assert(g != NULL);
switch(d){
case UP:
move(g, 0, 0, 0, 1);
break;
case DOWN:
move(g, 0, GRID_SIDE-1, 0, -1);
break;
case LEFT:
move(g, 0, 0, 1, 0);
break;
case RIGHT:
move(g, GRID_SIDE-1, 0, -1, 0);
break;
default:
break;
}
}
void add_tile(grid g){
assert(g != NULL);
int cpt_case_empty = 0;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
if(get_tile(g, i, j) == 0 )
cpt_case_empty++;
int position_random = rand() % cpt_case_empty;
int nbr_tile = rand() % 10;
cpt_case_empty = 0;
for(int i = 0; i < GRID_SIDE; i++){
for(int j = 0; j < GRID_SIDE; j++){
if(get_tile(g, i, j) == 0){
if(cpt_case_empty == position_random){
if(nbr_tile == 9)
set_tile(g, i, j, 2);
else
set_tile(g, i, j, 1);
}
cpt_case_empty++;
}
}
}
}
void play(grid g, dir d){
assert(g != NULL);
do_move(g, d);
add_tile(g);
}
/* =========================================
== IMPLEMENTATION DES FONCTIONS STATIC ==
========================================= */
/**
* \brief Fusionne deux cases dans toute la grille et met la deuxieme case a 0
* \param g grid
* \param i1, j1 coordonnee de la premiere case
* \param i2, j2 coordonnee de la deuxieme case
**/
static void fusion(grid g, int x1, int y1, int x2, int y2){
assert(g != NULL);
if(get_tile(g, x1, y1) == 0){
set_tile(g, x1, y1, get_tile(g, x2, y2));
}
else{
set_tile(g, x1, y1, get_tile(g, x1, y1) + 1);
}
set_tile(g, x2, y2, 0);
}
/**
* \brief Permet d'incrementer deux variables ayant des incrementations differentes.
* \param i1, i2 les variables a incrementer
* \param incrementationI1 incrementation du premier parametre
* \param incrementationI2 incrementation du deuxieme parametre
**/
static void incrementation(int *i1, int *i2, int incrementationI1, int incrementationI2){
*i1 += incrementationI1;
*i2 += incrementationI2;
}
/**
* \brief Deplace l'ensemble de la grille dans la direction voulue (en fonction des parametres)
* \param g grid visee
* \param x indice de l'ordonnee de depart
* \param y indice de l'abscisse de depart
* \param addx variable d'incrementation de l'ordonnee pour parcourir la grille
* \param addy variable d'incrementation de l'abscisse pour parcourir la grille
* \pre les directions prerequis : UP -> (grid, 0, 0, 0, 1)
* DOWN -> (grid, 0, GRID_SIDE - 1, 0, -1)
* LEFT -> (grid, 0, 0, 1, 0)
* RIGHT -> (grid, GRID_SIDE - 1, 0, -1, 0)
**/
static void move(grid g, int x, int y, int addx, int addy){
assert(g != NULL);
// Traite toutes les lignes ou toutes les colonnes via x et y
for(int cpt = 0; cpt < GRID_SIDE; cpt++){
// Case actuelle
int tmpx = x;
int tmpy = y;
// Case suivante dans le sens defini (devient case compteur)
int cptx = x + addx;
int cpty = y + addy;
// Traite les lignes/colonnes en les parcourant avec cpti et cptj
while(cptx < GRID_SIDE && cpty < GRID_SIDE && 0 <= cptx && 0 <= cpty){
if((tmpx == cptx && tmpy == cpty) || get_tile(g, cptx, cpty) == 0)
// On deplace la case compteur sur le case d'apres
incrementation(&cptx, &cpty, addx, addy);
else if(get_tile(g, tmpx, tmpy) == 0)
// On fusionne la case actuelle avec la case compteur (la case actuelle recupere la valeur de la case compteur)
fusion(g, tmpx, tmpy, cptx, cpty);
else if(get_tile(g, cptx, cpty) == get_tile(g, tmpx, tmpy)){
// On fusionne la case actuelle avec la case compteur
fusion(g, tmpx, tmpy, cptx, cpty);
set_grid_score(g, get_tile(g, tmpx, tmpy));
// On deplace la case actuelle et la case compteur dans le sens defini
incrementation(&tmpx, &tmpy, addx, addy);
incrementation(&cptx, &cpty, addx, addy);
}
// On change la case actuelle sur la même ligne/colonne suivant le sens defini
else
incrementation(&tmpx, &tmpy, addx, addy);
}
// On change de ligne ou de colonne suivant le sens defini
if(addx == -1 || addx == 1)
y++;
else
x++;
}
}
/**
* \brief Teste sur l'ensemble de la grille si le deplacement dans la direction voulue est faisable (en fonction des parametres)
* \param g grid visee
* \param x indice de l'ordonnee de depart
* \param y indice de l'abscisse de depart
* \param addx variable d'incrementation de l'ordonnee pour parcourir la grille
* \param addy variable d'incrementation de l'abscisse pour parcourir la grille
* \ret true si possible, false sinon
* \pre les directions prerequis : UP -> (grid, 0, 0, 0, 1)
* DOWN -> (grid, 0, GRID_SIDE - 1, 0, -1)
* LEFT -> (grid, 0, 0, 1, 0)
* RIGHT -> (grid, GRID_SIDE - 1, 0, -1, 0)
**/
static bool possible(grid g, int x,int y, int addx, int addy){
assert(g != NULL);
int tmpx = x;
int tmpy = y;
for(int cpt = 0; cpt < GRID_SIDE; cpt++){
while(x < GRID_SIDE - addx && x >= 0 - addx && y < GRID_SIDE - addy && y >= 0 - addy){
// Si deux cases collees sont indentiques alors return true
if((get_tile(g, x, y) == get_tile(g, x + addx, y + addy) && get_tile(g, x, y) != 0))
return true;
// Si une case vide est suivie d'une case non vide alors return true
else if(get_tile(g, x, y) == 0 && get_tile(g, x + addx, y + addy) != 0)
return true;
incrementation(&x, &y, addx, addy);
}
// Reinitialiser i ou j et incrementer l'autre indice pour changer de ligne ou de colonne selon la direction
if(addx == -1 || addx == 1)
incrementation(&y, &x, 1, tmpx - x);
else
incrementation(&x, &y, 1, tmpy - y);
}
return false;
}
/**
* \brief Ajoute un score au score de la grid
* \param g grid
* \param add_score score a ajouter
**/
static void set_grid_score(grid g, unsigned long int add_score){
assert(g != NULL);
g->score += pow(2, add_score);
}
<file_sep>/Projet-Jeu/src/sdl/main-sdl.c
#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include <time.h>
#include <gridSDL.h>
/**
* \file main-sdl.c
* \brief Jeu en interface graphique SDL
*/
int main(int argc, char *argv[]){
srand(time(NULL));
SDL_Init(SDL_INIT_VIDEO);
TTF_Init();
game_sdl();
TTF_Quit();
SDL_Quit();
return EXIT_SUCCESS;
}
<file_sep>/Projet-Jeu/src/test-fonction/fonction-test.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <grid.h>
#include <fonction-test.h>
#include <math.h>
#define END_GRID GRID_SIDE-1
#define HALF_GRID_SIDE (int)GRID_SIDE/2
#define EMPTY_TILE 0
#define TILE_2 1
#define TILE_4 2
#define TILE_8 3
#define TILE_16 4
#define TILE_32 5
/**
* \file fonction-test.c
* \brief Implementation de fonction-test.h
**/
bool test_new_grid(){
grid g = new_grid();
if(g == NULL)
return false;
delete_grid(g);
return true;
}
bool test_get_tile(grid g){
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j<GRID_SIDE; j++)
if(get_tile(g, i, j) != EMPTY_TILE )
return false;
return true;
}
bool test_set_tile(grid g){
// Passage de toutes les cases a 2
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, TILE_2);
// Verification que les cases sont a 2
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
if(get_tile(g, i, j) != TILE_2)
return false;
// Reset de la grid a zero
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE);
return true;
}
bool test_copy_grid(grid g){
grid gCopy = new_grid();
copy_grid(g, gCopy);
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
if(get_tile(g, i, j) != get_tile(gCopy, i, j))
return false;
delete_grid(gCopy);
return true;
}
bool test_get_score_grid(grid g){
if(grid_score(g) != 0)
return false;
return true;
}
bool test_game_over(grid g){
// On remplis la grille de case differentes pour evite les possibilites de deplacements
int nbr = 1;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++){
set_tile(g, i, j, nbr);
nbr++;
}
if(!game_over(g))
return false;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, TILE_2);
if(game_over(g))
return false;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE);
set_tile(g, 0, 0, TILE_2);
if(game_over(g))
return false;
return true;
}
static bool check_case_empty(grid g,int debuti,int fini,int debutj,int finj){
for(int i = debutj; i < finj; i++)
for(int j = debuti; j < fini; j++)
if(get_tile(g, i, j) != EMPTY_TILE)
return false;
return true;
}
bool test_do_move_up(grid g){
bool result = true;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, 0, TILE_2);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, END_GRID, TILE_2);
do_move(g, UP);
// On met des 2 sur la premiere ligne, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, 0) != TILE_4)
return false;
result = check_case_empty(g,1,GRID_SIDE,0,GRID_SIDE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, END_GRID, TILE_2);
do_move(g, UP);
// On met des 2 sur la premiere ligne, des 1 sur la deuxieme ligne et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, 0) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, 1) != TILE_2)
return false;
result = check_case_empty(g, 2, GRID_SIDE, 0, GRID_SIDE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, END_GRID, TILE_2);
do_move(g, UP);
// On met des 2 sur les deux premieres lignes, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, 0) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, 1) != TILE_4)
return false;
result = check_case_empty(g, 2, GRID_SIDE, 0, GRID_SIDE);
do_move(g, UP);
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, 0) != TILE_8)
return false;
result = check_case_empty(g, 1, GRID_SIDE, 0, GRID_SIDE);
return result;
}
bool test_do_move_down(grid g){
bool result = true;
// remise a 0 de la grille
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, END_GRID, TILE_2);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, 0, TILE_2);
do_move(g, DOWN);
// On met des 2 sur la premiere ligne, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, END_GRID) != TILE_4)
return false;
result = check_case_empty(g, 0, GRID_SIDE - 1, 0, GRID_SIDE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, 0, TILE_2);
do_move(g, DOWN);
// On met des 2 sur la premiere ligne, des 1 sur la deuxieme ligne et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, END_GRID) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, END_GRID - 1) != TILE_2)
return false;
result = check_case_empty(g, 0, END_GRID - 1, 0, GRID_SIDE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, 0, TILE_2);
do_move(g, DOWN);
// On met des 2 sur les deux premieres lignes, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, END_GRID) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, END_GRID - 1) != TILE_4)
return false;
result = check_case_empty(g, 0, GRID_SIDE - 2, 0, GRID_SIDE);
do_move(g, DOWN);
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, i, GRID_SIDE - 1) != TILE_8)
return false;
result = check_case_empty(g, 0, GRID_SIDE - 1, 0, GRID_SIDE);
return result;
}
bool test_do_move_left(grid g){
bool result = true;
// remise a 0 de la grille
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, 0, i, TILE_2);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, END_GRID, i, TILE_2);
do_move(g, LEFT);
// On met des 2 sur la premiere ligne, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, 0, i) != TILE_4)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 1, GRID_SIDE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, END_GRID, i, TILE_2);
do_move(g, LEFT);
// On met des 2 sur la premiere ligne, des 1 sur la deuxieme ligne et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, 0, i) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, 1, i) != TILE_2)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 2, GRID_SIDE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, END_GRID, i, TILE_2);
do_move(g, LEFT);
// On met des 2 sur les deux premieres lignes, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, 0, i) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, 1, i) != TILE_4)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 2, GRID_SIDE);
do_move(g, LEFT);
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, 0, i) != TILE_8)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 1, GRID_SIDE);
return result;
}
bool test_do_move_right(grid g){
bool result = true;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, END_GRID, i, TILE_2);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, 0, i, TILE_2);
do_move(g, RIGHT);
// On met des 2 sur la premiere ligne, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, END_GRID, i) != TILE_4)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 0, END_GRID);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, 0, i, TILE_2);
do_move(g, RIGHT);
// On met des 2 sur la premiere ligne, des 1 sur la deuxieme ligne et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, END_GRID, i) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, END_GRID - 1, i) != TILE_2)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 0, GRID_SIDE - 2);
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, 0, i, TILE_2);
do_move(g, RIGHT);
// On met des 2 sur les deux premieres lignes, et le reste de la grille est initialise a 0
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, END_GRID, i) != TILE_4)
return false;
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, END_GRID - 1, i) != TILE_4)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 0, HALF_GRID_SIDE);
do_move(g, RIGHT);
for(int i = 0; i < GRID_SIDE; i++)
if(get_tile(g, END_GRID, i) != TILE_8)
return false;
result = check_case_empty(g, 0, GRID_SIDE, 0, GRID_SIDE/4);
return result;
}
bool test_do_move_all(grid g){
bool result = true;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, TILE_2); // On initialise toute la grille a 2
do_move(g, UP);
//cas d'une grille impaire
if(GRID_SIDE%2 == 1){
for(int i = 0; i < GRID_SIDE; i++){
if(get_tile(g, i, GRID_SIDE/2) != TILE_2)
return false;
for(int j = 0; j < GRID_SIDE/2; j++)
if(get_tile(g, i, j) != TILE_4)
return false;
}
do_move(g, DOWN);
int nbLine8 = GRID_SIDE/4;
for(int i = 0; i < GRID_SIDE; i++){
if(get_tile(g, i, END_GRID) != TILE_2)
return false;
if((HALF_GRID_SIDE+1)%2 == 0){
if(get_tile(g, i, END_GRID - nbLine8 - 1) != TILE_4)
return false;
}
for(int j = nbLine8; j > 0; j--)
if(get_tile(g, i, END_GRID - j) != TILE_8)
return false;
}
do_move(g, RIGHT);
for(int i = HALF_GRID_SIDE+1; i < GRID_SIDE; i++){
if(get_tile(g, i, END_GRID) != TILE_4)
return false;
if((HALF_GRID_SIDE+1)%2 == 0)
if(get_tile(g, i, END_GRID - nbLine8 - 1) != TILE_8)
return false;
for(int j = nbLine8; j > 0; j--){
if((HALF_GRID_SIDE+1)%2 == 1)
if(get_tile(g, HALF_GRID_SIDE, END_GRID - j) != TILE_8)
return false;
if(get_tile(g, i, END_GRID - j) != TILE_16)
return false;
}
}
if((HALF_GRID_SIDE+1)%2 == 0){
if(get_tile(g, HALF_GRID_SIDE, END_GRID) != TILE_2)
return false;
if(get_tile(g, HALF_GRID_SIDE, END_GRID - nbLine8 - 1) != TILE_4)
return false;
}
do_move(g, LEFT);
for(int i = 1; i <= nbLine8 ; i++){
if(get_tile(g, i, END_GRID) != TILE_8)
return false;
if((HALF_GRID_SIDE+1)%2 == 0)
if(get_tile(g, i, END_GRID - nbLine8 - 1) != TILE_16)
return false;
if(get_tile(g, i, END_GRID - i) != TILE_32)
return false;
if(get_tile(g, 0, END_GRID - i) != TILE_8)
return false;
}
if(get_tile(g, 0, END_GRID) != TILE_2)
return false;
if((HALF_GRID_SIDE+1)%2 == 0){
if(get_tile(g, 0, END_GRID - nbLine8 - 1) != TILE_4)
return false;
if(get_tile(g, 0 + nbLine8 + 1, END_GRID - nbLine8 - 1) != TILE_8)
return false;
if(get_tile(g, 0 + nbLine8 + 1, END_GRID) != TILE_4)
return false;
for(int i = 0; i < nbLine8; i++)
if(get_tile(g, 0 + nbLine8 + 1, END_GRID - i - 1) != TILE_16)
return false;
}
}
else{
for(int i = 0; i < GRID_SIDE; i++){
for(int j = 0; j < HALF_GRID_SIDE; j++)
if(get_tile(g, i, j) != TILE_4)
return false;
}
do_move(g, DOWN);
for(int i = 0; i < GRID_SIDE; i++){
if((HALF_GRID_SIDE)%2 == 1)
if(get_tile(g, i, END_GRID - GRID_SIDE/4) != TILE_4)
return false;
for(int j = 0; j < GRID_SIDE/4; j++){
if(get_tile(g, i, END_GRID - j) != TILE_8)
return false;
}
}
do_move(g, RIGHT);
for(int i = HALF_GRID_SIDE + 1; i < GRID_SIDE; i++){
if((HALF_GRID_SIDE)%2 == 1)
if(get_tile(g, i, END_GRID - GRID_SIDE/4) != TILE_8)
return false;
for(int j = END_GRID; j > END_GRID - GRID_SIDE/4; j--)
if(get_tile(g, i, j) != TILE_16)
return false;
}
do_move(g, LEFT);
for(int i = 0; i < GRID_SIDE/4; i++){
if((HALF_GRID_SIDE)%2 == 1)
if(get_tile(g, i, END_GRID - GRID_SIDE/4) != TILE_16)
return false;
for(int j = END_GRID; j > END_GRID - GRID_SIDE/4; j--){
if((HALF_GRID_SIDE)%2 == 1)
if(get_tile(g, GRID_SIDE/4, j) != TILE_16)
return false;
if(get_tile(g, i, j) != TILE_32)
return false;
}
}
if((HALF_GRID_SIDE)%2 == 1){
if(get_tile(g, GRID_SIDE/4, END_GRID - GRID_SIDE/4) != TILE_8)
return false;
}
}
return result;
}
bool test_can_move(grid g){
// On initialise toute la grille a 0
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE);
if(can_move(g, UP) || can_move(g, DOWN) || can_move(g, RIGHT) || can_move(g, LEFT) )
return false;
// On place une tuile en plein milieu de la grille
set_tile(g, HALF_GRID_SIDE, HALF_GRID_SIDE, TILE_2);
if( !can_move(g, UP) || !can_move(g, DOWN) || !can_move(g, RIGHT) || !can_move(g, LEFT))
return false;
set_tile(g, HALF_GRID_SIDE, HALF_GRID_SIDE, EMPTY_TILE);
// On rempli la ligne du bas de fusion possible, avec un compteur qui creera des tuiles de valeurs croissantes
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, END_GRID, TILE_2);
if(!can_move(g, UP) || can_move(g, DOWN) || !can_move(g,RIGHT) || !can_move(g, LEFT))
return false;
// On interdit les fusion
int tile = 1;
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, END_GRID, tile++);
if(!can_move(g, UP) || can_move(g, DOWN) || can_move(g,RIGHT) || can_move(g, LEFT))
return false;
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, i, END_GRID, EMPTY_TILE);
// On place deux tuiles en haut a gauche de la grille
set_tile(g, 0, 0, TILE_2);
set_tile(g, 1, 0, TILE_2);
if(can_move(g, UP) || !can_move(g, DOWN) || !can_move(g, RIGHT) || !can_move(g, LEFT))
return false;
set_tile(g, 1, 0, EMPTY_TILE);
// On place une deuxieme tuiles sous la premiere (en x = 0; fusion possible)
set_tile(g, 0, 1, TILE_2);
if(!can_move(g, UP) || !can_move(g, DOWN) || !can_move(g, RIGHT) || can_move(g, LEFT))
return false;
// On la change (fusion impossible)
set_tile(g, 0, 1, TILE_4);
if(can_move(g, UP) || !can_move(g, DOWN) || !can_move(g, RIGHT) || can_move(g, LEFT))
return false;
// On continue de remplir la colonne de tiles a valeur croissantes(fusion impossible)
tile = 1;
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, 0, i, tile++);
if(can_move(g, UP) || can_move(g, DOWN) || !can_move(g, RIGHT) || can_move(g, LEFT))
return false;
// On autorise une fusion
for(int i = 0; i < 2; i++)
set_tile(g, 0, i,TILE_2);
if(!can_move(g, UP) || !can_move(g, DOWN) || !can_move(g, RIGHT) || can_move(g, LEFT))
return false;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE); // On initialise toute la grille a 0
if(can_move(g, UP) || can_move(g, DOWN) || can_move(g, RIGHT) || can_move(g, LEFT))
return false;
// On remplit la derniere colonne du tableau
for(int i = 0; i < GRID_SIDE; i++)
set_tile(g, END_GRID, i, TILE_2);
if(!can_move(g, UP) || !can_move(g, DOWN) || !can_move(g, LEFT) || can_move(g, RIGHT))
return false;
return true;
}
bool test_add_tile(grid g){
int rand4 = 0;
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++)
set_tile(g, i, j, EMPTY_TILE); // On initialise toute la grille a 0
for(int k = GRID_SIDE * GRID_SIDE; k > 0; k--)
add_tile(g);
for(int i = 0; i < GRID_SIDE; i++)
for(int j = 0; j < GRID_SIDE; j++){
if(get_tile(g, i, j) == EMPTY_TILE)
return false;
if
(get_tile(g, i, j) == TILE_4)
rand4 += 1;
}
if(rand4 < 1)
return false;
return true;
}
<file_sep>/Projet-Jeu/src/Makefile
LIBS= grid sdl strategy test-fonction ncurses
all: install
for i in $(LIBS);do\
$(MAKE) -C $$i all;\
done
install:
for i in $(LIBS);do\
$(MAKE) -C $$i install;\
done
check: all
$(MAKE) -C test-fonction check
clean:
for i in $(LIBS);do\
$(MAKE) -C $$i clean;\
done
<file_sep>/Projet-Jeu/src/strategy/A2_emery_gouraud_kirov_pouteau_low.c
#include <strategy.h>
#include <time.h>
#include <math.h>
#include <assert.h>
#include <grid.h>
#include <stdlib.h>
#define DEPTH 2
#define CASE_UP 0
#define CASE_LEFT 1
#define CASE_DOWN 2
#define CASE_RIGHT 3
#define MOVE_IMPOSSIBLE -999999999
#define ANY_CASE_EMPTY -9999999
/* define pour la note de la grille */
#define BONUS_CORNER 3000
#define BONUS_HIGH_MAXIMUM 600
#define BONUS_SCORE 60
#define BONUS_CASE_EMPTY 750
#define MALUS_SIGN_CHANGE 1025
/**
* \file A2_emery_gouraud_kirov_pouteau_low.c
* \brief Stratégie lente
**/
/**
* \brief Strategie utilisé
* \return stretegy
*/
strategy A2_emery_gouraud_kirov_pouteau_low();
/**
* \brief Permet de recupérer la meilleur direction
* \param str stratégie utilisé
* \param g grille
* \return direction
*/
static dir best_move(strategy str, grid g);
/**
* \brief Etude en profondeur
* \param g grille
* \param depth profondeur de l'étude voulue
* \param *d pointeur sur une direction
* \return long int
*/
static long int repetition_grid(grid g, int depth, dir *d);
/**
* \brief trouve le maximum
* \param max0,max1 les deux maximum
* \param dir0,dir1 direction des maximum
* \param *dir2 pointeur sur une direction
* \return long int
*/
static long int maximum(long int max0, long int max1, dir dir0, dir dir1, dir *dir2);
/**
* \brief note la configuration du grille
* \param g grille
* \return long int
*/
static long int grid_note(grid g);
/**
* \brief note la monotonicité d'une case par rapport à celle qui l'entoure
* \param g
* \param x,y coordonnée de la case
* \return long int
*/
static long int monotonicity(grid g, int x, int y);
strategy A2_emery_gouraud_kirov_pouteau_low(){
strategy str = malloc(sizeof(struct strategy_s));
str->name = "strategy_low";
str->mem = NULL;
str->free_strategy = free_memless_strat;
str->play_move = best_move;
return str;
}
void free_memless_strat(strategy strat){
free(strat);
}
static dir best_move(strategy str, grid g){
int depth = DEPTH;
dir d = UP;
int cpt_case_empty = 0;
for(int y = 0; y < GRID_SIDE; y++){
for(int x = 0; x < GRID_SIDE; x++){
if(get_tile(g, x, y) == 0){
cpt_case_empty++;
}
}
}
if (cpt_case_empty < 6)
depth++;
if (cpt_case_empty < 2)
depth++;
if (cpt_case_empty < 1)
depth++;
repetition_grid(g, depth, &d);
return d;
}
static long int repetition_grid(grid g, int depth, dir *d){
if(game_over(g)){
return 0;
}
if(depth == 0){
return grid_note(g);
}
long int tab[4];
grid g_copy = new_grid();
int indice_tab = -1;
// Traite les 4 mouvements possibles et stock leur valeur dans un tableau
for(int i = UP; i <= RIGHT; i++){
long int note = 0;
int cpt = 0;
indice_tab++;
copy_grid(g, g_copy);
if(can_move(g_copy, i)){
do_move(g_copy, i);
// Genere les 2 et les 4 dans chaque position vide
for(int y = 0; y < GRID_SIDE; y++)
for(int x = 0; x < GRID_SIDE; x++)
if(get_tile(g_copy, x, y) == 0){
set_tile(g_copy,x, y, 1);
// Rappelle la fonction et multiplie le resultat par 9 car 90% de chance d'avoir un 2
note += (long int) 9 * repetition_grid(g_copy, depth - 1, d);
set_tile(g_copy, x, y, 2);
// Rappelle la fonction et multiplie le resultat par 1 car 10% de chance d'avoir un 4
note += (long int) repetition_grid(g_copy, depth - 1, d);
set_tile(g_copy, x, y, 0);
cpt += 10;
}
// Si pas de case vide alors on met une mauvaise note
if(cpt == 0)
tab[indice_tab] = ANY_CASE_EMPTY;
// Renvoie la moyenne des notes dans la case du tableau correspondant
else
tab[indice_tab] = (long int)(note / cpt);
}
// Si le mouvement est impossible on met une mauvaise note
else{
tab[indice_tab] = MOVE_IMPOSSIBLE;
}
}
delete_grid(g_copy);
dir mdU_L;
dir mdD_R;
// Selectionne la meilleure valeur obtenue apres un UP et un LEFT et stock la direction dans mdU_L
long int max_UD = maximum(tab[CASE_UP], tab[CASE_LEFT], UP, LEFT, &mdU_L);
// Selectionne la meilleure valeur obtenue apres un DOWN et un RIGHT et stock la direction dans mdW_R
long int max_LR = maximum(tab[CASE_DOWN], tab[CASE_RIGHT], DOWN, RIGHT, &mdD_R);
// Renvoie la meilleure valeur obtenue apres un mdU_L et un mdD_R et stock la direction dans d
return maximum(max_UD, max_LR, mdU_L, mdD_R, d);
}
static long int maximum(long int max0, long int max1, dir dir0, dir dir1, dir *dir2){
if(max0 >= max1){
*dir2 = dir0;
return max0;
}
*dir2 = dir1;
return max1;
}
/* ==================================
NOTE
================================== */
static long int grid_note(grid g){
long int cpt = 0;
int cpt_case_empty = 0;
int cpt_sign_change = 0;
int max = 0;
// Parcours de la grille
for(int y = 0; y < GRID_SIDE; y++){
for(int x = 0; x < GRID_SIDE; x++){
cpt += get_tile(g, x, y);
// Determination de la valeur maximum
if(get_tile(g, x, y) > max)
max = get_tile(g, x, y);
// Determination du nombre de case vide
if(get_tile(g, x, y) == 0)
cpt_case_empty++;
// Monotonicite de la grille
cpt_sign_change += monotonicity(g, x, y);
}
}
// Bonus coin superieur gauche
if(get_tile(g, 0, 0) == max)
cpt += BONUS_CORNER * max;
// Autres bonus
cpt += BONUS_HIGH_MAXIMUM * pow(2, max);
cpt += BONUS_SCORE * grid_score(g);
cpt += BONUS_CASE_EMPTY * cpt_case_empty;
// Malus si pas monotone
cpt -= MALUS_SIGN_CHANGE * cpt_sign_change;
return cpt;
}
static long int monotonicity(grid g, int x, int y){
int cpt_sign_change = 0;
if(x < GRID_SIDE - 1){
if(get_tile(g, x, y) < get_tile(g, x + 1, y))
cpt_sign_change += get_tile(g, x + 1, y) - get_tile(g, x, y);
if(get_tile(g, y, x) < get_tile(g, y, x + 1))
cpt_sign_change += get_tile(g, y, x + 1) - get_tile(g, y, x);
}
return cpt_sign_change;
}
<file_sep>/Projet-Jeu/src/sdl/gridSDL.c
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_getenv.h>
#include <grid.h>
#include <gridSDL.h>
/**
* \file gridSDL.c
* \brief Implementation de gridSDL.h
* Ce fichier contient les fonctions de l'interface graphique SDL,
* du jeu du 2048.
**/
// Chemins relatifs des differents composants graphiques (tiles, animations, bouton, police, etc.)
#define PATH_TILE "../src/sdl/tiles/"
#define PATH_ANIMATION "../src/sdl/animation_penguin/"
#define PATH_BUTTON_MENU "../src/sdl/menu_button/"
#define PATH_FILE_HIGHSCORE "../src/sdl/highscore_sdl.txt"
#define PATH_POLICE_GAME "../src/sdl/arial.ttf"
#define PATH_POLICE_MENU "../src/sdl/leadcoat.ttf"
// Define permettant une maintenabilite et une inherence a GRID_SIDE de l'interface graphique
#define TILE_SIDE 100 // Taille de la tuile
#define WINDOW_MENU_WIDTH 400 // Largeur de la fenetre
#define WINDOW_MENU_HEIGHT 600 // Hauteur de la fenetre
#define WINDOW_WIDTH ((GRID_SIDE == 2 ? 3 : GRID_SIDE) + 1) * TILE_SIDE // Largeur de la fenetre
#define WINDOW_HEIGHT (GRID_SIDE + 2) * TILE_SIDE // Hauteur de la fenetre
#define POSITION_TILE_X (WINDOW_WIDTH - GRID_SIDE * TILE_SIDE)/2 // Position abscisse de la grille
#define POSITION_TILE_Y ((WINDOW_HEIGHT - (1 + GRID_SIDE) * TILE_SIDE)/2 + 10) // Position ordonnee de la grille
#define POSITION_BACKGROUND_X (POSITION_TILE_X - 10) // Position abscisse de l'arriere plan de la grille
#define POSITION_BACKGROUND_Y (POSITION_TILE_Y - 10) // Position ordonnee de l'arriere plan de la grille
// Variable global pour la couleur des tuiles
static char *char_color;
// Declaration des fonctions static
static void display_animation(SDL_Surface *surface_screen);
static void display_menu(SDL_Surface *surface_screen);
static void display_grid(grid g, SDL_Surface *surface_screen);
static void display_score(grid g, SDL_Surface *surface_screen);
static void display_gameover(grid g, SDL_Surface *surface_screen, SDL_Surface *surface_background_grid, SDL_Rect position_background_grid, bool *try_again);
static void display_text(SDL_Surface *surface_screen, TTF_Font *police_text, SDL_Color color_text, SDL_Color color_background, char *char_text, int position_height, bool transparence);
static void enter_nickname(grid g, SDL_Surface *surface_screen, SDL_Surface *surface_background_grid, SDL_Rect position_background_grid, char *char_highscore, bool *end_game, bool *try_again);
static void read_line(FILE *fichier, char *char_nickname, char *char_highscore);
static void write_line(FILE *fichier, char *char_nickname, char *char_highscore);
/* =============================================
== IMPLEMENTATION DE L'INTERFACE GRIDSDL.H ==
============================================= */
void game_sdl(){
// Initialisation de la fenetre du jeu
SDL_Surface *surface_screen = NULL;
SDL_WM_SetCaption("Game 2048 - by <NAME>", NULL);
// Initialisation du contour autour de la grille (sa couleur dependra du choix de l'utilisateur)
SDL_Surface *surface_background_grid = NULL;
surface_background_grid = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_DOUBLEBUF, 20 + TILE_SIDE * GRID_SIDE, 20 + TILE_SIDE * GRID_SIDE, 32, 0, 0, 0, 0);
SDL_Rect position_background_grid;
position_background_grid.x = POSITION_BACKGROUND_X;
position_background_grid.y = POSITION_BACKGROUND_Y;
// Initialisation de la grille
grid g = new_grid();
add_tile(g);
add_tile(g);
// Parametres boucle du jeu
bool game_loop = true; // Boolean de la boucle du jeu
bool try_again = false; // Boolean permettant de relancer un nouveau jeu
bool menu = true; // Boolean pour le menu
bool game = false; // Boolean pour le jeu
bool change_color = false;
int current_time = 0, before_time = 0;
SDL_Event event;
// Boucle du jeu
while(game_loop){
if(menu){
current_time = SDL_GetTicks();
if(current_time - before_time > 200){
surface_screen = SDL_SetVideoMode(WINDOW_MENU_WIDTH, WINDOW_MENU_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
SDL_FillRect(surface_screen, NULL, SDL_MapRGB(surface_screen->format, 255, 255, 255));
display_menu(surface_screen);
before_time = current_time;
display_animation(surface_screen);
SDL_Flip(surface_screen);
}
}
if(SDL_PollEvent(&event)){
// Permet de quitter (en cliquant sur la croix pour fermer)
if(event.type == SDL_QUIT)
game_loop = false;
else if(event.type == SDL_KEYDOWN){
switch(event.key.keysym.sym){
// Choix de la direction a partir des touches directionnelles
case SDLK_UP:
if(game && can_move(g, UP))
play(g, UP);
break;
case SDLK_DOWN:
if(game && can_move(g, DOWN))
play(g, DOWN);
break;
case SDLK_LEFT:
if(game && can_move(g, LEFT))
play(g, LEFT);
break;
case SDLK_RIGHT:
if(game && can_move(g, RIGHT))
play(g, RIGHT);
break;
// Rejouer
case SDLK_RETURN:
try_again = true;
game_loop = false;
break;
// Quitter la partie
case SDLK_ESCAPE:
game_loop = false;
break;
// Choix de la couleur des tuiles
case SDLK_F1:
char_color = "green/";
change_color = true;
break;
case SDLK_F2:
char_color = "red/";
change_color = true;
break;
case SDLK_F3:
char_color = "blue/";
change_color = true;
break;
default:
break;
}
}
}
// S'il y a des deplacements de souris, les ignorer
else if(event.type == SDL_MOUSEMOTION)
continue;
if(change_color){
if(menu)
surface_screen = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
// strcmp compare deux chaines de caracteres et retourne 0 si elle sont identiques
if(strcmp(char_color, "green/") == 0)
SDL_FillRect(surface_background_grid, NULL, SDL_MapRGB(surface_screen->format, 0, 150, 50)); // vert fonce
else if(strcmp(char_color, "red/") == 0)
SDL_FillRect(surface_background_grid, NULL, SDL_MapRGB(surface_screen->format, 255, 0, 0));
else if(strcmp(char_color, "blue/") == 0)
SDL_FillRect(surface_background_grid, NULL, SDL_MapRGB(surface_screen->format, 0, 0, 255));
menu = false;
game = true;
change_color = false;
}
if(game){
// Affiche le jeu
SDL_FillRect(surface_screen, NULL, SDL_MapRGB(surface_screen->format, 255, 255, 255));
SDL_BlitSurface(surface_background_grid, NULL, surface_screen, &position_background_grid);
display_grid(g, surface_screen);
display_score(g, surface_screen);
SDL_Flip(surface_screen);
}
if(game_over(g)){
display_gameover(g, surface_screen, surface_background_grid, position_background_grid, &try_again);
game_loop = false;
}
}
// Libere la memoire allouee
delete_grid(g);
SDL_FreeSurface(surface_background_grid);
SDL_FreeSurface(surface_screen);
// Relance un nouveau jeu si le joueur l'a decide
if(try_again)
game_sdl();
}
/* =========================================
== IMPLEMENTATION DES FONCTIONS STATIC ==
========================================= */
/**
* \brief Affiche l'animation
* \param surface_screen surface sur laquelle sera affichee l'animation
**/
static void display_animation(SDL_Surface *surface_screen){
static int num_animation = 0; // numero de l'animation
static int position_x = WINDOW_MENU_WIDTH - 135;
static bool run_right = false;
char char_animation[50];
SDL_Surface *surface_animation = NULL;
SDL_Rect position_animation;
position_animation.x = position_x;
position_animation.y = 10;
num_animation++;
if(num_animation > 20){
run_right = (run_right? false : true);
num_animation = 1;
}
if(num_animation < 6 || num_animation > 14){
if(run_right)
position_x += 20;
else
position_x -= 20;
}
// tableaux contenant l'ordre des numeros de l'animation
int tab_backward[22] = {1,2,1,2,1,2,3,4,3,5,6,5,6,5,6,7,8,7,8,7,8}; // Retour du pingouin (de droite a gauche)
int tab_forward[22] = {9,10,9,10,9,10,11,12,11,12,11,12,14,13,14,15,16,15,16,15,16}; // Aller du pingouin (de gauche a droite)
if(run_right)
sprintf(char_animation, "%spenguin_%d.bmp", PATH_ANIMATION, tab_forward[num_animation]);
else
sprintf(char_animation, "%spenguin_%d.bmp", PATH_ANIMATION, tab_backward[num_animation]);
surface_animation = SDL_LoadBMP(char_animation);
SDL_SetColorKey(surface_animation, SDL_SRCCOLORKEY, SDL_MapRGB(surface_animation->format, 255, 255, 255));
SDL_BlitSurface(surface_animation, NULL, surface_screen, &position_animation);
SDL_FreeSurface(surface_animation);
}
/**
* \brief Affiche le menu
* \param surface_screen surface sur laquelle sera affiche le menu
**/
static void display_menu(SDL_Surface *surface_screen){
// Parametres des boutons
char char_button[50];
SDL_Surface *surface_button;
SDL_Rect position_button;
int nb_button = 4;
TTF_Font *police_text = TTF_OpenFont(PATH_POLICE_MENU, 43);
SDL_Color color_text = {0, 0, 0}; // Couleur noire
SDL_Color color_background = {255, 255, 255}; // Couleur blanche
for(int i = 0; i < nb_button; i++){
if(i == 0){
sprintf(char_button, "%s2048.bmp", PATH_BUTTON_MENU);
position_button.y = 62;
}
if(i == 1){
sprintf(char_button, "%sF1_Green.bmp", PATH_BUTTON_MENU);
position_button.y = 3 * WINDOW_MENU_HEIGHT / 6;
}
if(i == 2){
sprintf(char_button, "%sF2_Red.bmp", PATH_BUTTON_MENU);
position_button.y = 4 * WINDOW_MENU_HEIGHT / 6;
}
if(i == 3){
sprintf(char_button, "%sF3_Blue.bmp", PATH_BUTTON_MENU);
position_button.y = 5 * WINDOW_MENU_HEIGHT / 6;
}
surface_button = SDL_LoadBMP(char_button);
position_button.x = (WINDOW_MENU_WIDTH - surface_button->w) / 2;
SDL_BlitSurface(surface_button, NULL, surface_screen, &position_button);
display_text(surface_screen, police_text, color_text, color_background, "Choose a color to", 220, false);
display_text(surface_screen, police_text, color_text, color_background, "start the Game", 270, false);
SDL_FreeSurface(surface_button);
}
TTF_CloseFont(police_text);
}
/**
* \brief Affiche la grille
* \param g grid
* \param surface_screen surface sur laquelle sera affiche la grille
**/
static void display_grid(grid g, SDL_Surface *surface_screen){
SDL_Surface *surface_tile = NULL;
SDL_Rect position_tile;
char name_tile[40];
for(int i = 0; i < GRID_SIDE; i++){
for(int j = 0; j < GRID_SIDE; j++){
position_tile.x = POSITION_TILE_X + i * TILE_SIDE;
position_tile.y = POSITION_TILE_Y + j * TILE_SIDE;
sprintf(name_tile, "%s%stile_%d.bmp", PATH_TILE, char_color, (int)get_tile(g, i, j));
surface_tile = SDL_LoadBMP(name_tile);
SDL_BlitSurface(surface_tile, NULL, surface_screen, &position_tile);
SDL_FreeSurface(surface_tile);
}
}
}
/**
* \brief Affiche le score
* \param g grid
* \param surface_screen surface sur laquelle sera affiche le score
**/
static void display_score(grid g, SDL_Surface *surface_screen){
// Parametres affichage score
TTF_Font *police_text = TTF_OpenFont(PATH_POLICE_GAME, 30);
SDL_Color color_text = {255, 0, 0}; // Couleur rouge
SDL_Color color_background = {255, 255, 255}; // Couleur blanche
char char_score[100];
int position_text_y = 2 * POSITION_BACKGROUND_Y + GRID_SIDE * TILE_SIDE;
// Ouverture (et si besoin creation) du fichier contenant l'highscore
FILE* highscore_txt = fopen(PATH_FILE_HIGHSCORE, "r+");
if(highscore_txt == NULL)
highscore_txt = fopen(PATH_FILE_HIGHSCORE, "w");
// Recupere le pseudo et le highscore sauvegardes precedemment
char char_highscore[10] = "";
char char_nickname[10] = "";
read_line(highscore_txt, char_nickname, char_highscore);
unsigned long int highscore = strtoul(char_highscore, NULL, 10); // Convertit une chaine de caractere en unsigned long int
sprintf(char_score, "Score : %lu", grid_score(g));
display_text(surface_screen, police_text, color_text, color_background, char_score, POSITION_BACKGROUND_Y/2, false);
// Affiche l'highscore
if(grid_score(g) >= highscore){
sprintf(char_highscore, "%lu", grid_score(g));
write_line(highscore_txt, char_nickname, char_highscore);
sprintf(char_score, "New Highscore : %s !!", char_highscore);
display_text(surface_screen, police_text, color_text, color_background, char_score, position_text_y - 5, false);
}else{
sprintf(char_score, "Highscore :%s - %s", char_highscore, char_nickname);
display_text(surface_screen, police_text, color_text, color_background, char_score, position_text_y - 5, false);
}
TTF_Font *police_menu = TTF_OpenFont(PATH_POLICE_GAME, 25);
char char_recommencer[30] = "Press ENTER to TRY AGAIN";
display_text(surface_screen, police_menu, color_text, color_background, char_recommencer, (WINDOW_HEIGHT + 2 * position_text_y)/3 + 5, false);
char char_giveUp[30] = "or ESC to GIVE UP";
display_text(surface_screen, police_menu, color_text, color_background, char_giveUp, (2 * WINDOW_HEIGHT + position_text_y)/3 + 5, false);
// Libere la memoire allouee et ferme le fichier contenant l'Highscore
TTF_CloseFont(police_text);
TTF_CloseFont(police_menu);
fclose(highscore_txt);
}
/**
* \brief Affiche le Game Over
* \param surface_screen surface sur laquelle sera affiche le Game Over
* \param surface_background_grid surface de l'arriere plan de la grille
* \param position_background_grid position du fond
* \param try_again pointeur de boolean permettant de relancer le jeu
**/
static void display_gameover(grid g, SDL_Surface *surface_screen, SDL_Surface *surface_background_grid, SDL_Rect position_background_grid, bool *try_again){
SDL_Color color_text = {255, 255, 255}; // Couleur blanche
SDL_Color color_background = {0, 0, 0}; // Couleur noire
char *char_gameover = "GAME OVER";
TTF_Font *police_gameover = TTF_OpenFont(PATH_POLICE_GAME, (GRID_SIDE == 2 ? 30 : 53));
bool end_game = true; // Boolean de la boucle de fin du jeu
char char_highscore[10]; // Chaine de caractere contenant le highscore
char char_nickname[10]; // Chaine de caractere contenant le pseudo
FILE* highscore_txt = fopen(PATH_FILE_HIGHSCORE, "r+");
read_line(highscore_txt, char_nickname, char_highscore);
fclose(highscore_txt);
unsigned long int highscore = strtoul(char_highscore, NULL, 10); // Convertit une chaine de caractere en unsigned long int
display_grid(g, surface_screen);
// Ajout d'un transparent sur la grille (de la couleur du contour de la grille)
SDL_SetAlpha(surface_background_grid, SDL_SRCALPHA, 125);
SDL_BlitSurface(surface_background_grid, NULL, surface_screen, &position_background_grid);
SDL_Flip(surface_screen);
// Reecriture de l'Highscore si nouvel highscore
if(grid_score(g) == highscore)
enter_nickname(g, surface_screen, surface_background_grid, position_background_grid, char_highscore, &end_game, try_again);
else
display_text(surface_screen, police_gameover, color_text, color_background, char_gameover, POSITION_TILE_Y + (GRID_SIDE * TILE_SIDE)/2, true);
SDL_Flip(surface_screen);
// Boucle de fin
SDL_Event event;
while(end_game){
SDL_WaitEvent(&event);
if(event.type == SDL_QUIT){
end_game = false;
}
else if(event.type == SDL_KEYDOWN){
switch(event.key.keysym.sym){
case SDLK_RETURN:
*try_again = true;
end_game = false;
break;
case SDLK_ESCAPE:
end_game = false;
break;
default:
break;
}
}
}
// Libere la memoire allouee
TTF_CloseFont(police_gameover);
}
/**
* \brief Affiche le texte voulue avec comme caracteristique la police, la couleur, la couleur de l'arriere plan
et la position souhaitees (ainsi que la possibilite de mettre la couleur de l'arriere plan en transparence)
* \param surface_screen surface sur laquelle sera affiche le texte
* \param police_text police du texte
* \param color_text couleur du texte
* \param color_background couleur du fond
* \param char_texte chaine de caractere contenant le texte a afficher
* \param position_height position en hauteur du texte
* \param transparence boolean permettant de mettre la couleur de l'arriere plan du texte en transparence
**/
static void display_text(SDL_Surface *surface_screen, TTF_Font *police_text, SDL_Color color_text, SDL_Color color_background, char *char_text, int position_height, bool transparence){
SDL_Surface *surface_text = NULL;
SDL_Rect position_text;
surface_text = TTF_RenderText_Shaded(police_text, char_text, color_text, color_background);
// Met en transparent la couleur de l'arriere plan du texte
if(transparence)
SDL_SetColorKey(surface_text, SDL_SRCCOLORKEY, SDL_MapRGB(surface_text->format, 0, 0, 0));
position_text.x = (surface_screen->w - surface_text->w)/2; // Centre le texte
position_text.y = position_height - surface_text->h/2;
SDL_BlitSurface(surface_text, NULL, surface_screen, &position_text);
// Libere la memoire allouee
SDL_FreeSurface(surface_text);
}
/**
* \brief Recupere le pseudo saisi par l'utilisateur et l'ecrit dans le fichier contenant l'highscore
* \param g grid
* \param surface_screen surface sur laquelle sera affiche le pseudo saisi
* \param surface_background_grid surface de l'arriere plan de la grille
* \param position_background_grid position de l'arriere plan
* \param char_highscore chaine de caractere contenant l'highscore
* \param end_game pointeur de boolean permettant de quitter le jeu
* \param try_again pointeur de boolean permettant de relancer le jeu
**/
static void enter_nickname(grid g, SDL_Surface *surface_screen, SDL_Surface *surface_background_grid, SDL_Rect position_background_grid, char *char_highscore, bool *end_game, bool *try_again){
FILE* highscore_txt = fopen(PATH_FILE_HIGHSCORE, "r+");
TTF_Font *police_text = TTF_OpenFont(PATH_POLICE_GAME, (GRID_SIDE == 2 ? 20 : 30));
TTF_Font *police_gameover = TTF_OpenFont(PATH_POLICE_GAME, (GRID_SIDE == 2 ? 30 : 53));
SDL_Color color_text = {255, 255, 255}; // Couleur blanche
SDL_Color color_background = {0, 0, 0}; // Couleur noire
char char_nickname[10] = ""; // Chaine de caractere qui contiendra le nouveau pseudo
char *char_gameover = "GAME OVER";
char char_display[60] = ""; // Chaine de caractere qui contiendra "char_highscore - char_nickname"
char char_tmp[9] = "********"; // Chaine de caractere permettant au joueur de visualiser le nombre de caractere restant pour ecrire son pseudo
char char_newHighscore[30] = ""; // Chaine de caractere qui contiendra "New Highscore - char_highscore"
// Position du texte (inherent a GRID_SIDE)
int position_adjusted = ((GRID_SIDE == 2 ? 2 : 3) * TILE_SIDE)/5;
int position_y_text = POSITION_TILE_Y + (GRID_SIDE * TILE_SIDE)/2 - position_adjusted * 5/2;
SDL_Event event;
int cpt_char = 0; // Nombre de caractere saisi par l'utilisateur
int nb_max_char = 8; // Nombre maximum de caractere pour le pseudo
bool re_display = true; // Boolean de reaffichage de l'ecran
bool enter_new_nickname = true; // Boolean de la boucle de saisi du nouveau pseudo
SDL_EnableUNICODE(1); // active l'unicode
// Boucle while permettant de recuperer et de sauvegarder le pseudo saisi par l'utilisateur, dans le fichier hghscore_sdl.txt
while(enter_new_nickname){
// Affiche tous les elements lies au Game Over, ainsi que le nouveau pseudo saisi
if(re_display){
sprintf(char_display, "%s - %s%s", char_highscore, char_nickname, char_tmp);
write_line(highscore_txt, char_nickname, char_highscore);
display_grid(g, surface_screen);
SDL_SetAlpha(surface_background_grid, SDL_SRCALPHA, 125);
SDL_BlitSurface(surface_background_grid, NULL, surface_screen, &position_background_grid);
display_text(surface_screen, police_gameover, color_text, color_background, char_gameover, position_y_text + position_adjusted, true);
sprintf(char_newHighscore, "New Highscore : %s !!", char_highscore);
display_text(surface_screen, police_text, color_text, color_background, char_newHighscore, position_y_text + 2 * position_adjusted, true);
display_text(surface_screen, police_text, color_text, color_background, "Enter your nickname :", position_y_text + 3 * position_adjusted,true);
display_text(surface_screen, police_text, color_text, color_background, char_display, position_y_text + 4 * position_adjusted, true);
SDL_Flip(surface_screen);
re_display = false;
}
SDL_WaitEvent(&event);
if(event.type == SDL_QUIT){
enter_new_nickname = false;
*end_game = false;
}
else if(event.type == SDL_KEYDOWN){
switch(event.key.keysym.sym){
// Quitter la partie
case SDLK_ESCAPE:
enter_new_nickname = false;
*end_game = false;
break;
case SDLK_RETURN: // Touche "entree"
enter_new_nickname = false;
*end_game = false;
*try_again = true;
break;
case SDLK_BACKSPACE: // Touche "supprimer"
if(cpt_char > 0){
char_nickname[strlen(char_nickname) - 1] = '\0';
char_tmp[nb_max_char - cpt_char] = '*';
re_display = true;
cpt_char -= 1;
}
break;
default:
if(nb_max_char > cpt_char){
// Si la touche est une lettre, un chiffre ou un symbole
if(event.key.keysym.unicode >= 32 && event.key.keysym.unicode <= 126){
sprintf(char_nickname, "%s%c", char_nickname, (char)event.key.keysym.unicode);
char_tmp[nb_max_char - cpt_char - 1] = '\0';
re_display = true;
cpt_char += 1;
}
}
break;
}
}
// S'il y a des deplacements de souris, les ignorer
else if(event.type == SDL_MOUSEMOTION)
continue;
}
SDL_EnableUNICODE(0); // desactive l'unicode
// Libere la memoire allouee et ferme le fichier stockant le Highscore
TTF_CloseFont(police_text);
TTF_CloseFont(police_gameover);
fclose(highscore_txt);
}
/**
* \brief Lit dans le fichier passe en parametre, les 10 premiers caracteres et les stockent dans char_nickname,
et stockent les 10 caracteres suivants dans le char_highscore.
* \param char_nickname chaine de caractere qui contiendra le pseudo
* \param char_highscore chaine de caractere qui contiendra l'highscore
**/
static void read_line(FILE *fichier, char *char_nickname, char *char_highscore){
rewind(fichier); // Revient au debut du fichier
// Si le fichier n'est pas vide
if(!feof(fichier)){
fgets(char_nickname, 10, fichier);
fgets(char_highscore, 10, fichier);
for(int i = 9; i > 0; i--){
if(char_nickname[i-1] == ' ')
char_nickname[i-1] = '\0';
else
break;
}
for(int i = 9; i > 0; i--){
if(char_highscore[i-1] == ' ')
char_highscore[i-1] = '\0';
else
break;
}
}
}
/**
* \brief Ecrit dans le fichier passe en parametre,
la chaine de caracteres char_nickname (suivie d'espaces afin de stocker 10 caracteres),
et la chaine de caracteres char_highscore, (suivie d'espaces afin de stocker 10 caracteres),
* \param char_nickname chaine de caractere qui contiendra le pseudo
* \param char_highscore chaine de caractere qui contiendra l'highscore
**/
static void write_line(FILE *fichier, char *char_nickname, char *char_highscore){
rewind(fichier); // Revient au debut du fichier
// Si la chaine passee en parametre est vide, on ecrit "Anyone" par defaut dans le pseudo
if(strlen(char_nickname) == 0){
char_nickname = "Anyone";
}
fprintf(fichier, "%-10s%-10s", char_nickname, char_highscore);
}
<file_sep>/Projet-Jeu/src/sdl/Makefile
CC = gcc
CFLAGS = -std=c99 -g -Wall -I../../include
LDLIBS = -lgridSDL -lSDL -lSDL_image -lSDL_ttf -lgrid -lm -lgcov -L ../../lib/
CPPFLAGS=
PATH_INCLUDE=../../include
PATH_LIB=../../lib
PATH_BIN=../../bin
all: $(PATH_LIB)/libgridSDL.a $(PATH_BIN)/jeu_sdl
$(PATH_BIN)/jeu_sdl: main-sdl.o $(PATH_LIB)/*
$(CC) -o $(PATH_BIN)/jeu_sdl main-sdl.o $(LDLIBS)
install: $(PATH_LIB)/libgridSDL.a
$(PATH_LIB)/libgridSDL.a: gridSDL.o
ar -cr $(PATH_LIB)/libgridSDL.a gridSDL.o
include dep
.PHONY: clean
clean:
rm -f dep *.o *~ jeu main-sdl-test *.g*
dep:
$(CC) $(CPPFLAGS) -MM *.c >dep
<file_sep>/Projet-Jeu/Makefile
LIBS= src
all:
if [ ! -d "bin" ];then mkdir bin; fi
if [ ! -d "lib" ];then mkdir lib; fi
$(MAKE) -C $(LIBS) all
check: all
$(MAKE) -C $(LIBS) check
clean:
$(MAKE) -C $(LIBS) clean;\
rm -rf *.db *.g*
if [ -d "lib" ];then rm -rf lib; fi
if [ -d "bin" ];then rm -rf bin; fi
if [ -d "html" ];then rm -rf html; fi
if [ -d "latex" ];then rm -rf latex; fi
doc:
doxygen Doxyfile
<file_sep>/Projet-Jeu/src/test-fonction/main-fonction-test.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <fonction-test.h>
/**
* \file main-fonction-test.c
* \brief main des fonctions de test
**/
static int nbrTest = 1;
static void display_test(char *t, bool valide);
int main(int argc, char *argv[]){
grid g = new_grid();
display_test("new_grid", test_new_grid());
display_test("get_tile", test_get_tile(g));
display_test("set_tile", test_set_tile(g));
display_test("get_score", test_get_score_grid(g));
display_test("copy_grid", test_copy_grid(g));
display_test("game_over", test_game_over(g));
display_test("do_move_UP", test_do_move_up(g));
display_test("do_move_DOWN", test_do_move_down(g));
display_test("do_move_LEFT", test_do_move_left(g));
display_test("do_move_RIGHT", test_do_move_right(g));
display_test("do_move_ALL", test_do_move_all(g));
display_test("test_can_move", test_can_move(g));
display_test("test_add_tile", test_add_tile(g));
delete_grid(g);
}
static void display_test(char *t, bool valide){
printf("[TEST ");
printf("%d]", nbrTest);
int i = 0;
if(nbrTest < 10)
printf(" ");
printf(" - ");
while(t[i] != '\0'){
printf("%c", t[i]);
i++;
}
printf(" ");
i++;
while(i < 70){
printf(".");
i++;
}
nbrTest++;
printf(valide ? " [\033[32;7m SUCCED \033[0m]" : " [\033[31;7m FAILED \033[0m]");
printf("\n");
}
<file_sep>/Projet-Jeu/src/strategy/Makefile
CC = gcc
CFLAGS = -std=c99 -g -Wall -fPIC -I../../include
LDLIBS = -lA2_emery_gouraud_kirov_pouteau_fast -lA2_emery_gouraud_kirov_pouteau_low -lgridNcurses -lgrid -lgcov -lm -lncurses -L ../../lib/
CPPFLAGS=
PATH_INCLUDe=../../include
PATH_LIB= ../../lib
PATH_BIN= ../../bin
all: $(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_fast.a $(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_low.a $(PATH_BIN)/IA-graphique-fast $(PATH_BIN)/IA-repetition-fast $(PATH_BIN)/IA-graphique-low $(PATH_BIN)/IA-repetition-low
$(PATH_BIN)/IA-graphique-fast: main-graphique-fast.o $(PATH_LIB)/*
$(CC) -o $(PATH_BIN)/IA-graphique-fast main-graphique-fast.o $(LDLIBS)
$(PATH_BIN)/IA-repetition-fast: main-repetition-fast.o $(PATH_LIB)/*
$(CC) -o $(PATH_BIN)/IA-repetition-fast main-repetition-fast.o $(LDLIBS)
$(PATH_BIN)/IA-graphique-low: main-graphique-low.o $(PATH_LIB)/*
$(CC) -o $(PATH_BIN)/IA-graphique-low main-graphique-low.o $(LDLIBS)
$(PATH_BIN)/IA-repetition-low: main-repetition-low.o $(PATH_LIB)/*
$(CC) -o $(PATH_BIN)/IA-repetition-low main-repetition-low.o $(LDLIBS)
install:$(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_fast.a $(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_low.a
$(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_fast.a: A2_emery_gouraud_kirov_pouteau_fast.o
ar -cr $(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_fast.a A2_emery_gouraud_kirov_pouteau_fast.o
$(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_low.a: A2_emery_gouraud_kirov_pouteau_low.o
ar -cr $(PATH_LIB)/libA2_emery_gouraud_kirov_pouteau_low.a A2_emery_gouraud_kirov_pouteau_low.o
include dep
.PHONY: clean
clean:
rm -f dep *.o *~ *.g*
dep:
$(CC) $(CPPFLAGS) -MM *.c > dep
<file_sep>/Projet-Jeu/src/test-fonction/Makefile
CC = gcc
CFLAGS = -std=c99 --coverage -g -Wall -I../../include
LDLIBS = -lgrid -lgcov -lm -L ../../lib/
CPPFLAGS =
EXEC =test-fonction
PATH_LIB=../../lib
PATH_INCLUDE=../../include
all: test-fonction
test-fonction: main-fonction-test.o ./fonction-test.o $(PATH_LIB)/*
${CC} ${CFLAGS} -o test-fonction main-fonction-test.o ./fonction-test.o $(LDLIBS)
install:
include dep
dep:
$(CC) $(CPPFLAGS) -MM *.c >dep
check: all
valgrind ./test-fonction
gcov main-fonction-test.c
gcov fonction-test.c
gcov ../grid/grid.c
.PHONY: clean
clean:
rm -rf dep *~ *.o test-fonction *.out *.g*
<file_sep>/Projet-Jeu/include/fonction-test.h
#ifndef _FONCTION_TEST_H_
#define _FONCTION_TEST_H_
/**
* \file fonction-test.h
* \brief Contient les tests des fonctions du fichier grid.h
**/
#include <stdbool.h>
#include <grid.h>
extern bool test_new_grid();
/**
* \brief Verifie que la valeur retourne par get_tile est la bonne
* \param g Une grille pour faire le test
* \return true si les valeurs correspondent false sinon
**/
extern bool test_get_tile(grid g);
/**
* \brief Verifie si set_tile modifie correctement la valeur de la tile
* \param g Une grille pour faire le test
* \return true si la valeur est correctement modifiee, false sinon
**/
extern bool test_set_tile(grid g);
/**
* \brief Verifie que la grille copie correspond a la grille passee en parametre
* \param g Une grille pour faire le test
* \return true si la grille copiee correspond a la grille passee en parametre, false sinon
**/
extern bool test_copy_grid(grid g);
/**
* \brief Verifie que get_score_grid renvoi le bon score correspondant a la grille passee en parametre
* \param g Une grille pour faire le test
* \return true si le score correspond, false sinon
**/
extern bool test_get_score_grid(grid g);
/**
* \brief Verifie que que l'on obtient game_over si il n'y a ni case vide ni fusion possible
* \param g Une grille pour faire le test
* \return true si on obtient game_over, false sinon
**/
extern bool test_game_over(grid g);
/**
* \brief Verifie que le mouvement vers le haut fonctionne correctement
* \param g Une grille pour faire le test
* \return true si apres le mouvement on obtient la grille souhaitait, false sinon
**/
extern bool test_do_move_up(grid g);
/**
* \brief Verifie que le mouvement vers le bas fonctionne correctement
* \param g Une grille pour faire le test
* \return true si apres le mouvement on obtient la grille souhaitait, false sinon
**/
extern bool test_do_move_down(grid g);
/**
* \brief Verifie que le mouvement vers la gauche fonctionne correctement
* \param g Une grille pour faire le test
* \return true si apres le mouvement on obtient la grille souhaitait, false sinon
**/
extern bool test_do_move_left(grid g);
/**
* \brief Verifie que le mouvement vers la droite fonctionne correctement
* \param g Une grille pour faire le test
* \return true si apres le mouvement on obtient la grille souhaitait, false sinon
**/
extern bool test_do_move_right(grid g);
/**
* \brief Verifie que tous les mouvements les uns apres les autres fonctionnent correctement
* \param g Une grille pour faire le test
* \return true si apres les mouvement on obtient la grille souhaitait, false sinon
**/
extern bool test_do_move_all(grid g);
/**
* \brief Verifie que can_move fonctionne
* \param g Une grille pour faire le test
* \return true si un mouvement est possible et can_move renvoi true et false si aucun mouvement possible et can_move renvoi false
**/
extern bool test_can_move(grid g);
/**
* \brief Verifie que add_tile ajoute des tiles sur toutes la grille avec une probalite de 1/10 pour un 4
* \param g Une grille pour faire le test
* \return true si la grille est rempli en GRID_SIDE*GRID_SIDE ajout et la probalite de 4 est bonne, false sinon
**/
extern bool test_add_tile(grid g);
/**
* \brief Verifie que le mouvement vers le haut fonctionne correctement
* \param g Une grille pour faire le test
* \return true si apres mouvement on obtient la grille souhaitait, false sinon
**/
#endif
<file_sep>/Projet-Jeu/src/strategy/main-repetition-fast.c
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <grid.h>
#include <strategy.h>
#include <math.h>
#define NOMBRE_TEST 1
/**
* \file main-repetition-fast.c
* \brief fait jouer n fois l'IA Rapide
*/
/**
* \brief Strategie utilisé
* \return stretegy
*/
strategy A2_emery_gouraud_kirov_pouteau_fast();
/**
* \brief recupere le maximum
* \return long
*/
static long maximum_tile(grid g){
long max_tile = 1;
for(int i = 0; i<GRID_SIDE; i++){
for(int j = 0; j< GRID_SIDE; j++){
if(get_tile(g, i, j)>max_tile)
max_tile = get_tile(g, i, j);
}
}
return max_tile;
}
/**
* \brief fonction d'usage erreur si mauvais appel de l'executable
* \return
*/
static void usage(char * commande){
fprintf(stderr,"%s <nombre repetition > \n", commande);
exit(EXIT_FAILURE);
}
int main (int argc, char **argv){
if (argc != 2)
usage(argv[0]);
int n = atoi(argv[1]);
int nb_lance = n;
int cpt_16 = 0;
int cpt_32 = 0;
int cpt_64 = 0;
int cpt_128 = 0;
int cpt_256 = 0;
int cpt_512 = 0;
int cpt_1024 = 0;
int cpt_2048 = 0;
int cpt_4096 = 0;
int cpt_8192= 0;
srand(time(NULL));
strategy str = A2_emery_gouraud_kirov_pouteau_fast();
while(n > 0){
grid g = new_grid();
add_tile(g);
add_tile(g);
while(!game_over(g)){
dir d = str->play_move(str,g);
if (can_move(g,d))
play(g, d);
}
printf("max %lu\n",(long int)pow(2,maximum_tile(g)));
if(maximum_tile(g) == 4)
cpt_16 += 1;
if(maximum_tile(g) == 5)
cpt_32 += 1;
if(maximum_tile(g) == 6)
cpt_64 += 1;
if(maximum_tile(g) == 7)
cpt_128 += 1;
if(maximum_tile(g) == 8)
cpt_256 += 1;
if(maximum_tile(g) == 9)
cpt_512 += 1;
if(maximum_tile(g) == 10)
cpt_1024 += 1;
if(maximum_tile(g) == 11)
cpt_2048 += 1;
if(maximum_tile(g) == 12)
cpt_4096 += 1;
if(maximum_tile(g) == 13)
cpt_8192 += 1;
delete_grid(g);
n -= 1;
}
str->free_strategy(str);
printf("\n --------------- \n");
printf("Sur %d lancés : \n\n", nb_lance);
printf("Nombre de fois 16 : %d\n", cpt_16);
printf("Nombre de fois 32 : %d\n", cpt_32);
printf("Nombre de fois 64 : %d\n", cpt_64);
printf("Nombre de fois 128 : %d\n", cpt_128);
printf("Nombre de fois 256 : %d\n", cpt_256);
printf("Nombre de fois 512 : %d\n", cpt_512);
printf("Nombre de fois 1024 : %d\n", cpt_1024);
printf("Nombre de fois 2048 : %d\n", cpt_2048);
printf("Nombre de fois 4096 : %d\n", cpt_4096);
printf("Nombre de fois 8192 : %d\n", cpt_8192);
}
|
2504b621ef3c0680320b5befe67e0e7605b3c24a
|
[
"Markdown",
"C",
"Makefile"
] | 21 |
Markdown
|
sebpouteau/2048
|
bce90b8caa8e0b8eb9363c595a0ac873efdd5ae0
|
3df72a4368e6df60b622a738bce95f0a8e4c1d79
|
refs/heads/master
|
<repo_name>hackwind/Tools<file_sep>/src/com/hjs/tools/ppt/PPT2Image.java
package com.hjs.tools.ppt;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape;
import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide;
/**
* 根据PPT生成一张预览图
* @author Administrator
*
*/
public class PPT2Image {
/**
* 以下类方法中实现了将 2007和 2003的字体都转为宋体,防止中文出现乱码问题,源代码如下:
类中的方法未判断 ppt的内容为空的时候,这个需要添加判断,
*/
private static Integer imgWidth=728;//默认宽度
private static Integer imgHeight=409;//默认高度
private static Integer padding = 20;//左右两边还有顶部底部间距
private static Integer PIC_NUMBER = 2;//除了第一张图是全图,下面每行并列图片数
private static Integer W_PADDING = 0;//图片直接间距
public static void main(String[] args) {
try {
createPPTImage(new FileInputStream(new File("E:\\PPT\\PPT模板.pptx")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void createPPTImage(InputStream in){
// try {
if(!in.markSupported()){
in=new BufferedInputStream(in);
}
if(in.markSupported()){
in=new PushbackInputStream(in,8);
}
// if(POIFSFileSystem.hasPOIFSHeader(in)){//2003
// create2003PPTImage(in);
// }else { //if(POIXMLDocument.hasOOXMLHeader(in)){//2007
create2007PPTImage(in);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
}
public static void create2007PPTImage(InputStream in){
try {
XMLSlideShow xmlSlideShow=new XMLSlideShow(in);
List<XSLFSlide> slides=xmlSlideShow.getSlides();
Dimension dim = xmlSlideShow.getPageSize();
imgWidth = dim.width;
imgHeight = dim.height;
BufferedImage img=new BufferedImage(imgWidth + padding * 2,
(int)(Math.ceil((slides.size() - 1) / (float)PIC_NUMBER)) * (imgHeight / PIC_NUMBER) //非第一张图片都是1/4尺寸
+ imgHeight + padding * 2, //第一张图片是全尺寸
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics=img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setPaint(Color.WHITE);
graphics.fillRect(0, 0, img.getWidth(), img.getHeight());
int i = 0;
int height = 0;
for(XSLFSlide slide : slides) {
//设置字体为宋体,解决中文乱码问题
CTSlide rawSlide=slide.getXmlObject();
CTGroupShape gs = rawSlide.getCSld().getSpTree();
CTShape[] shapes = gs.getSpArray();
for (CTShape shape : shapes) {
CTTextBody tb = shape.getTxBody();
if (null == tb)
continue;
CTTextParagraph[] paras = tb.getPArray();
CTTextFont font=CTTextFont.Factory.parse(
"<xml-fragment xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\">"+
"<a:rPr lang=\"zh-CN\" altLang=\"en-US\" dirty=\"0\" smtClean=\"0\"> "+
"<a:latin typeface=\"+mj-ea\"/> "+
"</a:rPr>"+
"</xml-fragment>");
for (CTTextParagraph textParagraph : paras) {
CTRegularTextRun[] textRuns = textParagraph.getRArray();
for (CTRegularTextRun textRun : textRuns) {
CTTextCharacterProperties properties=textRun.getRPr();
properties.setLatin(font);
}
}
}
System.out.println(i);
int mod = i % PIC_NUMBER;
if(i == 0) {
Image image = createSubImage(imgWidth,imgHeight,slide);
graphics.drawImage(image,padding, padding, imgWidth, imgHeight, null);
System.out.println("left:" + padding + ",top:" + padding + ",right:" + imgWidth + ",bottom:" + imgHeight);
height += imgHeight + padding;
} else if(mod == 0){//最右
Image image = createSubImage(imgWidth,imgHeight,slide);
graphics.drawImage(image,(PIC_NUMBER - 1) * imgWidth / PIC_NUMBER + W_PADDING * (PIC_NUMBER - 1) + padding, height + W_PADDING, imgWidth / PIC_NUMBER, imgHeight / PIC_NUMBER, null);
System.out.println("left:" + ((PIC_NUMBER - 1) * imgWidth / PIC_NUMBER + W_PADDING * (PIC_NUMBER - 1) + padding) + ",top:" + (height + W_PADDING) + ",right:" + imgWidth / PIC_NUMBER + ",bottom:" + imgHeight / PIC_NUMBER);
height += imgHeight / PIC_NUMBER;
} else if(mod < PIC_NUMBER) {//左
Image image = createSubImage(imgWidth,imgHeight,slide);
graphics.drawImage(image,(mod - 1) * imgWidth / PIC_NUMBER + W_PADDING * (mod - 1) + padding, height + W_PADDING , imgWidth / PIC_NUMBER, imgHeight / PIC_NUMBER, null);
System.out.println("left:" + ((mod - 1) * imgWidth / PIC_NUMBER + W_PADDING * (mod - 1) + padding) + ",top:" + (height + W_PADDING) + ",right:" + imgWidth / PIC_NUMBER + ",bottom:" + imgHeight / PIC_NUMBER);
}
i++;
}
FileOutputStream out = new FileOutputStream("E:/1.jpeg");
javax.imageio.ImageIO.write(img, "jpeg", out);
out.close();
System.out.println("生成缩略图成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
private static Image createSubImage(int width,int height,XSLFSlide slide) {
BufferedImage subImg=new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics=subImg.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setPaint(Color.WHITE);
slide.draw(graphics);
return subImg;
}
public static void create2003PPTImage(InputStream in){
// try {
// SlideShow slideShow=new SlideShow(in);
//
// List<Slide> slides=slideShow.getSlides();
// Slide slide=slides.get(0);
//
// TextRun[] textRuns=slide.getTextRuns();
// for(TextRun tr:textRuns){
// RichTextRun rt=tr.getRichTextRuns()[0];
// rt.setFontName("宋体");
// }
//
// BufferedImage img=new BufferedImage(imgWidth,imgHeight, BufferedImage.TYPE_INT_RGB);
// Graphics2D graphics=img.createGraphics();
// graphics.setPaint(Color.WHITE);
// graphics.fill(new Rectangle2D.Float(0, 0, imgWidth, imgHeight));
// slide.draw(graphics);
//
// FileOutputStream out = new FileOutputStream("E:/1.jpeg");
// javax.imageio.ImageIO.write(img, "jpeg", out);
// out.close();
//
// System.out.println("缩略图成功!");
// } catch (Exception e) {
// e.printStackTrace();
// }
}
}
|
ef8fc4d6e3db7a00e6a5e3abf6b1c38528f2a03f
|
[
"Java"
] | 1 |
Java
|
hackwind/Tools
|
f45d2d51d8c1148dde3e02d05640240d28f1adb3
|
208161767c656dedc0b6256088d3a3564b356c1d
|
refs/heads/master
|
<file_sep># Hot-Restaurant
## Step One (Clone the Repository) ##
```
git clone https://github.com/Jernical/Hot-Restaurant.git
```
## Step Two (Install Packages!) ##
```
npm install
```
## Step Three (Run Server) ##
Open git in the repo and do ``node server.js``
## Step Four (Go to localhost) ##
Open any browser and type in http://localhost:3100/
<file_sep>var tableArray = [
{
customerName: "<NAME>",
customerEmail: "<EMAIL>",
customerID: "JohnSmith98",
phoneNumber: "000-000-0000"
}
];
module.exports = tableArray;<file_sep>var waitingArray = [
{
customerName: "God",
customerEmail: "<EMAIL>",
phoneNumber: "000-000-0000",
customerID: "Omnipotent"
}
];
module.exports = waitingArray;
|
a17331c560eba07996fcf23e0ff182c11080bb1a
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
Jernical/Hot-Restaurant
|
91ac469c74229b9c691cba675f065ac3958fe466
|
11b8d2b1584d05aa4e14610dfb58b54ffef900af
|
refs/heads/main
|
<file_sep>package tads.eaj.ufrn.projeto;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ProjetoApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>package tads.eaj.ufrn.projeto.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import tads.eaj.ufrn.projeto.model.Programacao;
public interface ProgramacaoRepository extends JpaRepository<Programacao, Long> {
}<file_sep>package tads.eaj.ufrn.projeto.dto.request;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tads.eaj.ufrn.projeto.model.Sala;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class SalaRequest {
private Long id;
private String nome;
private int acentos;
private Boolean is3D;
public Sala build(){
return new Sala()
.setId(this.id)
.setNome(this.nome)
.setAcentos(this.acentos)
.setIs3D(this.is3D);
}
}
<file_sep>package tads.eaj.ufrn.projeto.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tads.eaj.ufrn.projeto.dto.request.SalaRequest;
import tads.eaj.ufrn.projeto.dto.response.SalaResponse;
import tads.eaj.ufrn.projeto.model.Sala;
import tads.eaj.ufrn.projeto.service.SalaService;
import java.net.URI;
import java.util.Optional;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
@Controller
@RequestMapping(value = "/sala")
public class SalaController {
SalaService salaService;
@Autowired
public void setSalaService(SalaService salaService) {
this.salaService = salaService;
}
@PostMapping
public ResponseEntity inserir (@RequestBody SalaRequest salaRequest){
Sala sala = salaRequest.build();
sala = salaService.inserir(sala);
return ResponseEntity.created(URI.create("/sala/"+sala.getId())).body(new SalaResponse(sala));
}
@GetMapping
public ResponseEntity listar(){
return ResponseEntity.ok().body(salaService.listar());
}
@GetMapping(value = "/{id}")
public ResponseEntity buscar(@PathVariable Long id){
Optional<Sala> sala = salaService.buscar(id);
if (sala.isPresent()){
return ResponseEntity.ok().body(new SalaResponse(sala.get()));
}
else{
return ResponseEntity.notFound().build();
}
}
@PutMapping(value = "/editar/{id}")
public ResponseEntity editar (@RequestBody Sala sala, @PathVariable Long id){
Optional<Sala> c = salaService.buscar(id);
if(c.isPresent() && c.get().getId().equals(id) && sala.getId().equals(id))
return ResponseEntity.ok().body(new SalaResponse(salaService.editar(sala)));
else
return ResponseEntity.notFound().build();
}
@DeleteMapping(value = "/deletar/{id}")
public ResponseEntity deletar(@PathVariable Long id){
if(salaService.buscar(id).isPresent()){
salaService.deletar(id);
return ResponseEntity.ok(linkTo(SalaController.class).withRel("Listar Sessões"));
}else
return ResponseEntity.notFound().build();
}
}
<file_sep>package tads.eaj.ufrn.projeto.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import tads.eaj.ufrn.projeto.model.Sessao;
@Repository
public interface SessaoRepository extends JpaRepository<Sessao, Long> {
}
<file_sep>package tads.eaj.ufrn.projeto.dto.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tads.eaj.ufrn.projeto.dto.request.SessaoRequest;
import tads.eaj.ufrn.projeto.model.Programacao;
import tads.eaj.ufrn.projeto.model.Sessao;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ProgramacaoResponse {
private Long id;
private Date data;
private List<SessaoResponse> sessoes;
public ProgramacaoResponse(Programacao p){
if(p != null){
this.id = p.getId();
this.data = p.getData();
ArrayList<SessaoResponse> lista = new ArrayList<>();
for(Sessao s : p.getSessoes())
lista.add(new SessaoResponse(s));
this.sessoes = lista;
}
}
}
<file_sep>package tads.eaj.ufrn.projeto.dto.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.hateoas.RepresentationModel;
import tads.eaj.ufrn.projeto.controller.FilmeController;
import tads.eaj.ufrn.projeto.model.Filme;
import tads.eaj.ufrn.projeto.model.Sessao;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class FilmeResponse extends RepresentationModel<FilmeResponse> {
private Long id;
private String titulo;
private int duracao;
private String classificacao;
private String direcao;
private int faixaEtaria;
public FilmeResponse(Filme f){
if(f != null){
this.id = f.getId();
this.titulo = f.getTitulo();
this.duracao = f.getDuracao();
this.classificacao = f.getClassificacao();
this.direcao = f.getDirecao();
this.faixaEtaria = f.getFaixaEtaria();
this.add(linkTo(FilmeController.class).slash(f.getId()).withSelfRel());
this.add(linkTo(FilmeController.class).slash("/editar/"+f.getId()).withRel("editar filme"));
this.add(linkTo(FilmeController.class).slash("/deletar/"+f.getId()).withRel("deletar filme"));
this.add(linkTo(FilmeController.class).withRel("listar filme"));
}
}
}
<file_sep>package tads.eaj.ufrn.projeto.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.util.Date;
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain = true)
public class Filme {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "titulo", nullable = false)
private String titulo;
@Column(name = "duracao", nullable = false)
private int duracao;
@Column(name = "classificacao", nullable = false)
private String classificacao;
@Column(name = "direcao", nullable = false)
private String direcao;
@Column(name = "faixaEtaria", nullable = false)
private int faixaEtaria;
@OneToOne(mappedBy = "filme", cascade = CascadeType.ALL, orphanRemoval = true)
private Sessao sessao;
}
<file_sep>spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.datasource.url=jdbc:postgresql://localhost:5432/dbcinema?serverTimezone=UTC
spring.datasource.username=postgres
spring.datasource.password=123
|
4557a307c37d775dfe68ea8c103a6564926c711b
|
[
"Java",
"INI"
] | 9 |
Java
|
ioresss/projetowebfim
|
e971c66d1fb04759544a83cd36c8ee1ed05ec860
|
89fbac3a3776c01aae4afaecc625d69b60757528
|
refs/heads/master
|
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include "igl/slice.h"
#include "igl/slice_into.h"
#include "Determinants.h"
#include "BFSlater.h"
#include "global.h"
#include "input.h"
using namespace Eigen;
BFSlater::BFSlater()
{
initDet();
initHforbs();
initBf();
}
void BFSlater::initDet()
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
if (schd.hf == "rhf" || schd.hf == "uhf") {
for (int i = 0; i < nalpha; i++)
det.setoccA(i, true);
for (int i = 0; i < nbeta; i++)
det.setoccB(i, true);
}
else {
//jailbreaking existing dets for ghf use, filling alpha orbitals first and then beta, a ghf det wrapper maybe cleaner
int nelec = nalpha + nbeta;
if (nelec <= norbs) {
for (int i = 0; i < nelec; i++)
det.setoccA(i, true);
}
else {
for (int i = 0; i < norbs; i++)
det.setoccA(i, true);
for (int i = 0; i < nelec-norbs; i++)
det.setoccB(i, true);
}
}
}
void BFSlater::initHforbs()
{
int norbs = Determinant::norbs;
int size; //dimension of the mo coeff matrix
//initialize hftype and hforbs
if (schd.hf == "uhf") {
hftype = HartreeFock::UnRestricted;
MatrixXcd Hforbs = MatrixXcd::Zero(norbs, 2*norbs);
readMat(Hforbs, "hf.txt");
if (schd.ifComplex && Hforbs.imag().isZero(0)) Hforbs.imag() = 0.01 * MatrixXd::Random(norbs, 2*norbs);
HforbsA = Hforbs.block(0, 0, norbs, norbs);
HforbsB = Hforbs.block(0, norbs, norbs, norbs);
}
else {
if (schd.hf == "rhf") {
hftype = HartreeFock::Restricted;
size = norbs;
}
else if (schd.hf == "ghf") {
hftype = HartreeFock::Generalized;
size = 2*norbs;
}
MatrixXcd Hforbs = MatrixXcd::Zero(size, size);
readMat(Hforbs, "hf.txt");
if (schd.ifComplex && Hforbs.imag().isZero(0)) Hforbs.imag() = 0.01 * MatrixXd::Random(size, size);
HforbsA = Hforbs;
HforbsB = Hforbs;
}
}
void BFSlater::initBf() {
int norbs = Determinant::norbs;
bf = MatrixXd::Random(norbs, norbs);
bool readBf = false;
char file[5000];
sprintf(file, "bf.txt");
ifstream ofile(file);
if (ofile)
readBf = true;
if (readBf) {
for (int i = 0; i < bf.rows(); i++) {
for (int j = 0; j < bf.rows(); j++){
ofile >> bf(i, j);
}
}
}
}
void BFSlater::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
int norbs = Determinant::norbs;
int numHfVars = 0;
if (hftype == Generalized) {
for (int i = 0; i < 2*norbs; i++) {
for (int j = 0; j < 2*norbs; j++) {
v[4 * i * norbs + 2 * j] = HforbsA(i, j).real();
v[4 * i * norbs + 2 * j + 1] = HforbsA(i, j).imag();
}
}
numHfVars = 2 * HforbsA.rows() * HforbsA.rows();
}
else if (hftype == Restricted) {
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
v[2 * i * norbs + 2 * j] = HforbsA(i, j).real();
v[2 * i * norbs + 2 * j + 1] = HforbsA(i, j).imag();
}
}
numHfVars = 2 * HforbsA.rows() * HforbsA.rows();
}
else {
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
v[2 * i * norbs + 2 * j] = HforbsA(i, j).real();
v[2 * i * norbs + 2 * j + 1] = HforbsA(i, j).imag();
v[2 * norbs * norbs + 2 * i * norbs + 2 * j] = HforbsB(i, j).real();
v[2 * norbs * norbs + 2 * i * norbs + 2 * j + 1] = HforbsB(i, j).imag();
}
}
numHfVars = 4 * HforbsA.rows() * HforbsA.rows();
}
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
v[numHfVars + i * norbs + j] = bf(i, j);
}
}
}
long BFSlater::getNumVariables() const
{
long numVars = 0;
if (hftype == UnRestricted)
numVars += 4 * HforbsA.rows() * HforbsA.rows();
else
numVars += 2 * HforbsA.rows() * HforbsA.rows();
numvars += norbs * norbs;
return numVars;
}
void BFSlater::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
int norbs = Determinant::norbs;
int numHfVars = 0;
if (hftype == Generalized) {
for (int i = 0; i < 2*norbs; i++) {
for (int j = 0; j < 2*norbs; j++) {
HforbsA(i, j) = std::complex<double>(v[4 * i * norbs + 2 * j], v[4 * i * norbs + 2 * j + 1]);
HforbsB(i, j) = HforbsA(i, j);
}
}
numHfVars = 2 * HforbsA.rows() * HforbsA.rows();
}
else if (hftype == Restricted) {
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
HforbsA(i, j) = std::complex<double>(v[2 * i * norbs + 2 * j], v[2 * i * norbs + 2 * j + 1]);
HforbsB(i, j) = HforbsA(i, j);
}
}
numHfVars = 2 * HforbsA.rows() * HforbsA.rows();
}
else {
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
HforbsA(i, j) = std::complex<double>(v[2 * i * norbs + 2 * j], v[2 * i * norbs + 2 * j + 1]);
HforbsB(i, j) = std::complex<double>(v[2 * norbs * norbs + 2 * i * norbs + 2 * j], v[2 * norbs * norbs + 2 * i * norbs + 2 * j + 1]);
}
}
numHfVars = 4 * HforbsA.rows() * HforbsA.rows();
}
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
bf(i, j) = v[numHfVars + i * norbs + j];
}
}
}
void BFSlater::printVariables() const
{
cout << endl<<"DeterminantA"<<endl;
//for r/ghf
for (int i = 0; i < HforbsA.rows(); i++) {
for (int j = 0; j < HforbsA.rows(); j++)
cout << " " << HforbsA(i, j);
cout << endl;
}
if (hftype == UnRestricted) {
//if (hftype == 1) {
cout << endl
<< "DeterminantB" << endl;
for (int i = 0; i < HforbsB.rows(); i++) {
for (int j = 0; j < HforbsB.rows(); j++)
cout << " " << HforbsB(i, j);
cout << endl;
}
}
cout << "bf\n" << bf << endl;
cout << endl;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <random>
#include <chrono>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Core>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
//#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include "evaluatePT.h"
#include "MoDeterminants.h"
#include "Determinants.h"
#include "Correlator.h"
#include "Wfn.h"
#include "input.h"
#include "integral.h"
#include "SHCIshm.h"
#include "math.h"
using namespace Eigen;
using namespace boost;
using namespace std;
int main(int argc, char* argv[]) {
#ifndef SERIAL
boost::mpi::environment env(argc, argv);
boost::mpi::communicator world;
#endif
startofCalc = getTime();
initSHM();
license();
string inputFile = "input.dat";
if (argc > 1)
inputFile = string(argv[1]);
if (commrank == 0) readInput(inputFile, schd);
#ifndef SERIAL
mpi::broadcast(world, schd, 0);
#endif
generator = std::mt19937(schd.seed+commrank);
twoInt I2; oneInt I1;
int norbs, nalpha, nbeta;
double coreE=0.0;
std::vector<int> irrep;
readIntegrals("FCIDUMP", I2, I1, nalpha, nbeta, norbs, coreE, irrep);
//initialize the heatbath integrals
std::vector<int> allorbs;
for (int i=0; i<norbs; i++)
allorbs.push_back(i);
twoIntHeatBath I2HB(1.e-10);
twoIntHeatBathSHM I2HBSHM(1.e-10);
if (commrank == 0) I2HB.constructClass(allorbs, I2, I1, norbs);
I2HBSHM.constructClass(norbs, I2HB);
//Setup static variables
Determinant::EffDetLen = (norbs)/64+1;
Determinant::norbs = norbs;
MoDeterminant::norbs = norbs;
MoDeterminant::nalpha = nalpha;
MoDeterminant::nbeta = nbeta;
//Setup Slater Determinants
HforbsA = MatrixXd::Zero(norbs, norbs);
HforbsB = MatrixXd::Zero(norbs, norbs);
readHF(HforbsA, HforbsB, schd.uhf);
//Setup CPS wavefunctions
std::vector<Correlator> nSiteCPS;
for (auto it = schd.correlatorFiles.begin(); it != schd.correlatorFiles.end();
it++) {
readCorrelator(it->second, it->first, nSiteCPS);
}
vector<Determinant> detList; vector<double> ciExpansion;
if (boost::iequals(schd.determinantFile, "") )
{
detList.resize(1); ciExpansion.resize(1, 1.0);
for (int i=0; i<nalpha; i++)
detList[0].setoccA(i, true);
for (int i=0; i<nbeta; i++)
detList[0].setoccB(i, true);
}
else
{
readDeterminants(schd.determinantFile, detList, ciExpansion);
}
//setup up wavefunction
CPSSlater wave(nSiteCPS, detList, ciExpansion);
size_t size;
ifstream file ("params.bin", ios::in|ios::binary|ios::ate);
if (commrank == 0) {
size = file.tellg();
}
#ifndef SERIAL
MPI_Bcast(&size, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
Eigen::VectorXd vars = Eigen::VectorXd::Zero(size/sizeof(double));
if (commrank == 0) {
file.seekg (0, ios::beg);
file.read ( (char*)(&vars[0]), size);
file.close();
}
#ifndef SERIAL
MPI_Bcast(&vars[0], vars.rows(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if ( (schd.uhf && vars.size() != wave.getNumVariables()+2*norbs*norbs) ||
(!schd.uhf && vars.size() != wave.getNumVariables()+norbs*norbs) ){
cout << "number of variables on disk: "<<vars.size()<<" is not equal to wfn parameters: "<<wave.getNumVariables()<<endl;
exit(0);
}
wave.updateVariables(vars);
int numVars = wave.getNumVariables();
for (int i=0; i<norbs; i++) {
for (int j=0; j<norbs; j++) {
if (!schd.uhf) {
HforbsA(i,j) = vars[numVars + i *norbs + j];
HforbsB(i,j) = vars[numVars + i *norbs + j];
}
else {
HforbsA(i,j) = vars[numVars + i *norbs + j];
HforbsB(i,j) = vars[numVars + norbs*norbs + i *norbs + j];
}
}
}
MatrixXd alpha(norbs, nalpha), beta(norbs, nbeta);
alpha = HforbsA.block(0, 0, norbs, nalpha);
beta = HforbsB.block(0, 0, norbs, nbeta );
MoDeterminant det(alpha, beta);
/*
if (schd.deterministic) {
double scaledE0 = evaluateScaledEDeterministic(wave, lambda, unscaledE,
nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE);
if (commrank == 0) cout << format("%14.8f (%8.2e) , E(lambda) = %14.8f\n")
%(unscaledE) % (stddev) %(scaledE0);
//double PT = evaluatePTDeterministic(wave, scaledE0, nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE);
//double PT = evaluatePTDeterministicC(wave, scaledE0, nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE);
double PT = evaluatePTDeterministicD(wave, scaledE0, nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE);
if (commrank == 0) cout << format("%14.8f (%8.2e) \n") %(unscaledE+PT) % (stddev);
}
else {
//double scaledE0 = evaluateScaledEStochastic(wave, lambda, unscaledE,
//nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE,
//stddev, schd.stochasticIter);
double scaledE0 = evaluateScaledEDeterministic(wave, lambda, unscaledE,
nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE);
//double scaledE0 = -74.65542308;
if (commrank == 0) cout << format("%14.8f (%8.2e) , E(lambda) = %14.8f\n")
%(unscaledE) % (stddev) %(scaledE0);
double A2, B, C, A3;
double stddevA, stddevB, stddevC;
double PT;
/*
{
PT = evaluatePTStochasticMethodD(wave, scaledE0, nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE, stddevA, stddevB, stddevC, schd.stochasticIter, A2, B, C);
if (commrank == 0) cout <<format("%14.8f (%6.2e) %14.8f (%6.2e) %14.8f (%6.2e) %14.8f\n")
%(A2) %(stddevA) %B %stddevB %C %stddevC %(A2/B);
}
/
{
double PT = evaluatePTStochasticMethodC(wave, scaledE0, nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE, stddevA, stddevB, stddevC, schd.stochasticIter, A2, B, C);
//double PT = evaluatePTStochastic3rdOrder(wave, scaledE0, nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE, stddev, schd.stochasticIter, A2, B, C, A3);
//double PT = evaluatePTStochasticMethodA(wave, scaledE0, nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE, stddevA, schd.stochasticIter, A2, B, C);
if (commrank == 0) cout <<format("%14.8f (%6.2e) %14.8f (%6.2e) %14.8f (%6.2e) %14.8f\n")
%(A2) %(stddevA) %B %stddevB %C %stddevC %(A2+B*B/C);
}
if (commrank == 0) cout << format("%14.8f (%8.2e) \n") %(unscaledE+PT) % (stddev);
}
}
else {
cout << "Use the python script to optimize the wavefunction."<<endl;
exit(0);
}
*/
Eigen::VectorXd grad = Eigen::VectorXd::Zero(vars.size());
double unscaledE, stddev, rk;
/*
double scaledE0 = evaluateScaledEDeterministic(wave, schd.PTlambda, unscaledE,
nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE);
double PTdet = evaluatePTDeterministic(wave, scaledE0,
nalpha, nbeta, norbs, I1, I2, I2HBSHM, coreE);
*/
//if (commrank == 0) cout << scaledE0<<" "<<unscaledE<<" "<<PTdet<<endl;
double scaledE = evaluateScaledEStochastic(wave, schd.PTlambda, unscaledE, nalpha, nbeta, norbs,
I1, I2, I2HBSHM, coreE, stddev, rk,
schd.stochasticIter, 0.5e-3);
double A, B, C, stddev2;
double PTstoc = evaluatePTStochasticMethodB(wave, unscaledE, nalpha, nbeta, norbs,
I1, I2, I2HBSHM, coreE, stddev2, rk,
schd.stochasticIter, A, B, C);
if (commrank == 0) cout << PTstoc<<" "<<stddev2<<endl;
if (commrank == 0) {
std::cout << format("%14.8f (%8.2e) %14.8f (%8.2e) %10.2f %10i %8.2f\n")
%unscaledE % stddev %(unscaledE+A+B*B/C) %stddev2 %rk %(schd.stochasticIter) %( (getTime()-startofCalc));
}
boost::interprocess::shared_memory_object::remove(shciint2.c_str());
boost::interprocess::shared_memory_object::remove(shciint2shm.c_str());
return 0;
}
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
#include "CxNumpyArray.h"
#include "CxMemoryStack.h"
#include "BlockContract.h"
#include "CxDefs.h"
#include "icpt.h"
#include "mkl.h"
#include "mkl_cblas.h"
using ct::TArray;
using ct::FMemoryStack;
using boost::format;
int main(int argc, char const *argv[])
{
// what we need:
// - CI order, nElec, Ms2 (-> nOccA, nOccB)
// - tensor declarations
// - equations (read from .inl files)
// - E0/Fock/Int2e (take from numpy arrays).
// Assume input is already in MO basis.
// - something to split up tensors (H) and combine them (RDM)
// regarding universal indices
mkl_set_num_threads(numthrds);
FJobContext
Job;
char const
*pInp = "CoMinAo.args";
std::string
MethodOverride;
for (int iArg = 1; iArg < argc; ++ iArg) {
if (0 == strcmp(argv[iArg], "-m")) {
++ iArg;
if (iArg < argc)
MethodOverride = std::string(argv[iArg]);
continue;
}
pInp = argv[iArg];
}
Job.ReadInputFile(pInp);
if (!MethodOverride.empty())
Job.MethodName = MethodOverride;
ct::FMemoryStack2 Mem[numthrds];
size_t mb = 1048576;
Mem[0].Create(Job.WorkSpaceMb*mb);
if (Job.MethodName == "MRLCC") {
std::string methods[] = {"MRLCC_CCVV", "MRLCC_ACVV", "MRLCC_AAVV", "MRLCC_CCAA", "MRLCC_CCAV", "MRLCC_CAAV"};
for (int i=0; i<6; i++) {
Job.MethodName = methods[i];
Job.Run(Mem);
Job.DeleteData(Mem[0]);
}
}
else if (Job.MethodName == "NEVPT2") {
//std::string methods[] = {"NEVPT2_CCVV", "NEVPT2_ACVV", "NEVPT2_AAVV", "NEVPT2_CCAA", "NEVPT2_CCAV", "NEVPT2_CAAV"};
std::string methods[] = {"NEVPT2_CCVV", "NEVPT2_ACVV", "NEVPT2_CCAV"};
for (int i=0; i<3; i++) {
Job.MethodName = methods[i];
Job.Run(Mem);
Job.DeleteData(Mem[0]);
}
}
else
Job.Run(Mem);
}
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "integral.h"
#include "input.h"
#include "string.h"
#include "global.h"
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include "math.h"
#include "boost/format.hpp"
#include <fstream>
#include "Determinants.h"
#ifndef SERIAL
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include <boost/serialization/vector.hpp>
#include "hdf5.h"
using namespace boost;
bool myfn(double i, double j) { return fabs(i)<fabs(j); }
//=============================================================================
void readIntegralsAndInitializeDeterminantStaticVariables(string fcidump) {
//-----------------------------------------------------------------------------
/*!
Read FCIDUMP file and populate "I1, I2, coreE, nelec, norbs, irrep"
:Inputs:
string fcidump:
Name of the FCIDUMP file
*/
//-----------------------------------------------------------------------------
if (H5Fis_hdf5(fcidump.c_str())) {
readIntegralsHDF5AndInitializeDeterminantStaticVariables(fcidump);
return;
}
#ifndef SERIAL
boost::mpi::communicator world;
#endif
ifstream dump(fcidump.c_str());
if (!dump.good()) {
cout << "Integral file "<<fcidump<<" does not exist!"<<endl;
exit(0);
}
vector<int> irrep;
int nelec, sz, norbs, nalpha, nbeta;
#ifndef SERIAL
if (commrank == 0) {
#endif
I2.ksym = false;
bool startScaling = false;
norbs = -1;
nelec = -1;
sz = -1;
int index = 0;
vector<string> tok;
string msg;
while(!dump.eof()) {
std::getline(dump, msg);
trim(msg);
boost::split(tok, msg, is_any_of(", \t="), token_compress_on);
if (startScaling == false && tok.size() == 1 && (boost::iequals(tok[0],"&END") || boost::iequals(tok[0], "/"))) {
startScaling = true;
index += 1;
break;
} else if(startScaling == false) {
if (boost::iequals(tok[0].substr(0,4),"&FCI")) {
if (boost::iequals(tok[1].substr(0,4), "NORB"))
norbs = atoi(tok[2].c_str());
if (boost::iequals(tok[3].substr(0,5), "NELEC"))
nelec = atoi(tok[4].c_str());
if (boost::iequals(tok[5].substr(0,5), "MS2"))
sz = atoi(tok[6].c_str());
} else if (boost::iequals(tok[0].substr(0,4),"ISYM")) {
continue;
} else if (boost::iequals(tok[0].substr(0,4),"KSYM")) {
I2.ksym = true;
} else if (boost::iequals(tok[0].substr(0,6),"ORBSYM")) {
for (int i=1;i<tok.size(); i++)
irrep.push_back(atoi(tok[i].c_str()));
} else {
for (int i=0;i<tok.size(); i++)
irrep.push_back(atoi(tok[i].c_str()));
}
index += 1;
}
} // while
if (norbs == -1 || nelec == -1 || sz == -1) {
std::cout << "could not read the norbs or nelec or MS2"<<std::endl;
exit(0);
}
nalpha = nelec/2 + sz/2;
nbeta = nelec - nalpha;
irrep.resize(norbs);
#ifndef SERIAL
} // commrank=0
mpi::broadcast(world, nalpha, 0);
mpi::broadcast(world, nbeta, 0);
mpi::broadcast(world, nelec, 0);
mpi::broadcast(world, norbs, 0);
mpi::broadcast(world, irrep, 0);
mpi::broadcast(world, I2.ksym, 0);
#endif
long npair = norbs*(norbs+1)/2;
if (I2.ksym) npair = norbs*norbs;
I2.norbs = norbs;
I2.npair = npair;
int inner = norbs;
if (schd.nciAct > 0) inner = schd.nciCore + schd.nciAct;
I2.inner = inner;
//innerDetLen = DetLen;
int virt = norbs - inner;
I2.virt = virt;
//size_t nvirtpair = virt*(virt+1)/2;
size_t nii = inner*(inner+1)/2;
size_t niv = inner*virt;
size_t nvv = virt*(virt+1)/2;
size_t niiii = nii*(nii+1)/2;
size_t niiiv = nii*niv;
size_t niviv = niv*(niv+1)/2;
size_t niivv = nii*nvv;
I2.nii = nii;
I2.niv = niv;
I2.nvv = nvv;
I2.niiii = niiii;
I2.niiiv = niiiv;
I2.niviv = niviv;
I2.niivv = niivv;
size_t I2memory = niiii + niiiv + niviv + niivv;
//size_t I2memory = npair*(npair+1)/2 - nvirtpair*(nvirtpair+1)/2; //memory in bytes
#ifndef SERIAL
world.barrier();
#endif
int2Segment.truncate((I2memory)*sizeof(double));
regionInt2 = boost::interprocess::mapped_region{int2Segment, boost::interprocess::read_write};
memset(regionInt2.get_address(), 0., (I2memory)*sizeof(double));
#ifndef SERIAL
world.barrier();
#endif
I2.store = static_cast<double*>(regionInt2.get_address());
if (commrank == 0) {
I1.store.clear();
I1.store.resize(2*norbs*(2*norbs),0.0); I1.norbs = 2*norbs;
coreE = 0.0;
vector<string> tok;
string msg;
while(!dump.eof()) {
std::getline(dump, msg);
trim(msg);
boost::split(tok, msg, is_any_of(", \t"), token_compress_on);
if (tok.size() != 5) continue;
double integral = atof(tok[0].c_str());int a=atoi(tok[1].c_str()), b=atoi(tok[2].c_str()), c=atoi(tok[3].c_str()), d=atoi(tok[4].c_str());
if(a==b&&b==c&&c==d&&d==0) {
coreE = integral;
} else if (b==c&&c==d&&d==0) {
continue;//orbital energy
} else if (c==d&&d==0) {
I1(2*(a-1),2*(b-1)) = integral; //alpha,alpha
I1(2*(a-1)+1,2*(b-1)+1) = integral; //beta,beta
I1(2*(b-1),2*(a-1)) = integral; //alpha,alpha
I1(2*(b-1)+1,2*(a-1)+1) = integral; //beta,beta
} else {
int n = 0;
if ((a-1) >= inner) n++;
if ((b-1) >= inner) n++;
if ((c-1) >= inner) n++;
if ((d-1) >= inner) n++;
if (n < 3) I2(2*(a-1),2*(b-1),2*(c-1),2*(d-1)) = integral;
}
} // while
//exit(0);
I2.maxEntry = *std::max_element(&I2.store[0], &I2.store[0]+I2memory,myfn);
I2.Direct = MatrixXd::Zero(norbs, norbs); I2.Direct *= 0.;
I2.Exchange = MatrixXd::Zero(norbs, norbs); I2.Exchange *= 0.;
for (int i=0; i<inner; i++)
for (int j=0; j<inner; j++) {
I2.Direct(i,j) = I2(2*i,2*i,2*j,2*j);
I2.Exchange(i,j) = I2(2*i,2*j,2*j,2*i);
}
} // commrank=0
#ifndef SERIAL
mpi::broadcast(world, I1, 0);
long intdim = I2memory;
long maxint = 26843540; //mpi cannot transfer more than these number of doubles
long maxIter = intdim/maxint;
world.barrier();
for (int i=0; i<maxIter; i++) {
mpi::broadcast(world, &I2.store[i*maxint], maxint, 0);
world.barrier();
}
mpi::broadcast(world, &I2.store[maxIter*maxint], I2memory - maxIter*maxint, 0);
world.barrier();
mpi::broadcast(world, I2.maxEntry, 0);
mpi::broadcast(world, I2.Direct, 0);
mpi::broadcast(world, I2.Exchange, 0);
mpi::broadcast(world, I2.zero, 0);
mpi::broadcast(world, coreE, 0);
#endif
Determinant::EffDetLen = (norbs) / 64 + 1;
Determinant::norbs = norbs;
Determinant::nalpha = nalpha;
Determinant::nbeta = nbeta;
//initialize the heatbath integrals
std::vector<int> allorbs;
std::vector<int> innerorbs;
for (int i = 0; i < norbs; i++)
allorbs.push_back(i);
for (int i = 0; i < inner; i++)
innerorbs.push_back(i);
twoIntHeatBath I2HB(1.e-10);
twoIntHeatBath I2HBCAS(1.e-10);
if (commrank == 0) {
//if (schd.nciAct > 0) I2HB.constructClass(innerorbs, I2, I1, 0, norbs);
//else I2HB.constructClass(allorbs, I2, I1, 0, norbs);
I2HB.constructClass(innerorbs, I2, I1, 0, norbs);
if (schd.nciCore > 0 || schd.nciAct > 0) I2HBCAS.constructClass(allorbs, I2, I1, schd.nciCore, schd.nciAct, true);
}
I2hb.constructClass(norbs, I2HB, 0);
if (schd.nciAct > 0 || schd.nciAct > 0) I2hbCAS.constructClass(norbs, I2HBCAS, 1);
} // end readIntegrals
//=============================================================================
void readIntegralsHDF5AndInitializeDeterminantStaticVariables(string fcidump) {
//-----------------------------------------------------------------------------
/*!
Read fcidump file and populate "I1, I2, coreE, nelec, norbs"
NB: I2 assumed to be 8-fold symmetric, irreps not implemented
:Inputs:
string fcidump:
Name of the FCIDUMP file
*/
//-----------------------------------------------------------------------------
#ifndef SERIAL
boost::mpi::communicator world;
#endif
vector<int> irrep;
int nelec, sz, norbs, nalpha, nbeta;
hid_t file = (-1), dataset_header, dataset_hcore, dataset_eri, dataset_iiii, dataset_iiiv, dataset_iviv, dataset_iivv, dataset_energy_core ; /* identifiers */
herr_t status;
#ifndef SERIAL
if (commrank == 0) {
#endif
cout << "Reading integrals\n";
norbs = -1;
nelec = -1;
sz = -1;
H5E_BEGIN_TRY {
file = H5Fopen(fcidump.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
} H5E_END_TRY
if (file < 0) {
cout << "FCIDUMP not found!" << endl;
exit(0);
}
int header[3];
header[0] = 0; //nelec
header[1] = 0; //norbs
header[2] = 0; //ms2
dataset_header = H5Dopen(file, "/header", H5P_DEFAULT);
status = H5Dread(dataset_header, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, header);
I2.ksym = false;
bool startScaling = false;
nelec = header[0]; norbs = header[1]; sz = header[2];
if (norbs == -1 || nelec == -1 || sz == -1) {
std::cout << "could not read the norbs or nelec or MS2"<<std::endl;
exit(0);
}
nalpha = nelec/2 + sz/2;
nbeta = nelec - nalpha;
irrep.resize(norbs);
#ifndef SERIAL
} // commrank=0
mpi::broadcast(world, nalpha, 0);
mpi::broadcast(world, nbeta, 0);
mpi::broadcast(world, nelec, 0);
mpi::broadcast(world, norbs, 0);
mpi::broadcast(world, irrep, 0);
mpi::broadcast(world, I2.ksym, 0);
#endif
long npair = norbs*(norbs+1)/2;
if (I2.ksym) npair = norbs*norbs;
I2.norbs = norbs;
I2.npair = npair;
int inner = norbs;
if (schd.nciAct > 0) inner = schd.nciCore + schd.nciAct;
I2.inner = inner;
//innerDetLen = DetLen;
int virt = norbs - inner;
I2.virt = virt;
//size_t nvirtpair = virt*(virt+1)/2;
size_t nii = inner*(inner+1)/2;
size_t niv = inner*virt;
size_t nvv = virt*(virt+1)/2;
size_t niiii = nii*(nii+1)/2;
size_t niiiv = nii*niv;
size_t niviv = niv*(niv+1)/2;
size_t niivv = nii*nvv;
I2.nii = nii;
I2.niv = niv;
I2.nvv = nvv;
I2.niiii = niiii;
I2.niiiv = niiiv;
I2.niviv = niviv;
I2.niivv = niivv;
size_t I2memory = niiii + niiiv + niviv + niivv;
//size_t I2memory = npair*(npair+1)/2 - nvirtpair*(nvirtpair+1)/2; //memory in bytes
#ifndef SERIAL
world.barrier();
#endif
int2Segment.truncate((I2memory)*sizeof(double));
regionInt2 = boost::interprocess::mapped_region{int2Segment, boost::interprocess::read_write};
memset(regionInt2.get_address(), 0., (I2memory)*sizeof(double));
#ifndef SERIAL
world.barrier();
#endif
I2.store = static_cast<double*>(regionInt2.get_address());
if (commrank == 0) {
I1.store.clear();
I1.store.resize(2*norbs*(2*norbs),0.0); I1.norbs = 2*norbs;
coreE = 0.0;
double *hcore = new double[norbs * norbs];
for (int i = 0; i < norbs; i++)
for (int j = 0; j < norbs; j++)
hcore[i * norbs + j] = 0.;
dataset_hcore = H5Dopen(file, "/hcore", H5P_DEFAULT);
status = H5Dread(dataset_hcore, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, hcore);
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
double integral = hcore[i * norbs + j];
I1(2*i, 2*j) = integral;
I1(2*i+1, 2*j+1) = integral;
I1(2*j, 2*i) = integral;
I1(2*j + 1, 2*i + 1) = integral;
}
}
delete [] hcore;
//assuming 8-fold symmetry
H5E_BEGIN_TRY {
dataset_eri = H5Dopen(file, "/eri", H5P_DEFAULT);
} H5E_END_TRY
if (dataset_eri > 0) {
unsigned int eri_size = npair * (npair + 1) / 2;
double *eri = new double[eri_size];
for (unsigned int i = 0; i < eri_size; i++)
eri[i] = 0.;
status = H5Dread(dataset_eri, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, eri);
unsigned int ij = 0;
unsigned int ijkl = 0;
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < i + 1; j++) {
int kl = 0;
for (int k = 0; k < i + 1; k++) {
for (int l = 0; l < k + 1; l++) {
int n = 0;
if (i >= inner) n++;
if (j >= inner) n++;
if (k >= inner) n++;
if (l >= inner) n++;
if (ij >= kl) {
if (n < 3) I2(2*i, 2*j, 2*k, 2*l) = eri[ijkl];
//I2(2*i, 2*j, 2*k, 2*l) = eri[ijkl];
ijkl++;
}
kl++;
}
}
ij++;
}
}
delete [] eri;
}
else {
dataset_iiii = H5Dopen(file, "/iiii", H5P_DEFAULT);
double *iiii = new double[niiii];
for (unsigned int i = 0; i < niiii; i++)
iiii[i] = 0.;
status = H5Dread(dataset_iiii, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, iiii);
unsigned int ij = 0;
unsigned int ijkl = 0;
for (int i = 0; i < inner; i++) {
for (int j = 0; j < i + 1; j++) {
int kl = 0;
for (int k = 0; k < i + 1; k++) {
for (int l = 0; l < k + 1; l++) {
if (ij >= kl) {
I2(2*i, 2*j, 2*k, 2*l) = iiii[ijkl];
//I2(2*i, 2*j, 2*k, 2*l) = eri[ijkl];
ijkl++;
}
kl++;
}
}
ij++;
}
}
delete [] iiii;
dataset_iiiv = H5Dopen(file, "/iiiv", H5P_DEFAULT);
double *iiiv = new double[niiiv];
for (size_t i = 0; i < niiiv; i++)
iiiv[i] = 0.;
status = H5Dread(dataset_iiiv, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, iiiv);
for (size_t iv = 0; iv < niv; iv++) {
size_t i = iv / inner + inner;
size_t j = iv % inner;
for (size_t k = 0; k < inner; k++) {
for (size_t l = 0; l <= k; l++) {
size_t ii = k*(k+1)/2 + l;
I2(2*i, 2*j, 2*k, 2*l) = iiiv[iv*nii + ii];
}
}
}
delete [] iiiv;
dataset_iivv = H5Dopen(file, "/iivv", H5P_DEFAULT);
double *iivv = new double[niivv];
for (size_t i = 0; i < niivv; i++)
iivv[i] = 0.;
status = H5Dread(dataset_iivv, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, iivv);
for (size_t i = inner; i < norbs; i++) {
for (size_t j = inner; j <= i; j++) {
size_t vv = (i-inner) * (i-inner+1) / 2 + (j-inner);
for (size_t k = 0; k < inner; k++) {
for (size_t l = 0; l <= k; l++) {
size_t ii = k*(k+1)/2 + l;
I2(2*i, 2*j, 2*k, 2*l) = iivv[vv*nii + ii];
}
}
}
}
delete [] iivv;
dataset_iviv = H5Dopen(file, "/iviv", H5P_DEFAULT);
double *iviv = new double[niviv];
for (size_t i = 0; i < niviv; i++)
iviv[i] = 0.;
status = H5Dread(dataset_iviv, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, iviv);
for (size_t iv1 = 0; iv1 < niv; iv1++) {
size_t i = iv1 / inner + inner;
size_t j = iv1 % inner;
for (size_t iv2 = 0; iv2 <= iv1; iv2++) {
size_t k = iv2 / inner + inner;
size_t l = iv2 % inner;
I2(2*i, 2*j, 2*k, 2*l) = iviv[iv1*(iv1+1)/2 + iv2];
}
}
delete [] iviv;
}
double energy_core[1];
energy_core[0] = 0.;
dataset_energy_core = H5Dopen(file, "/energy_core", H5P_DEFAULT);
status = H5Dread(dataset_energy_core, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, energy_core);
coreE = energy_core[0];
status = H5Fclose(file);
//exit(0);
I2.maxEntry = *std::max_element(&I2.store[0], &I2.store[0]+I2memory,myfn);
I2.Direct = MatrixXd::Zero(norbs, norbs); I2.Direct *= 0.;
I2.Exchange = MatrixXd::Zero(norbs, norbs); I2.Exchange *= 0.;
for (int i=0; i<inner; i++)
for (int j=0; j<inner; j++) {
I2.Direct(i,j) = I2(2*i,2*i,2*j,2*j);
I2.Exchange(i,j) = I2(2*i,2*j,2*j,2*i);
}
cout << "Finished reading integrals\n";
} // commrank=0
#ifndef SERIAL
mpi::broadcast(world, I1, 0);
long intdim = I2memory;
long maxint = 26843540; //mpi cannot transfer more than these number of doubles
long maxIter = intdim/maxint;
world.barrier();
for (int i=0; i<maxIter; i++) {
mpi::broadcast(world, &I2.store[i*maxint], maxint, 0);
world.barrier();
}
mpi::broadcast(world, &I2.store[maxIter*maxint], I2memory - maxIter*maxint, 0);
world.barrier();
mpi::broadcast(world, I2.maxEntry, 0);
mpi::broadcast(world, I2.Direct, 0);
mpi::broadcast(world, I2.Exchange, 0);
mpi::broadcast(world, I2.zero, 0);
mpi::broadcast(world, coreE, 0);
#endif
Determinant::EffDetLen = (norbs) / 64 + 1;
Determinant::norbs = norbs;
Determinant::nalpha = nalpha;
Determinant::nbeta = nbeta;
//initialize the heatbath integrals
std::vector<int> allorbs;
std::vector<int> innerorbs;
for (int i = 0; i < norbs; i++)
allorbs.push_back(i);
for (int i = 0; i < inner; i++)
innerorbs.push_back(i);
twoIntHeatBath I2HB(1.e-10);
twoIntHeatBath I2HBCAS(1.e-10);
if (commrank == 0) {
cout << "Starting heat bath integral construction\n";
//if (schd.nciAct > 0) I2HB.constructClass(innerorbs, I2, I1, 0, norbs);
//else I2HB.constructClass(allorbs, I2, I1, 0, norbs);
I2HB.constructClass(innerorbs, I2, I1, 0, norbs);
if (schd.nciCore > 0 || schd.nciAct > 0) I2HBCAS.constructClass(allorbs, I2, I1, schd.nciCore, schd.nciAct, true);
}
I2hb.constructClass(norbs, I2HB, 0);
if (schd.nciAct > 0 || schd.nciAct > 0) I2hbCAS.constructClass(norbs, I2HBCAS, 1);
if (commrank == 0) cout << "Finished heat bath integral construction\n";
} // end readIntegrals
//=============================================================================
int readNorbs(string fcidump) {
//-----------------------------------------------------------------------------
/*!
Finds the number of orbitals in the FCIDUMP file
:Inputs:
string fcidump:
Name of the FCIDUMP file
:Returns:
int norbs:
Number of orbitals in the FCIDUMP file
*/
//-----------------------------------------------------------------------------
#ifndef SERIAL
boost::mpi::communicator world;
#endif
int norbs;
if (commrank == 0) {
ifstream dump(fcidump.c_str());
vector<string> tok;
string msg;
std::getline(dump, msg);
trim(msg);
boost::split(tok, msg, is_any_of(", \t="), token_compress_on);
if (boost::iequals(tok[0].substr(0,4),"&FCI"))
if (boost::iequals(tok[1].substr(0,4), "NORB"))
norbs = atoi(tok[2].c_str());
}
#ifndef SERIAL
mpi::broadcast(world, norbs, 0);
#endif
return norbs;
} // end readNorbs
//=============================================================================
void twoIntHeatBathSHM::constructClass(int norbs, twoIntHeatBath& I2, bool cas) {
//-----------------------------------------------------------------------------
/*!
BM_description
:Inputs:
int norbs:
Number of orbitals
twoIntHeatBath& I2:
Two-electron tensor of the Hamiltonian (output)
*/
//-----------------------------------------------------------------------------
#ifndef SERIAL
boost::mpi::communicator world;
#endif
sameSpinPairExcitations = MatrixXd::Zero(norbs, norbs);
oppositeSpinPairExcitations = MatrixXd::Zero(norbs, norbs);
Singles = I2.Singles;
if (commrank != 0) Singles.resize(2*norbs, 2*norbs);
if (!cas) {
#ifndef SERIAL
mpi::broadcast(world, &Singles(0,0), Singles.rows()*Singles.cols(), 0);
#endif
}
I2.Singles.resize(0,0);
size_t memRequired = 0;
size_t nonZeroSameSpinIntegrals = 0;
size_t nonZeroOppositeSpinIntegrals = 0;
size_t nonZeroSingleExcitationIntegrals = 0;
if (commrank == 0) {
std::map<std::pair<short,short>, std::multimap<float, std::pair<short,short>, compAbs > >::iterator it1 = I2.sameSpin.begin();
for (;it1!= I2.sameSpin.end(); it1++) nonZeroSameSpinIntegrals += it1->second.size();
std::map<std::pair<short,short>, std::multimap<float, std::pair<short,short>, compAbs > >::iterator it2 = I2.oppositeSpin.begin();
for (;it2!= I2.oppositeSpin.end(); it2++) nonZeroOppositeSpinIntegrals += it2->second.size();
std::map<std::pair<short,short>, std::multimap<float, short, compAbs > >::iterator it3 = I2.singleIntegrals.begin();
for (;it3!= I2.singleIntegrals.end(); it3++) nonZeroSingleExcitationIntegrals += it3->second.size();
//total Memory required
memRequired += nonZeroSameSpinIntegrals*(sizeof(float)+2*sizeof(short))+ ( (norbs*(norbs+1)/2+1)*sizeof(size_t));
memRequired += nonZeroOppositeSpinIntegrals*(sizeof(float)+2*sizeof(short))+ ( (norbs*(norbs+1)/2+1)*sizeof(size_t));
memRequired += nonZeroSingleExcitationIntegrals*(sizeof(float)+2*sizeof(short))+ ( (norbs*(norbs+1)/2+1)*sizeof(size_t));
}
#ifndef SERIAL
mpi::broadcast(world, memRequired, 0);
mpi::broadcast(world, nonZeroSameSpinIntegrals, 0);
mpi::broadcast(world, nonZeroOppositeSpinIntegrals, 0);
mpi::broadcast(world, nonZeroSingleExcitationIntegrals, 0);
world.barrier();
#endif
if (!cas) {
int2SHMSegment.truncate(memRequired);
regionInt2SHM = boost::interprocess::mapped_region{int2SHMSegment, boost::interprocess::read_write};
memset(regionInt2SHM.get_address(), 0., memRequired);
}
else {
int2SHMCASSegment.truncate(memRequired);
regionInt2SHMCAS = boost::interprocess::mapped_region{int2SHMCASSegment, boost::interprocess::read_write};
memset(regionInt2SHMCAS.get_address(), 0., memRequired);
}
#ifndef SERIAL
world.barrier();
#endif
char* startAddress;
if (!cas) startAddress = (char*)(regionInt2SHM.get_address());
else startAddress = (char*)(regionInt2SHMCAS.get_address());
sameSpinIntegrals = (float*)(startAddress);
startingIndicesSameSpin = (size_t*)(startAddress
+ nonZeroSameSpinIntegrals*sizeof(float));
sameSpinPairs = (short*)(startAddress
+ nonZeroSameSpinIntegrals*sizeof(float)
+ (norbs*(norbs+1)/2+1)*sizeof(size_t));
oppositeSpinIntegrals = (float*)(startAddress
+ nonZeroSameSpinIntegrals*(sizeof(float)+2*sizeof(short))
+ (norbs*(norbs+1)/2+1)*sizeof(size_t));
startingIndicesOppositeSpin = (size_t*)(startAddress
+ nonZeroOppositeSpinIntegrals*sizeof(float)
+ nonZeroSameSpinIntegrals*(sizeof(float)+2*sizeof(short))
+ (norbs*(norbs+1)/2+1)*sizeof(size_t));
oppositeSpinPairs = (short*)(startAddress
+ nonZeroOppositeSpinIntegrals*sizeof(float)
+ (norbs*(norbs+1)/2+1)*sizeof(size_t)
+ nonZeroSameSpinIntegrals*(sizeof(float)+2*sizeof(short))
+ (norbs*(norbs+1)/2+1)*sizeof(size_t));
singleIntegrals = (float*)(startAddress
+ nonZeroOppositeSpinIntegrals*sizeof(float)
+ (norbs*(norbs+1)/2+1)*sizeof(size_t)
+ nonZeroSameSpinIntegrals*(sizeof(float)+2*sizeof(short))
+ (norbs*(norbs+1)/2+1)*sizeof(size_t)
+ nonZeroOppositeSpinIntegrals*(2*sizeof(short)));
startingIndicesSingleIntegrals = (size_t*)(startAddress
+ nonZeroOppositeSpinIntegrals*sizeof(float)
+ (norbs*(norbs+1)/2+1)*sizeof(size_t)
+ nonZeroSameSpinIntegrals*(sizeof(float)+2*sizeof(short))
+ (norbs*(norbs+1)/2+1)*sizeof(size_t)
+ nonZeroOppositeSpinIntegrals*(2*sizeof(short))
+ nonZeroSingleExcitationIntegrals*sizeof(float));
singleIntegralsPairs = (short*)(startAddress
+ nonZeroOppositeSpinIntegrals*sizeof(float)
+ (norbs*(norbs+1)/2+1)*sizeof(size_t)
+ nonZeroSameSpinIntegrals*(sizeof(float)+2*sizeof(short))
+ (norbs*(norbs+1)/2+1)*sizeof(size_t)
+ nonZeroOppositeSpinIntegrals*(2*sizeof(short))
+ nonZeroSingleExcitationIntegrals*sizeof(float)
+ (norbs*(norbs+1)/2+1)*sizeof(size_t));
if (commrank == 0) {
startingIndicesSameSpin[0] = 0;
size_t index = 0, pairIter = 1;
for (int i=0; i<norbs; i++)
for (int j=0; j<=i; j++) {
std::map<std::pair<short,short>, std::multimap<float, std::pair<short,short>, compAbs > >::iterator it1 = I2.sameSpin.find( std::pair<short,short>(i,j));
if (it1 != I2.sameSpin.end()) {
for (std::multimap<float, std::pair<short,short>,compAbs >::reverse_iterator it=it1->second.rbegin(); it!=it1->second.rend(); it++) {
sameSpinIntegrals[index] = it->first;
sameSpinPairs[2*index] = it->second.first;
sameSpinPairs[2*index+1] = it->second.second;
sameSpinPairExcitations(it->second.first, it->second.second) += abs(it->first);
index++;
}
}
startingIndicesSameSpin[pairIter] = index;
pairIter++;
}
I2.sameSpin.clear();
startingIndicesOppositeSpin[0] = 0;
index = 0; pairIter = 1;
for (int i=0; i<norbs; i++)
for (int j=0; j<=i; j++) {
std::map<std::pair<short,short>, std::multimap<float, std::pair<short,short>, compAbs > >::iterator it1 = I2.oppositeSpin.find( std::pair<short,short>(i,j));
if (it1 != I2.oppositeSpin.end()) {
for (std::multimap<float, std::pair<short,short>,compAbs >::reverse_iterator it=it1->second.rbegin(); it!=it1->second.rend(); it++) {
oppositeSpinIntegrals[index] = it->first;
oppositeSpinPairs[2*index] = it->second.first;
oppositeSpinPairs[2*index+1] = it->second.second;
oppositeSpinPairExcitations(it->second.first, it->second.second) += abs(it->first);
index++;
}
}
startingIndicesOppositeSpin[pairIter] = index;
pairIter++;
}
I2.oppositeSpin.clear();
startingIndicesSingleIntegrals[0] = 0;
index = 0; pairIter = 1;
for (int i=0; i<norbs; i++)
for (int j=0; j<=i; j++) {
std::map<std::pair<short,short>, std::multimap<float, short, compAbs > >::iterator it1 = I2.singleIntegrals.find( std::pair<short,short>(i,j));
if (it1 != I2.singleIntegrals.end()) {
for (std::multimap<float, short,compAbs >::reverse_iterator it=it1->second.rbegin(); it!=it1->second.rend(); it++) {
singleIntegrals[index] = it->first;
singleIntegralsPairs[2*index] = it->second;
index++;
}
}
startingIndicesSingleIntegrals[pairIter] = index;
pairIter++;
}
I2.singleIntegrals.clear();
} // commrank=0
long intdim = memRequired;
long maxint = 26843540; //mpi cannot transfer more than these number of doubles
long maxIter = intdim/maxint;
#ifndef SERIAL
world.barrier();
char* shrdMem = static_cast<char*>(startAddress);
for (int i=0; i<maxIter; i++) {
mpi::broadcast(world, shrdMem+i*maxint, maxint, 0);
world.barrier();
}
mpi::broadcast(world, shrdMem+(maxIter)*maxint, memRequired - maxIter*maxint, 0);
world.barrier();
#endif
#ifndef SERIAL
mpi::broadcast(world, &sameSpinPairExcitations(0,0), sameSpinPairExcitations.rows()*
sameSpinPairExcitations.cols(), 0);
mpi::broadcast(world, &oppositeSpinPairExcitations(0,0), oppositeSpinPairExcitations.rows()*
oppositeSpinPairExcitations.cols(), 0);
#endif
} // end twoIntHeatBathSHM::constructClass
void twoIntHeatBathSHM::getIntegralArray(int i, int j, const float* &integrals,
const short* &orbIndices, size_t& numIntegrals) const {
int I = i / 2, J = j / 2;
int X = max(I, J), Y = min(I, J);
int pairIndex = X * (X + 1) / 2 + Y;
size_t start = i % 2 == j % 2 ? I2hb.startingIndicesSameSpin[pairIndex] : I2hb.startingIndicesOppositeSpin[pairIndex];
size_t end = i % 2 == j % 2 ? I2hb.startingIndicesSameSpin[pairIndex + 1] : I2hb.startingIndicesOppositeSpin[pairIndex + 1];
integrals = i % 2 == j % 2 ? I2hb.sameSpinIntegrals+start : I2hb.oppositeSpinIntegrals+start;
orbIndices = i % 2 == j % 2 ? I2hb.sameSpinPairs+2*start : I2hb.oppositeSpinPairs+2*start;
numIntegrals = end-start;
}
void twoIntHeatBathSHM::getIntegralArrayCAS(int i, int j, const float* &integrals,
const short* &orbIndices, size_t& numIntegrals) const {
int I = i / 2, J = j / 2;
int X = max(I, J), Y = min(I, J);
int pairIndex = X * (X + 1) / 2 + Y;
size_t start = i % 2 == j % 2 ? I2hbCAS.startingIndicesSameSpin[pairIndex] : I2hbCAS.startingIndicesOppositeSpin[pairIndex];
size_t end = i % 2 == j % 2 ? I2hbCAS.startingIndicesSameSpin[pairIndex + 1] : I2hbCAS.startingIndicesOppositeSpin[pairIndex + 1];
integrals = i % 2 == j % 2 ? I2hbCAS.sameSpinIntegrals+start : I2hbCAS.oppositeSpinIntegrals+start;
orbIndices = i % 2 == j % 2 ? I2hbCAS.sameSpinPairs+2*start : I2hbCAS.oppositeSpinPairs+2*start;
numIntegrals = end-start;
}
<file_sep>import numpy as np
xmax, ymax = 1, 10
nsites = xmax*ymax
U = 4.
corrLen = 1
sqrt2 = 2**0.5
data = []
for i in range(xmax):
for j in range(ymax):
data.append([i,j])
integralsFh = open("FCIDUMP", "w")
integralsFh.write("&FCI NORB=%d ,NELEC=%d ,MS2=0,\n"%(nsites, nsites))
integralsFh.write("ORBSYM=")
for i in range(nsites):
integralsFh.write("%1d,"%(1))
integralsFh.write("\n")
integralsFh.write("ISYM=1,\n")
integralsFh.write("&END\n")
int2 = np.zeros((nsites, nsites, nsites, nsites))
int1 = np.zeros((nsites, nsites))
fock = np.zeros((nsites, nsites))
for i in range(nsites):
int2[i,i,i,i] = U
integralsFh.write("%16.8f %4d %4d %4d %4d \n"%(U, i+1, i+1, i+1, i+1))
for i in range(nsites):
for j in range(i+1, nsites):
d1, d2 = data[i], data[j]
if ( (abs(d1[0] - d2[0]) == 1 or abs(d1[0] - d2[0]) == xmax-1) and d1[1]== d2[1]) :
int1[i, j] = int1[j, i] = -1.
fock[i, j] = fock[j, i] = -1.
integralsFh.write("%16.8f %4d %4d %4d %4d \n"%(-1., i+1, j+1, 0, 0))
elif ( (abs(d1[1] - d2[1]) == 1 or abs(d1[1] - d2[1]) == ymax-1) and d1[0]== d2[0]) :
int1[i, j] = int1[j, i] = -1.
fock[i, j] = fock[j, i] = -1.
integralsFh.write("%16.8f %4d %4d %4d %4d \n"%(-1., i+1, j+1, 0, 0))
integralsFh.close()
correlators=[]
#all nearest neighbors
#for i in range(nsites):
# c = [i]
# for j in range(nsites):
# if (int1[i,j] != 0):
# c.append(j)
# c = list(set(c))
# correlators.append(c)
#neighbor pairs for 1 d
for i in range(nsites - 1):
correlators.append([i, i + 1])
correlators.append([nsites - 1, 0])
#all pairs
#for i in range(nsites):
# for j in range(nsites - 1 - i):
# correlators.append([i, i + j + 1])
correlatorsFh = open("correlators.txt", 'w')
for c in correlators:
for t in c:
correlatorsFh.write("%d "%(t))
correlatorsFh.write("\n")
correlatorsFh.close();
ek, orb = np.linalg.eigh(fock)
diag = np.zeros((nsites, nsites))
for i in range(nsites/2):
diag[i, i] = 1.
pairMat = np.mat(orb) * np.mat(diag) * np.mat(np.transpose(orb))
pairFh = open("pairMat.txt", 'w')
for i in range(nsites):
for j in range(nsites):
pairFh.write('%16.10e '%(pairMat[i,j]))
pairFh.write('\n')
pairFh.close()
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef FORTRAN_INT_H
#define FORTRAN_INT_H
#include <boost/cstdint.hpp>
//#include <stdint.h>
// ^- get those from C99 stdint.h (technically not C++ standard)
// or from boost cstdint.hpp from outside.
// basic fortran integer type.
#ifdef _I4_
typedef boost::int32_t FORTINT;
#else
// typedef boost::int64_t FORTINT;
//#ifdef _SINGLE_PRECISION
//typedef int FORTINT;
//#else
typedef long FORTINT;
//#endif
// ^- (should default to 32bit for 32bit systems)
#endif
typedef FORTINT const
&FINTARG;
typedef double const
&FDBLARG;
// number of trailing underscores functions with FORTRAN signature get.
#ifndef FORT_UNDERSCORES
#define FORT_UNDERSCORES 1 /* most linux fortran compilers do it like that. */
#endif
// macro for defining C functions which are callable from FORTRAN side
// (and reverse direction):
// A function
// void FORT_Extern(bla,BLA)(FORTINT &a, double &b);
// can be called as a function
// subroutine bla(a, b)
// integer :: a
// double precision :: b
// from Fortran side.
#ifdef FORT_UPPERCASE
#if FORT_UNDERSCORES == 0
#define FORT_Extern(lowercasef,UPPERCASEF) UPPERCASEF
#elif FORT_UNDERSCORES == 1
#define FORT_Extern(lowercasef,UPPERCASEF) UPPERCASEF##_
#elif FORT_UNDERSCORES == 2
#define FORT_Extern(lowercasef,UPPERCASEF) UPPERCASEF##__
#else
#error "should define FORT_UNDERSCORES for fortran function signatures."
#endif
#else
#if FORT_UNDERSCORES == 0
#define FORT_Extern(lowercasef,UPPERCASEF) lowercasef
#elif FORT_UNDERSCORES == 1
#define FORT_Extern(lowercasef,UPPERCASEF) lowercasef##_
#elif FORT_UNDERSCORES == 2
#define FORT_Extern(lowercasef,UPPERCASEF) lowercasef##__
#else
#error "should define FORT_UNDERSCORES for fortran function signatures."
#endif
#endif
#endif /* FORTRAN_INT_H */
<file_sep>import numpy
import math
from pyscf import gto, scf, ao2mo, mcscf, tools, fci
from pyscf.shciscf import shci, settings
from pyscf.lo import pipek
mol = gto.M(
atom = 'H 0 0 0; H 0 0 1.0;H 0 0 2.0;H 0 0 3.0;H 0 0 4.0;H 0 0 5.0;',
basis = 'sto-3g',
verbose=5,
spin = 0)
myhf = scf.RHF(mol)
myhf.kernel()
print myhf.e_tot
mc = mcscf.CASCI(myhf, myhf.mo_coeff.shape[0], 6)
mc.fcisolver = shci.SHCI(mol)
mc.fcisolver.sweep_iter=[0]
mc.fcisolver.sweep_epsilon=[0.12]
print mc.kernel(myhf.mo_coeff)
lmo = pipek.PM(mol).kernel(myhf.mo_coeff)
S = myhf.get_ovlp(mol)
#uc(lmo, mo)
uc = reduce(numpy.dot, (myhf.mo_coeff.T, S, lmo)).T
norbs = myhf.mo_coeff.shape[0]
fileHF = open("hf.txt", 'w')
for i in range(norbs):
for j in range(norbs):
fileHF.write('%16.10e '%(uc[i,j]))
fileHF.write('\n')
mc.fcisolver.onlywriteIntegral = True
mc.kernel(lmo)
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#include <stdexcept>
#include <stdio.h> // for tmpfile and c-style file handling functions
#include <memory.h>
#include <string.h>
#include "CxStorageDevice.h"
#include "CxMemoryStack.h"
#include "CxAlgebra.h"
namespace ct {
FStorageBlock FStorageDevice::AllocNewBlock(uint64_t SizeInBytes)
{
FRecord r = AllocNewRecord(SizeInBytes);
return FStorageBlock(*this, r);
};
FStorageDevice::~FStorageDevice()
{
};
FRecord FStorageDevicePosixFs::AllocNewRecord(uint64_t SizeInBytes)
{
uint
NewId = FileIds.size();
FILE *NewFile = tmpfile();
if ( NewFile == 0 )
throw std::runtime_error("FStorageDevicePosixFs: Failed to open a temporary file via tmpfile() function.");
FileIds[NewId] = NewFile;
return FRecord(NewId, 0, 0, SizeInBytes);
};
void FStorageDevicePosixFs::Write( FRecord const &r, void const *pData, FStreamOffset nLength, FStreamOffset Offset ) const
{
FILE *File = GetHandle(r);
fseek(File, Offset + r.BaseOffset, SEEK_SET);
fwrite(pData, 1, nLength, File);
if (ferror(File)) throw std::runtime_error("failed to write data.");
};
void FStorageDevicePosixFs::Read( FRecord const &r, void *pData, FStreamOffset nLength, FStreamOffset Offset ) const
{
FILE *File = GetHandle(r);
fseek(File, Offset + r.BaseOffset, SEEK_SET);
fread(pData, 1, nLength, File);
if (ferror(File)) throw std::runtime_error("failed to read data.");
};
void FStorageDevicePosixFs::Reserve( FRecord const &r, FStreamOffset nLength ) const
{
};
void FStorageDevicePosixFs::Delete( FRecord const &r )
{
FILE *File = GetHandle(r);
fclose(File);
FileIds.erase(r.iFile);
};
FILE *FStorageDevicePosixFs::GetHandle(FRecord const &r) const {
FFileIdMap::const_iterator
it = FileIds.find(r.iFile);
if ( it == FileIds.end() )
throw std::runtime_error("FStorageDevicePosixFs: Attempted to access a non-exitent file id.");
return it->second;
};
// FILE *FStorageDevicePosixFs::GetHandle(FRecord const &r) {
// return const_cast<FILE*>( const_cast<FStorageDevicePosixFs const*>(this)->GetHandle(r) );
// };
FStorageDevicePosixFs::FStorageDevicePosixFs()
{
};
FStorageDevicePosixFs::~FStorageDevicePosixFs()
{
FFileIdMap::reverse_iterator
itFile;
for (itFile = FileIds.rbegin(); itFile != FileIds.rend(); ++ itFile)
fclose(itFile->second);
};
void FStorageDevice::FRecord::SetLength(FStreamOffset NewLength) const
{
assert(NewLength != UnknownSize);
assert(EndOffset == UnknownSize || EndOffset - BaseOffset == NewLength);
const_cast<FStorageDevice::FRecord*>(this)->EndOffset = BaseOffset + NewLength;
}
FStorageDeviceMemoryBuf::FBuffer &FStorageDeviceMemoryBuf::GetBuf(FRecord const &r) const {
assert(r.iRecord < m_Buffers.size());
return *(const_cast<FBuffer*>(&m_Buffers[r.iRecord]));
}
FRecord FStorageDeviceMemoryBuf::AllocNewRecord(uint64_t SizeInBytes)
{
m_Buffers.push_back(FBuffer());
m_Buffers.back().p = 0;
m_Buffers.back().Length = 0;
FRecord
r = FRecord(0, m_Buffers.size() - 1, 0);
if ( SizeInBytes != 0 )
Reserve(r, SizeInBytes);
return r;
};
void FStorageDeviceMemoryBuf::Write( FRecord const &r, void const *pData, FStreamOffset nLength, FStreamOffset Offset ) const
{
FBuffer &Buf = GetBuf(r);
if ( Buf.p == 0 )
Reserve(r, Offset + nLength);
Offset += r.BaseOffset;
assert(Offset + nLength <= Buf.Length );
memcpy(Buf.p + Offset, pData, nLength);
};
void FStorageDeviceMemoryBuf::Read( FRecord const &r, void *pData, FStreamOffset nLength, FStreamOffset Offset ) const
{
FBuffer &Buf = GetBuf(r);
Offset += r.BaseOffset;
assert(Offset + nLength <= Buf.Length );
memcpy(pData, Buf.p + Offset, nLength);
};
void FStorageDeviceMemoryBuf::Reserve( FRecord const &r, FStreamOffset nLength ) const
{
FBuffer &Buf = GetBuf(r);
delete Buf.p;
Buf.p = static_cast<char*>(malloc(nLength));
Buf.Length = nLength;
};
void FStorageDeviceMemoryBuf::Delete( FRecord const &r )
{
FBuffer &Buf = GetBuf(r);
delete Buf.p;
Buf.p = 0;
Buf.Length = 0;
};
FStorageDeviceMemoryBuf::~FStorageDeviceMemoryBuf()
{
// semi-safe...
for ( uint i = m_Buffers.size(); i != 0; -- i )
delete m_Buffers[i - 1].p;
m_Buffers.clear();
};
template<class FScalar>
void FileAndMemOp( FFileAndMemOp Op, FScalar &F, FScalar *pMemBuf,
std::size_t nMemLength, FStorageBlock const &Rec,
FMemoryStack &Temp )
{
// perform simple memory block/file block operations with
// constant memory buffer size.
std::size_t
nSize,
nOff = 0,
nFileStep = std::min( Temp.MemoryLeft(), (size_t)1000000 ); // ! ~ 1 mb
FScalar
fVal = 0.0,
*pFileBuf;
const uint
Byte = sizeof(FScalar);
nFileStep = nFileStep/Byte - 1;
//assert_rt( nFileStep != 0 );
Temp.Alloc( pFileBuf, nFileStep );
while ( nOff < nMemLength ) {
nSize = std::min( nFileStep, nMemLength - nOff );
Rec.pDevice->Read( Rec.Record, pFileBuf, nSize*Byte, nOff*Byte );
switch( Op ){
case OP_AddToMem:
// add f*file_content to BufM.
Add( pMemBuf + nOff, pFileBuf, F, nSize );
break;
case OP_AddToFile:
// add f*mem_content to file
Add( pFileBuf, pMemBuf + nOff, F, nSize );
Rec.pDevice->Write( Rec.Record, pFileBuf, nSize*Byte, nOff*Byte );
break;
case OP_Dot:
// form dot(mem,file), store result in F.
fVal += Dot( pFileBuf, pMemBuf + nOff, nSize );
F = fVal;
break;
default:
assert(0);
}
nOff += nSize;
}
Temp.Free( pFileBuf );
}
template void FileAndMemOp( FFileAndMemOp, double&, double*, std::size_t, FStorageBlock const &, FMemoryStack & );
// template void FileAndMemOp( FFileAndMemOp, float&, float*, std::size_t, FStorageBlock const &, FMemoryStack & );
} // namespace ct
<file_sep>#include "pythonInterface.h"
#include "fittedFunctions.h"
#include <iostream>
void getSphericalCoords(double& x, double& y, double& z,
double& r, double& t, double& p) {
double xy = x*x + y*y;
r = sqrt(xy + z*z);
t = atan2(sqrt(xy), z);
p = atan2(y, x);
if (p < 0.0)
p += 2*M_PI;
}
void getSphericalCoords(MatrixXdR& grid, MatrixXd& SphericalCoords) {
int ngridPts = grid.rows();
for (int i=0; i<ngridPts; i++) {
getSphericalCoords(grid(i,0), grid(i, 1), grid(i,2),
SphericalCoords(i,0), SphericalCoords(i,1), SphericalCoords(i,2));
}
}
void getBeckePartition(double* coords, int ngrids, double* pbecke) {
vector<double> fcoord(ngrids*3);
vector<double> atmCoord(natm*3);
for (int i=0; i<ngrids; i++) {
fcoord[0*ngrids+i] = coords[i*3+0];
fcoord[1*ngrids+i] = coords[i*3+1];
fcoord[2*ngrids+i] = coords[i*3+2];
}
for (int i=0; i<natm; i++) {
atmCoord[3*i+0] = env[atm[6*i+1] + 0];
atmCoord[3*i+1] = env[atm[6*i+1] + 1];
atmCoord[3*i+2] = env[atm[6*i+1] + 2];
}
VXCgen_grid(pbecke, &fcoord[0], &atmCoord[0], NULL, natm, ngrids);
}
void SplineFit::Init(const RawDataOnGrid& potentialYlm){
zgrid = potentialYlm.zgrid;
rm = potentialYlm.rm;
lmax = potentialYlm.lmax;
int nlm = potentialYlm.CoeffsYlm.cols();
int nr = zgrid.size();
CoeffsYlm.resize(nlm);
CoeffsYlmFit.resize(nlm);
vector<double> vals(nr+2,0.0);
double h = 1.0/(1.*nr + 1.), t0 = 0; //t0 = 0 -> r= infty
for (int lm = 0; lm < nlm; lm++) {
for (int j=0; j<nr; j++)
vals[j+1] = potentialYlm.CoeffsYlm(j, lm);
vals[nr+1] = 0.0; //at r-> 0 Ulm = 0;
if (lm == 0) //l == 0
vals[0] = vals[1]; //sqrt(r pi) q
else
vals[0] = 0.0;
CoeffsYlmFit[lm] = boost::math::cubic_b_spline<double>(vals.begin(), vals.end(), t0, h);
}
}
void SplineFit::getPotential(int ngrid, double* grid, double* potential) {
#pragma omp parallel
{
double sphCoord[3];
CalculateSphHarmonics sph(lmax);
#pragma omp for
for (int i=0; i<ngrid; i++) {
double X = grid[3*i] - coord[0],
Y = grid[3*i+1] - coord[1],
Z = grid[3*i+2] - coord[2];
getSphericalCoords(X, Y, Z,
sphCoord[0], sphCoord[1], sphCoord[2]);
sph.populate(sphCoord[1], sphCoord[2]); //sphcoords
double r = sphCoord[0];
double z = (1./M_PI) * acos( (r - rm)/(r+rm));
for (int lm=0; lm<CoeffsYlmFit.size(); lm++)
CoeffsYlm[lm] = CoeffsYlmFit[lm](z);
potential[i] += CoeffsYlm.dot( sph.values )/r;
}
}
}
void RawDataOnGrid::InitStaticVariables(int plmax, int lebdevOrder) {
//make lebdev grid of order lebdevorder
lmax = plmax;
int GridSize = lebdevGridSize[lebdevOrder/2];
lebdevgrid.resize(GridSize,4);
LebdevGrid::MakeAngularGrid(&lebdevgrid(0,0), GridSize);
lebdevgrid.col(3) *= 4 * M_PI;
//get spherical coordinates from it
SphericalCoords.resize(GridSize, 3);
getSphericalCoords(lebdevgrid, SphericalCoords);
//get value of spherical harmonics on the lebdev grid
sphVals.resize(GridSize, (lmax+1)*(lmax+1));
WeightedSphVals.resize(GridSize, (lmax+1)*(lmax+1));
CalculateSphHarmonics sph(lmax); //this is just used to calculated Ylm on the grid
for (int i=0; i<GridSize; i++) {
sph.populate(SphericalCoords(i,1), SphericalCoords(i,2));
sphVals.row(i) = sph.values;
WeightedSphVals.row(i) = sph.values * lebdevgrid(i,3) ;
}
densityStore.resize(GridSize);
}
void RawDataOnGrid::InitRadialGrids(int rmax, double prm) {
GridValues.resize(rmax, lebdevgrid.rows());
CoeffsYlm.resize(rmax, (lmax+1)*(lmax+1)); //spherical harmonics on a radial grid
radialGrid.resize(rmax);
zgrid.resize(rmax);
wts.resize(rmax);
rm = prm;
GridValues.setZero(); CoeffsYlm.setZero();
for (int i=0; i<rmax; i++) {
zgrid(i) = (1.*i+1.)/(1.*rmax+1.);
double x = cos(M_PI*zgrid(i));
radialGrid(i) = rm * ((1.+x)/(1.-x));
//grid[i] = radialGrid(i);
wts(i) = pow(radialGrid(i),2) * M_PI/(1.*rmax+1.) *
pow( sin( (i+1.) * M_PI / (1.*rmax + 1.0)), 2.) *
2 * rm/(1.-x)/(1.-x)/sqrt(1.-x*x);
//radwts[i] = wts(i);
}
}
//calculate the coefficients for spherical Harmonics for lebdev grid at radius r
void RawDataOnGrid::fit(int rindex, double* density) {
int nang = densityStore.size();
for (int i=0; i<densityStore.size(); i++)
densityStore(i) = density[i];
GridValues.row(rindex) = densityStore;
CoeffsYlm.row(rindex) = WeightedSphVals.transpose() * densityStore;
}
void RawDataOnGrid::getValue(int rindex, double* densityOut) {
densityStore = CoeffsYlm.row(rindex) * sphVals.transpose();
for (int i=0; i<densityStore.size(); i++)
densityOut[i] = densityStore(i);
}
<file_sep>#ifndef STATS_HEADER_H
#define STATS_HEADER_H
#include "Determinants.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
//various functions for calculating statistics of serially correlated data, functions overloaded for weighted and unweighted data sets
//random calcTcorr function, idk who wrote this it's pretty rough
double calcTcorr(vector<double> &v);
//average function
// weighted data
double average(vector<double> &x, vector<double> &w);
// unweighted data
double average(vector<double> &x);
//calculates effective sample size for weighted data sets. For unweighted data, will just return the size of the data set
double neff(vector<double> &w);
//variance function, takes advantage of bessel's correction
// weighted data
double variance(vector<double> &x, vector<double> &w);
// unweighted data
double variance(vector<double> &x);
//correlation function: given a weighted/unweighted data set, calculates C(t) = <(x(i)-x_bar)(x(i+t)-x_bar)> / <(x(i)-x_bar)^2>
//Input: x, w if weighted; x if unweighted
//Output: c
void corrFunc(vector<double> &c, vector<double> &x, vector<double> &w);
void corrFunc(vector<double> &c, vector<double> &x);
//autocorrelation time: given correlation function, calculates autocorrelation time: t = 1 + 2 \sum C(i)
double corrTime(vector<double> &c);
//writes correlation function to text file
void writeCorrFunc(vector<double> &c);
//blocking function, given a wighted or unweighted data set, calculates autocorrelation time vs. block size
//Input: x, w if weighted; x if unweighted
//Output: b_size - block size per iteration, r_t - autocorrelation time per iteration
void block(vector<double> &b_size, vector<double> &r_t, vector<double> &x, vector<double> &w);
void block(vector<double> &b_size, vector<double> &r_t, vector<double> &x);
//autocorrelation time: given blocking data, finds autocorrelation time based on the criteria: (block size)^3 > 2 * (number of original data points) * (autocorrelation time)^2
double corrTime(double n_original, vector<double> &b_size, vector<double> &r_t);
//writes blocking data to file
void writeBlock(vector<double> &b_size, vector<double> &r_t);
//class wrapper
class Statistics
{
public:
//data
vector<double> X, W;
vector<double> eneSamples, normSamples, ovlps;
vector<Determinant> dets;
//outputs
double avg, n = -1.0, var;
vector<double> C;
vector<double> B, R;
double t_corr, t_block;
//append data point
int push_back(double ene, double norm, double ovlp, Determinant d, double T)
{
eneSamples.push_back(ene);
normSamples.push_back(norm);
ovlps.push_back(ovlp);
dets.push_back(d);
W.push_back(T);
return 2;
}
int push_back(double x, double w)
{
X.push_back(x);
W.push_back(w);
return 2;
}
int push_back(double x)
{
X.push_back(x);
return 1;
}
void writeSamples(double avgEne, double stddev, double avgNorm)
{
string fname = "samples_";
fname.append(to_string(commrank));
fname.append(".dat");
ofstream samplesFile(fname, ios::app);
samplesFile << "newIter\n" << "ene " << setprecision(8) << avgEne << " (" << stddev << "), avgNorm " << avgNorm << endl;
samplesFile << "det ovlp eneSample normSample ratio T\n";
for (int i = 0; i < eneSamples.size(); i++)
samplesFile << dets[i] << " " << ovlps[i] << " " << eneSamples[i] << " " << normSamples[i] << " " << eneSamples[i] / normSamples[i] << " " << W[i] << endl;
samplesFile << endl << endl;
samplesFile.close();
}
//write data to file
void WriteData()
{
if (X.size() == 0)
cout << "No data to write" << endl;
else
{
ofstream xdata("X.bin", ios::binary);
xdata.write((char *)&X[0], X.size() * sizeof(double));
xdata.close();
if (X.size() == W.size())
{
ofstream wdata("W.bin", ios::binary);
wdata.write((char *)&W[0], W.size() * sizeof(double));
wdata.close();
}
}
}
//calculates average of data
double Average()
{
if (X.size() == 0)
{
cout << "No data to average" << endl;
return 0.0;
}
else
{
if (X.size() == W.size())
avg = average(X,W);
else
avg = average(X);
return avg;
}
}
//calculates effective number of data points
double Neff()
{
if (X.size() == W.size())
n = neff(W);
else
n = (double) X.size();
return n;
}
//calculates variance of data set
double Variance()
{
if (X.size() == 0)
{
cout << "No data to analyze" << endl;
return 0.0;
}
else
{
if (X.size() == W.size())
var = variance(X,W);
else
var = variance(X);
return var;
}
}
//calculates time correlation function
void CorrFunc()
{
if (X.size() == 0)
cout << "No data to analyze" << endl;
else
{
if (X.size() == W.size())
corrFunc(C,X,W);
else
corrFunc(C,X);
}
}
//Integrates correlation function to calculate autocorrelation time
double IntCorrTime() //"Integrated autocorrelation time" - brute force calc
{
if (C.size() == 0)
{
cout << "Run CorrFunc() before integrating for autocorrelation time" << endl;
t_corr = 0.0;
return t_corr;
}
else
{
t_corr = corrTime(C);
return t_corr;
}
}
//Writes Correlation function to file
void WriteCorrFunc()
{
if (C.size() == 0)
cout << "Correlation function is empty" << endl;
else
writeCorrFunc(C);
}
//reblocking analysis
void Block()
{
if (X.size() == 0)
cout << "No data to analyze" << endl;
else
{
if (X.size() == W.size())
block(B,R,X,W);
else
block(B,R,X);
}
}
//find autocorrelation time by finding saturated block length
double BlockCorrTime()
{
if (B.size() == 0)
{
cout << "Run Block() before checking for autocorrelation time convergence" << endl;
return 0.0;
}
else
{
if (n == -1) Neff();
t_block = corrTime(n,B,R);
return t_block;
}
}
//Write bloc to file
void WriteBlock()
{
if (B.size() == 0 && R.size() == 0)
cout << "Blocking data is empty" << endl;
else
writeBlock(B,R);
}
};
#endif
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#include <iostream>
#include <cmath>
#include <stdexcept>
#include <cmath>
#include "CxTypes.h"
#include "CxAlgebra.h"
#include "CxDiis.h"
#include "CxMemoryStack.h"
namespace ct {
uint const VecNotPresent = 0xffff;
void PrintMatrixGen( std::ostream &out, double const *pData,
uint nRows, uint nRowStride, uint nCols, uint nColStride,
std::string const &Name );
//typedef FDiisTarget::FScalar
//FScalar;
void ErrorExit1(std::string const &s) {
throw std::runtime_error(s);
}
void LinearSolveSymSvd(FScalar *pOut, FScalar *pMat, uint nStr, FScalar *pIn, uint nDim, FScalar Thr, FMemoryStack &Mem)
{
FScalar
*pEvs = Mem.AllocN(nDim * nDim, pMat[0]),
*pEws = Mem.AllocN(nDim, pMat[0]),
*pXv = Mem.AllocN(nDim, pMat[0]); // input vectors in EV basis.
for (uint j = 0; j < nDim; ++ j)
for (uint i = 0; i < nDim; ++ i)
pEvs[i + nDim*j] = -pMat[i + nStr*j]; // <- beware of minus.
Diagonalize(pEws, pEvs, nDim, nDim);
Mxv(pXv,1, pEvs,nDim,1, pIn,1, nDim,nDim);
for (uint iEw = 0; iEw != nDim; ++ iEw)
if (std::abs(pEws[iEw]) >= Thr)
pXv[iEw] /= -pEws[iEw];
// ^- note that this only screens by absolute value.
// no positive semi-definiteness is assumed!
else
pXv[iEw] = 0.;
Mxv(pOut,1, pEvs,1,nDim, pXv,1, nDim,nDim);
Mem.Free(pEvs);
}
FDiisState::FDiisState( FMemoryStack &Memory, FDiisOptions const &Options,
FStorageBlock const &Storage )
: m_Options( Options ),
m_Storage( Storage ),
m_Memory(Memory),
m_ErrorMatrix( Options.nMaxDim, Options.nMaxDim )
{
m_nAmplitudeLength = iNotPresent;
m_nResidualLength = iNotPresent;
if ( m_Storage.pDevice == 0 ) {
// no external device provided. Use an internal one
// which just keeps resident memory buffers.
m_Storage = FStorageBlock(m_StorageDeviceToUseIfNoneProvided,
m_StorageDeviceToUseIfNoneProvided.AllocNewRecord());
}
if ( nMaxDim() >= nMaxDiisCapacity )
ErrorExit1( "Trying to construct a DIIS object with higher number of"
" subspace vectors than currently allowed. Increase nMaxDiisCapacity." );
Reset();
};
void FDiisState::Reset()
{
// m_nDim = 0;
for ( uint i = 0; i < nMaxDiisCapacity; ++ i )
m_iVectorAge[i] = VecNotPresent;
m_iNext = 0;
};
FStorageDevice::FRecord FDiisState::ResidualRecord( uint iVec )
{
// store all residuals at the front of the record.
assert( m_nResidualLength != iNotPresent );
FStorageDevice::FRecord
r(m_Storage.Record);
r.BaseOffset += m_nResidualLength * iVec;
return r;
};
FStorageDevice::FRecord FDiisState::AmplitudeRecord( uint iVec )
{
// store amplitudes behind the residuals.
assert( m_nAmplitudeLength != iNotPresent );
FStorageDevice::FRecord
r(m_Storage.Record);
r.BaseOffset += m_nResidualLength * nMaxDim();
r.BaseOffset += m_nAmplitudeLength * iVec;
return r;
};
struct FDiisTargetLock
{
FDiisTargetLock( FDiisTarget &TR_ ) : TR(TR_) {
TR.Prepare();
};
~FDiisTargetLock(){
TR.Finish();
};
FDiisTarget &TR;
};
uint FDiisState::nLastDim() const
{
uint nDim = 0;
for ( uint i = 0; i < nMaxDim(); ++ i )
if ( m_iVectorAge[i] < VecNotPresent )
nDim += 1;
return nDim;
}
void FDiisState::FindUsefulVectors(uint *iUsedVecs, uint &nDim, FScalar &fBaseScale, uint iThis)
{
// remove lines from the system which correspond to vectors which are too bad
// to be really useful for extrapolation purposes, but which might break
// numerical stability if left in.
FScalar const
fThrBadResidual = 1e12;
FScalar
fBestResidualDot = m_ErrorMatrix(iThis,iThis),
fWorstResidualDot = fBestResidualDot;
assert(m_iVectorAge[iThis] < VecNotPresent);
for ( uint i = 0; i < nMaxDim(); ++ i ) {
if ( m_iVectorAge[i] >= VecNotPresent ) continue;
fBestResidualDot = std::min( m_ErrorMatrix(i,i), fBestResidualDot );
}
nDim = 0;
for ( uint i = 0; i < nMaxDim(); ++ i ){
if ( i != iThis && m_iVectorAge[i] >= VecNotPresent )
continue;
if ( i != iThis && m_ErrorMatrix(i,i) > fBestResidualDot * fThrBadResidual) {
m_iVectorAge[i] = VecNotPresent; // ignore this slot next time.
continue;
}
fWorstResidualDot = std::max( m_ErrorMatrix(i,i), fWorstResidualDot );
iUsedVecs[nDim] = i;
++ nDim;
};
fBaseScale = std::sqrt(fWorstResidualDot * fBestResidualDot);
if ( fBaseScale <= 0. )
fBaseScale = 1.;
};
void FDiisState::PerformDiis( FDiisTarget &TR, FScalar W1 )
{
using std::abs;
if ( nMaxDim() <= 1 )
// DIIS has been disabled.
return;
// see if we have enough memory left for diis matrices and
// for a reasonable file buffer in FileAndMemOp.
if ( m_Memory.MemoryLeft() < sizeof(FScalar) * (25000 + 1338) )
ErrorExit1("DIIS: Not enough memory left to perform DIIS.");
FDiisTargetLock
Lock(TR);
void
*pTopOfStack = m_Memory.Alloc(0);
if ( m_nAmplitudeLength == iNotPresent ) {
// vector not yet initialized. vector length was not known previously.
m_nAmplitudeLength = TR.nAmplitudeLength();
m_nResidualLength = TR.nResidualLength();
// reserve memory for iterative subspace residuals/amplitudes on target record.
FStreamSize
TotalLength = nMaxDim() * ( m_nAmplitudeLength + m_nResidualLength );
m_Storage.pDevice->Reserve( m_Storage.Record, TotalLength );
m_Weights.resize( nMaxDim() );
} else {
if ( m_nAmplitudeLength != TR.nAmplitudeLength() ||
m_nResidualLength != TR.nResidualLength() )
ErrorExit1("DIIS: Lengths of different amplitude/residual vectors differ.");
}
FScalar
fThisResidualDot = TR.OwnResidualDot();
m_LastResidualNormSq = fThisResidualDot;
if ( m_iNext == 0 && fThisResidualDot > m_Options.ResidualThresh )
// current vector is to be considered too wrong to be useful for DIIS
// purposes. Don't store it.
return;
uint
iThis = m_iNext;
assert(iThis < nMaxDim() && nMaxDim() < nMaxDiisCapacity);
m_ErrorMatrix(iThis,iThis) = fThisResidualDot;
for ( uint i = 0; i < nMaxDim(); ++ i )
m_iVectorAge[i] += 1;
m_iVectorAge[iThis] = 0;
// find set of vectors actually used in the current run and
// find their common size scale.
uint
iUsedVecs[ nMaxDiisCapacity + 1 ],
nDim;
// ^- note: this is the DIIS dimension--the actual matrices and vectors have
// dimension nDim+1 due to the Lagrange-Multipliers!
FScalar
fBaseScale;
FindUsefulVectors(&iUsedVecs[0], nDim, fBaseScale, iThis);
// transform iThis into a relative index.
for ( uint i = 0; i < nDim; ++ i )
if ( iThis == iUsedVecs[i] ) {
iThis = i;
break;
}
// make array of sub-records describing all present subspace vectors
FStorageDevice::FRecord
ResRecs[ nMaxDiisCapacity + 1 ],
AmpRecs[ nMaxDiisCapacity + 1 ];
assert( nDim < nMaxDiisCapacity );
for ( uint i = 0; i < nDim; ++ i ){
ResRecs[i] = ResidualRecord(iUsedVecs[i]);
AmpRecs[i] = AmplitudeRecord(iUsedVecs[i]);
}
// write current amplitude and residual vectors to their designated place
TR.SerializeTo( ResRecs[iThis], AmpRecs[iThis], *m_Storage.pDevice, m_Memory );
m_Weights[iUsedVecs[iThis]] = W1;
// go through previous residual vectors and form the dot products with them
FDiisVector
ResDot(nDim);
TR.CalcResidualDots( ResDot.data(), ResRecs, nDim, iThis,
*m_Storage.pDevice, m_Memory );
ResDot[iThis] = fThisResidualDot;
// update resident error matrix with new residual-dots
for ( uint i = 0; i < nDim; ++ i ) {
m_ErrorMatrix(iUsedVecs[i], iUsedVecs[iThis]) = ResDot[i];
m_ErrorMatrix(iUsedVecs[iThis], iUsedVecs[i]) = ResDot[i];
}
// build actual DIIS system for the subspace used.
FDiisVector
Rhs(nDim+1),
Coeffs(nDim+1);
FDiisMatrix
B(nDim+1, nDim+1);
// Factor out common size scales from the residual dots.
// This is done to increase numerical stability for the case when _all_
// residuals are very small.
for ( uint nRow = 0; nRow < nDim; ++ nRow )
for ( uint nCol = 0; nCol < nDim; ++ nCol )
B(nRow, nCol) = m_ErrorMatrix(iUsedVecs[nRow], iUsedVecs[nCol])/fBaseScale;
// make Lagrange/constraint lines.
for ( uint i = 0; i < nDim; ++ i ) {
B(i, nDim) = -m_Weights[iUsedVecs[i]];
B(nDim, i) = -m_Weights[iUsedVecs[i]];
Rhs[i] = 0.0;
}
B(nDim, nDim) = 0.0;
Rhs[nDim] = -W1;
// invert the system, determine extrapolation coefficients.
LinearSolveSymSvd( Coeffs.data(), B.data(), nDim+1, Rhs.data(), nDim+1, 1.0e-10, m_Memory );
// Find a storage place for the vector in the next round. Either
// an empty slot or the oldest vector.
uint iOldestAge = m_iVectorAge[0];
m_iNext = 0;
for ( uint i = nMaxDim(); i != 0; -- i ){
if ( iOldestAge <= m_iVectorAge[i-1] ) {
iOldestAge = m_iVectorAge[i-1];
m_iNext = i-1;
}
}
// bool
// PrintDiisState = true;
// if ( PrintDiisState ) {
// std::ostream &xout = std::cout;
// xout << " iUsedVecs: "; for ( uint i = 0; i < nDim; ++ i ) xout << " " << iUsedVecs[i]; xout << std::endl;
// PrintMatrixGen( xout, m_ErrorMatrix.data(), nMaxDim(), 1, nMaxDim(), m_ErrorMatrix.nStride(), "DIIS-B (resident)" );
// PrintMatrixGen( xout, B.data(), nDim+1, 1, nDim+1, B.nStride(), "DIIS-B/I" );
// PrintMatrixGen( xout, Rhs.data(), 1, 1, nDim+1, 1, "DIIS-Rhs" );
// PrintMatrixGen( xout, Coeffs.data(), 1, 1, nDim+1, 1, "DIIS-C" );
// xout << std::endl;
// }
// now actually perform the extrapolation on the residuals
// and amplitudes.
m_LastAmplitudeCoeff = Coeffs[iThis];
TR.InterpolateFrom( Coeffs[iThis], Coeffs.data(), ResRecs, AmpRecs,
nDim, iThis, *m_Storage.pDevice, m_Memory );
// done.
// assert_rt( m_Memory.IsOnTop(pTopOfStack) );
m_Memory.Free(pTopOfStack);
};
// convenience function to run DIIS on a block set in memory.
// pOth: set of amplitudes to extrapolate, but not to include in the
// DIIS system itself.
void FDiisState::operator() ( FScalar *pAmp, size_t nAmpSize, FScalar *pRes,
size_t nResSize, FScalar *pOth, size_t nOthSize )
{
if ( nResSize == static_cast<size_t>(-1) )
nResSize = nAmpSize;
FDiisTargetMemoryBlockSet
TR(pAmp, nAmpSize, pRes, nResSize);
if ( pOth != 0 )
TR.AddAmpBlock(pOth, nOthSize);
PerformDiis(TR);
};
FDiisTarget::~FDiisTarget()
{
};
void FDiisTarget::Prepare()
{
};
void FDiisTarget::Finish()
{
};
FDiisTargetMemoryBlockSet::~FDiisTargetMemoryBlockSet()
{
};
FStreamSize FDiisTargetMemoryBlockSet::nBlockSetLength( FMemoryBlockSet const &BlockSet )
{
FStreamSize
r = 0;
FMemoryBlockSet::const_iterator
itBlock;
_for_each( itBlock, BlockSet )
r += itBlock->nSize;
return sizeof(FScalar) * r;
}
FStreamSize FDiisTargetMemoryBlockSet::nResidualLength(){
return nBlockSetLength( m_ResBlocks );
};
FStreamSize FDiisTargetMemoryBlockSet::nAmplitudeLength(){
return nBlockSetLength( m_AmpBlocks );
};
FScalar FDiisTargetMemoryBlockSet::OwnResidualDot()
{
FScalar
r = 0;
FMemoryBlockSet::const_iterator
itBlock;
_for_each( itBlock, m_ResBlocks )
r += Dot( itBlock->pData, itBlock->pData, itBlock->nSize );
return r;
}
template<class FScalar>
void FileAndMemOp( FFileAndMemOp Op, FScalar &f, FMemoryBlock *pMemBlocks,
std::size_t nMemBlocks, FStorageBlock const &Rec_,
FMemoryStack &Temp )
{
FStorageBlock
Rec( Rec_ );
FScalar
f2 = 0.0;
for ( uint iBlock = 0; iBlock < nMemBlocks; ++ iBlock ){
//xout << "FM-OP: " << Op << " " << Rec.Record.iRecord << fmt::ff(f,14,6) << " off " << fmt::fi(Rec.Record.BaseOffset,10) << " len" << fmt::fi(sizeof(FScalar) * pMemBlocks->nSize,10) << std::endl;
if ( Op == OP_WriteFile ) {
Rec.pDevice->Write( Rec.Record, pMemBlocks->pData,
sizeof(FScalar) * pMemBlocks->nSize );
} else {
FileAndMemOp( Op, f, pMemBlocks->pData, pMemBlocks->nSize,
Rec, Temp );
if ( Op == OP_Dot ){
f += f2;
f2 = f;
}
}
Rec.Record.BaseOffset += sizeof(FScalar) * pMemBlocks->nSize;
++ pMemBlocks;
};
};
void FDiisTargetMemoryBlockSet::SerializeTo( FRecord const &ResidualRec,
FRecord const &AmplitudeRec, FStorageDevice const &Device, FMemoryStack &Memory )
{
FScalar
f = 1.0;
FileAndMemOp( OP_WriteFile, f, &m_ResBlocks[0], m_ResBlocks.size(),
FStorageBlock(Device,ResidualRec), Memory );
FileAndMemOp( OP_WriteFile, f, &m_AmpBlocks[0], m_AmpBlocks.size(),
FStorageBlock(Device,AmplitudeRec), Memory );
}
// another evil hack... FileAndMemOp always takes non-const, since some
// operations actually change the record contents.
static inline FStorageBlock StorageBlockFromConst( FStorageDevice const &Device,
FStorageDevice::FRecord const &Record )
{
return FStorageBlock( const_cast<FStorageDevice&>( Device ),
const_cast<FStorageDevice::FRecord&>( Record ) );
}
void FDiisTargetMemoryBlockSet::CalcResidualDots( FScalar Out[],
FRecord const Res[], uint nVectors, uint iSkip,
FStorageDevice const &Device, FMemoryStack &Memory )
{
for ( uint iVec = 0; iVec < nVectors; ++ iVec )
{
if ( iVec == iSkip )
continue;
FileAndMemOp( OP_Dot, Out[iVec], &m_ResBlocks[0], m_ResBlocks.size(),
StorageBlockFromConst(Device,Res[iVec]), Memory );
}
};
void FDiisTargetMemoryBlockSet::InterpolateBlockSet( FMemoryBlockSet &BlockSet,
FScalar fOwnCoeff, FScalar const Coeffs[], FRecord const Vecs[],
uint nVectors, uint iSkip, FStorageDevice const &Device, FMemoryStack &Memory )
{
// scale this vector with given coefficient
FMemoryBlockSet::const_iterator
itBlock;
_for_each( itBlock, BlockSet )
Scale( itBlock->pData, fOwnCoeff, itBlock->nSize );
// add scaled other vectors to current one.
for ( uint iVec = 0; iVec < nVectors; ++ iVec )
{
if ( iVec == iSkip )
continue;
FScalar
Ci = Coeffs[iVec];
if ( Ci == 0.0 )
continue;
FileAndMemOp( OP_AddToMem, Ci, &BlockSet[0], BlockSet.size(),
StorageBlockFromConst(Device,Vecs[iVec]), Memory );
}
};
void FDiisTargetMemoryBlockSet::InterpolateFrom( FScalar fOwnCoeff, FScalar const Coeffs[],
FRecord const Res[], FRecord const Amps[], uint nVectors, uint iSkip,
FStorageDevice const &Device, FMemoryStack &Memory )
{
InterpolateBlockSet( m_AmpBlocks, fOwnCoeff, Coeffs, Amps, nVectors, iSkip, Device, Memory );
InterpolateBlockSet( m_ResBlocks, fOwnCoeff, Coeffs, Res, nVectors, iSkip, Device, Memory );
};
} // namespace ct
// kate: space-indent on; tab-indent on; backspace-indent on; tab-width 4; indent-width 4; mixedindent off; indent-mode normal;
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "Gutzwiller.h"
#include "Correlator.h"
#include "Determinants.h"
#include <boost/container/static_vector.hpp>
#include <fstream>
#include "input.h"
using namespace Eigen;
Gutzwiller::Gutzwiller () {
//g = (VectorXd::Constant(Determinant::norbs, 1.0) + VectorXd::Random(Determinant::norbs))/20;
int norbs = Determinant::norbs;
g = VectorXd::Constant(Determinant::norbs, 1.);
bool readGutz = false;
char file[5000];
sprintf(file, "Gutzwiller.txt");
ifstream ofile(file);
if (ofile)
readGutz = true;
if (readGutz) {
for (int i = 0; i < norbs; i++) {
ofile >> g(i);
}
}
};
double Gutzwiller::Overlap(const Determinant &d) const
{
int norbs = Determinant::norbs;
double ovlp = 1.0;
for (int i = 0; i < norbs; i++) {
if (d.getoccA(i) && d.getoccB(i)) ovlp *= g(i);
}
return ovlp;
}
double Gutzwiller::OverlapRatio (const Determinant &d1, const Determinant &d2) const {
return Overlap(d1)/Overlap(d2);
}
double Gutzwiller::OverlapRatio(int i, int a, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
double Gutzwiller::OverlapRatio(int i, int j, int a, int b, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
void Gutzwiller::OverlapWithGradient(const Determinant& d,
Eigen::VectorBlock<VectorXd>& grad,
const double& ovlp) const {
if (schd.optimizeCps) {
int norbs = Determinant::norbs;
for (int i = 0; i < norbs; i++) {
if (d.getoccA(i) && d.getoccB(i)) grad[i] = 1/g(i);
}
}
}
long Gutzwiller::getNumVariables() const
{
return Determinant::norbs;
}
void Gutzwiller::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
for (int i = 0; i < Determinant::norbs; i++)
v[i] = g[i];
}
void Gutzwiller::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
for (int i = 0; i < Determinant::norbs; i++)
g[i] = v[i];
}
void Gutzwiller::printVariables() const
{
cout << "Gutzwiller"<< endl;
//for (int i=0; i<SpinCorrelator.rows(); i++)
// for (int j=0; j<=i; j++)
// cout << SpinCorrelator(i,j);
cout << g << endl << endl;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PermutedTRWavefunction_HEADER_H
#define PermutedTRWavefunction_HEADER_H
#include "TRWavefunction.h"
#include "PermutedTRWalker.h"
/**
*/
struct PermutedTRWavefunction {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & wave
& permutations
& numP
& characters;
}
public:
using CorrType = Jastrow;
using ReferenceType = Slater;
TRWavefunction wave;
MatrixXd permutations; // rows contain permutations except identity
int numP; // number of permutations not including identity
VectorXd characters;
// default constructor
PermutedTRWavefunction() {
wave = TRWavefunction();
numP = schd.numPermutations;
characters = VectorXd::Zero(numP);
int norbs = Determinant::norbs;
permutations = MatrixXd::Zero(numP, norbs);
ifstream dump("permutations.txt");
if (dump) {
for (int i = 0; i < numP; i++) {
dump >> characters(i);
for (int j = 0; j < norbs; j++) dump >> permutations(i, j);
}
}
else {
if (commrank == 0) cout << "permutations.txt not found!\n";
exit(0);
}
};
Slater& getRef() { return wave.getRef(); }
Jastrow& getCorr() { return wave.getCorr(); }
// used at the start of each sampling run
void initWalker(PermutedTRWalker &walk)
{
walk = PermutedTRWalker(getCorr(), getRef(), permutations);
}
// used in deterministic calculations
void initWalker(PermutedTRWalker &walk, Determinant &d)
{
walk = PermutedTRWalker(getCorr(), getRef(), d, permutations);
}
// used in rdm calculations
double Overlap(const PermutedTRWalker &walk) const
{
double overlap = wave.Overlap(walk.walkerVec[0]);
for (int i = 0; i < numP; i++) {
overlap += characters(i) * wave.Overlap(walk.walkerVec[i+1]);
}
return overlap;
}
// used in HamAndOvlp below
double Overlap(const PermutedTRWalker &walk, vector<double> &overlaps) const
{
overlaps.resize(numP+1, 0.);
double totalOverlap = 0.;
overlaps[0] = wave.Overlap(walk.walkerVec[0]);
totalOverlap += overlaps[0];
for (int i = 0; i < numP; i++) {
overlaps[i+1] = characters(i) * wave.Overlap(walk.walkerVec[i+1]);
totalOverlap += overlaps[i+1];
}
return totalOverlap;
}
// used in rdm calculations
double getOverlapFactor(int i, int a, const PermutedTRWalker& walk, bool doparity) const
{
vector<double> overlaps;
double totalOverlap = Overlap(walk, overlaps);
double numerator = wave.getOverlapFactor(i, a, walk.walkerVec[0], doparity) * overlaps[0];
int norbs = Determinant::norbs;
for (int n = 0; n < numP; n++) {
int ip = 2 * permutations(n, i/2) + i%2;
int ap = 2 * permutations(n, a/2) + a%2;
numerator += wave.getOverlapFactor(ip, ap, walk.walkerVec[n+1], doparity) * overlaps[n+1];
}
return numerator / totalOverlap;
}
// used in rdm calculations
double getOverlapFactor(int I, int J, int A, int B, const PermutedTRWalker& walk, bool doparity) const
{
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, doparity);
vector<double> overlaps;
double totalOverlap = Overlap(walk, overlaps);
double numerator = wave.getOverlapFactor(I, J, A, B, walk.walkerVec[0], doparity) * overlaps[0];
int norbs = Determinant::norbs;
for (int n = 0; n < numP; n++) {
int ip = 2 * permutations(n, I/2) + I%2;
int ap = 2 * permutations(n, A/2) + A%2;
int jp = 2 * permutations(n, J/2) + J%2;
int bp = 2 * permutations(n, B/2) + B%2;
numerator += wave.getOverlapFactor(ip, jp, ap, bp, walk.walkerVec[n+1], doparity) * overlaps[n+1];
}
return numerator / totalOverlap;
}
double getOverlapFactor(int i, int a, const PermutedTRWalker& walk, vector<double>& overlaps, double& totalOverlap, bool doparity) const
{
//double parity_n = walk.walkerVec[0].d.parity(a/2, i/2, i%2);
//double numerator = parity_n * wave.getOverlapFactor(i, a, walk.walkerVec[0], doparity) * overlaps[0];
double numerator = wave.getOverlapFactor(i, a, walk.walkerVec[0], doparity) * overlaps[0];
int norbs = Determinant::norbs;
for (int n = 0; n < numP; n++) {
int ip = 2 * permutations(n, i/2) + i%2;
int ap = 2 * permutations(n, a/2) + a%2;
//double parity_np = walk.walkerVec[n+1].d.parity(ap/2, ip/2, ip%2);
//numerator += parity_np * wave.getOverlapFactor(ip, ap, walk.walkerVec[n+1], doparity) * overlaps[n+1];
numerator += wave.getOverlapFactor(ip, ap, walk.walkerVec[n+1], doparity) * overlaps[n+1];
}
return numerator / totalOverlap;
}
// used in HamAndOvlp below
double getOverlapFactor(int I, int J, int A, int B, const PermutedTRWalker& walk, vector<double>& overlaps, double& totalOverlap, bool doparity) const
{
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, overlaps, totalOverlap, doparity);
double numerator = wave.getOverlapFactor(I, J, A, B, walk.walkerVec[0], doparity) * overlaps[0];
int norbs = Determinant::norbs;
for (int n = 0; n < numP; n++) {
int ip = 2 * permutations(n, I/2) + I%2;
int ap = 2 * permutations(n, A/2) + A%2;
int jp = 2 * permutations(n, J/2) + J%2;
int bp = 2 * permutations(n, B/2) + B%2;
numerator += wave.getOverlapFactor(ip, jp, ap, bp, walk.walkerVec[n+1], doparity) * overlaps[n+1];
}
return numerator / totalOverlap;
}
// gradient overlap ratio, used during sampling
// just calls OverlapWithGradient on the last wave function
void OverlapWithGradient(const PermutedTRWalker &walk,
double &factor,
Eigen::VectorXd &grad) const
{
vector<double> overlaps;
double totalOverlap = Overlap(walk, overlaps);
VectorXd grad_i = 0. * grad;
wave.OverlapWithGradient(walk.walkerVec[0], factor, grad_i);
grad += (grad_i * overlaps[0]) / totalOverlap;
for (int i = 0; i < numP; i++) {
grad_i = 0. * grad;
wave.OverlapWithGradient(walk.walkerVec[i+1], factor, grad_i);
grad += (grad_i * overlaps[i+1]) / totalOverlap;
}
}
void printVariables() const
{
wave.printVariables();
}
// update after vmc optimization
// updates the wave function helpers as well
void updateVariables(Eigen::VectorXd &v)
{
wave.updateVariables(v);
}
void getVariables(Eigen::VectorXd &v) const
{
wave.getVariables(v);
}
long getNumVariables() const
{
return wave.getNumVariables();
}
string getfileName() const {
return "PermutedTRWavefunction";
}
void writeWave() const
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
//if (commrank == 0)
//{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
//}
#ifndef SERIAL
//boost::mpi::communicator world;
//boost::mpi::broadcast(world, *this, 0);
#endif
}
// calculates local energy and overlap
// used directly during sampling
void HamAndOvlp(const PermutedTRWalker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true, double epsilon = schd.epsilon) const
{
int norbs = Determinant::norbs;
vector<double> overlaps;
ovlp = Overlap(walk, overlaps);
if (schd.debug) {
cout << "overlaps\n";
for (int i = 0; i <overlaps.size(); i++) cout << overlaps[i] << " ";
cout << endl;
}
ham = walk.walkerVec[0].d.Energy(I1, I2, coreE);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.walkerVec[0].d, epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.walkerVec[0].d, epsilon, schd.screen,
work, false);
//loop over all the screened excitations
if (schd.debug) {
cout << "eloc excitations" << endl;
cout << "phi0 d.energy" << ham << endl;
}
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double ovlpRatio = getOverlapFactor(I, J, A, B, walk, overlaps, ovlp, false);
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, dbig, dbigcopy, false);
ham += tia * ovlpRatio;
if (schd.debug) cout << ex1 << " " << ex2 << " tia " << tia << " ovlpRatio " << ovlpRatio << endl;
work.ovlpRatio[i] = ovlpRatio;
}
if (schd.debug) cout << endl;
}
void HamAndOvlpLanczos(const PermutedTRWalker &walk,
Eigen::VectorXd &lanczosCoeffsSample,
double &ovlpSample,
workingArray& work,
workingArray& moreWork, double &alpha)
{
work.setCounterToZero();
int norbs = Determinant::norbs;
double el0 = 0., el1 = 0., ovlp0 = 0., ovlp1 = 0.;
HamAndOvlp(walk, ovlp0, el0, work, true, schd.lanczosEpsilon);
std::vector<double> ovlp{0., 0., 0.};
ovlp[0] = ovlp0;
ovlp[1] = el0 * ovlp0;
ovlp[2] = ovlp[0] + alpha * ovlp[1];
lanczosCoeffsSample[0] = ovlp[0] * ovlp[0] * el0 / (ovlp[2] * ovlp[2]);
lanczosCoeffsSample[1] = ovlp[0] * ovlp[1] * el0 / (ovlp[2] * ovlp[2]);
el1 = walk.walkerVec[0].d.Energy(I1, I2, coreE);
//if (schd.debug) cout << "phi1 d.energy " << el1 << endl;
//workingArray work1;
//cout << "E0 " << el1 << endl;
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
PermutedTRWalker walkCopy = walk;
walkCopy.updateWalker(getRef(), getCorr(), work.excitation1[i], work.excitation2[i], false);
moreWork.setCounterToZero();
HamAndOvlp(walkCopy, ovlp0, el0, moreWork, true, schd.lanczosEpsilon);
ovlp1 = el0 * ovlp0;
el1 += tia * ovlp1 / ovlp[1];
work.ovlpRatio[i] = (ovlp0 + alpha * ovlp1) / ovlp[2];
//if (schd.debug) cout << work.excitation1[i] << " " << work.excitation2[i] << " tia " << tia << " ovlpRatio " << ovlp1 / ovlp[1] << endl;
}
//if (schd.debug) cout << endl;
lanczosCoeffsSample[2] = ovlp[1] * ovlp[1] * el1 / (ovlp[2] * ovlp[2]);
lanczosCoeffsSample[3] = ovlp[0] * ovlp[0] / (ovlp[2] * ovlp[2]);
ovlpSample = ovlp[2];
}
};
#endif
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HFWalker_HEADER_H
#define HFWalker_HEADER_H
#include "Determinants.h"
#include "WalkerHelper.h"
#include <array>
#include "igl/slice.h"
#include "igl/slice_into.h"
#include "Slater.h"
#include "MultiSlater.h"
#include "AGP.h"
#include "Pfaffian.h"
#include <unordered_set>
using namespace Eigen;
/**
* Is essentially a single determinant used in the VMC/DMC simulation
* At each step in VMC one need to be able to calculate the following
* quantities
* a. The local energy = <walker|H|Psi>/<walker|Psi>
* b. The gradient = <walker|H|Psi_t>/<walker/Psi>
* c. The update = <walker'|Psi>/<walker|Psi>
*
* To calculate these efficiently the walker uses the HFWalkerHelper class
*
**/
template<typename Corr, typename Reference>
struct Walker { };
template<typename Corr>
struct Walker<Corr, Slater> {
Determinant d;
WalkerHelper<Corr> corrHelper;
WalkerHelper<Slater> refHelper;
unordered_set<int> excitedHoles; //spin orbital indices of excited electrons (in core orbitals) in d
unordered_set<int> excitedOrbs; //spin orbital indices of excited electrons (in virtual orbitals) in d
Walker() {};
Walker(Corr &corr, const Slater &ref)
{
initDet(ref.getHforbsA().real(), ref.getHforbsB().real());
refHelper = WalkerHelper<Slater>(ref, d);
corrHelper = WalkerHelper<Corr>(corr, d);
}
template<typename Wave>
Walker(Wave &wave, const Determinant &pd)
{
d = pd;
refHelper = WalkerHelper<Slater>(wave.ref, pd);
corrHelper = WalkerHelper<Corr>(wave.corr, pd);
}
Walker(Corr &corr, const Slater &ref, const Determinant &pd) : d(pd), refHelper(ref, pd), corrHelper(corr, pd) {};
Determinant& getDet() {return d;}
void readBestDeterminant(Determinant& d) const
{
if (commrank == 0) {
char file[5000];
sprintf(file, "BestDeterminant.txt");
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> d;
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
/**
* makes det based on mo coeffs
*/
void guessBestDeterminant(Determinant& d, const Eigen::MatrixXd& HforbsA, const Eigen::MatrixXd& HforbsB) const
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
d = Determinant();
if (boost::iequals(schd.determinantFile, "")) {
for (int i = 0; i < nalpha; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j = 0; j < norbs; j++) {
if (abs(HforbsA(i, j)) > maxovlp && !d.getoccA(j)) {
maxovlp = abs(HforbsA(i, j));
bestorb = j;
}
}
d.setoccA(bestorb, true);
}
for (int i = 0; i < nbeta; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j = 0; j < norbs; j++) {
if (schd.hf == "rhf" || schd.hf == "uhf") {
if (abs(HforbsB(i, j)) > maxovlp && !d.getoccB(j)) {
bestorb = j;
maxovlp = abs(HforbsB(i, j));
}
}
else {
if (abs(HforbsB(i+norbs, j)) > maxovlp && !d.getoccB(j)) {
bestorb = j;
maxovlp = abs(HforbsB(i+norbs, j));
}
}
}
d.setoccB(bestorb, true);
}
}
else if (boost::iequals(schd.determinantFile, "bestDet")) {
std::vector<Determinant> dets;
std::vector<double> ci;
readDeterminants(schd.determinantFile, dets, ci);
d = dets[0];
}
}
void initDet(const MatrixXd& HforbsA, const MatrixXd& HforbsB)
{
bool readDeterminant = false;
char file[5000];
sprintf(file, "BestDeterminant.txt");
{
ifstream ofile(file);
if (ofile)
readDeterminant = true;
}
if (readDeterminant)
readBestDeterminant(d);
else
guessBestDeterminant(d, HforbsA, HforbsB);
}
double getIndividualDetOverlap(int i) const
{
return (refHelper.thetaDet[i][0] * refHelper.thetaDet[i][1]).real();
}
double getDetOverlap(const Slater &ref) const
{
double ovlp = 0.0;
for (int i = 0; i < refHelper.thetaDet.size(); i++) {
ovlp += ref.getciExpansion()[i] * (refHelper.thetaDet[i][0] * refHelper.thetaDet[i][1]).real();
}
return ovlp;
}
double getDetFactor(int i, int a, const Slater &ref) const
{
if (i % 2 == 0)
return getDetFactor(i / 2, a / 2, 0, ref);
else
return getDetFactor(i / 2, a / 2, 1, ref);
}
double getDetFactor(int I, int J, int A, int B, const Slater &ref) const
{
if (I % 2 == J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 0, ref);
else if (I % 2 == J % 2 && I % 2 == 1)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 1, ref);
else if (I % 2 != J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 1, ref);
else
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 0, ref);
}
double getDetFactor(int i, int a, bool sz, const Slater &ref) const
{
int tableIndexi, tableIndexa;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz);
double detFactorNum = 0.0;
double detFactorDen = 0.0;
for (int j = 0; j < ref.getDeterminants().size(); j++)
{
double factor = (refHelper.rTable[j][sz](tableIndexa, tableIndexi) * refHelper.thetaDet[j][0] * refHelper.thetaDet[j][1]).real() * ref.getciExpansion()[j] / getDetOverlap(ref);
detFactorNum += ref.getciExpansion()[j] * factor * (refHelper.thetaDet[j][0] * refHelper.thetaDet[j][1]).real();
detFactorDen += ref.getciExpansion()[j] * (refHelper.thetaDet[j][0] * refHelper.thetaDet[j][1]).real();
}
return detFactorNum / detFactorDen;
}
double getDetFactor(int i, int j, int a, int b, bool sz1, bool sz2, const Slater &ref) const
{
int tableIndexi, tableIndexa, tableIndexj, tableIndexb;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz1);
refHelper.getRelIndices(j, tableIndexj, b, tableIndexb, sz2) ;
double detFactorNum = 0.0;
double detFactorDen = 0.0;
for (int j = 0; j < ref.getDeterminants().size(); j++)
{
double factor;
if (sz1 == sz2 || refHelper.hftype == 2)
factor =((refHelper.rTable[j][sz1](tableIndexa, tableIndexi) * refHelper.rTable[j][sz1](tableIndexb, tableIndexj)
- refHelper.rTable[j][sz1](tableIndexb, tableIndexi) *refHelper.rTable[j][sz1](tableIndexa, tableIndexj)) * refHelper.thetaDet[j][0] * refHelper.thetaDet[j][1]).real() * ref.getciExpansion()[j]/ getDetOverlap(ref);
else
factor = (refHelper.rTable[j][sz1](tableIndexa, tableIndexi) * refHelper.rTable[j][sz2](tableIndexb, tableIndexj) * refHelper.thetaDet[j][0] * refHelper.thetaDet[j][1]).real() * ref.getciExpansion()[j]/ getDetOverlap(ref);
detFactorNum += ref.getciExpansion()[j] * factor * (refHelper.thetaDet[j][0] * refHelper.thetaDet[j][1]).real();
detFactorDen += ref.getciExpansion()[j] * (refHelper.thetaDet[j][0] * refHelper.thetaDet[j][1]).real();
}
return detFactorNum / detFactorDen;
}
//only works for ghf
double getDetFactor(std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to) const
{
if (from[0].size() + from[1].size() == 0) return 1.;
int numExc = from[0].size() + from[1].size();
VectorXi tableIndicesRow = VectorXi::Zero(from[0].size() + from[1].size());
VectorXi tableIndicesCol = VectorXi::Zero(from[0].size() + from[1].size());
Determinant dcopy = d;
double parity = 1.;
int count = 0;
for (int sz = 0; sz < 2; sz++) {//iterate over spins
auto itFrom = from[sz].begin();
auto itTo = to[sz].begin();
for (int n = 0; n < from[sz].size(); n++) {//iterate over excitations
int i = *itFrom, a = *itTo;
itFrom = std::next(itFrom); itTo = std::next(itTo);
refHelper.getRelIndices(i, tableIndicesCol(count), a, tableIndicesRow(count), sz);
count++;
parity *= dcopy.parity(a, i, sz);
dcopy.setocc(i, sz, false);
dcopy.setocc(a, sz, true);
}
}
MatrixXcd detSlice = MatrixXcd::Zero(numExc,numExc);
igl::slice(refHelper.rTable[0][0], tableIndicesRow, tableIndicesCol, detSlice);
complex<double> det(0.,0.);
if (detSlice.rows() == 1) det = detSlice(0, 0);
else if (detSlice.rows() == 2) det = detSlice(0, 0) * detSlice(1, 1) - detSlice(0, 1) * detSlice(1, 0);
else if (detSlice.rows() == 3) det = detSlice(0, 0) * (detSlice(1, 1) * detSlice(2, 2) - detSlice(1, 2) * detSlice(2, 1))
- detSlice(0, 1) * (detSlice(1, 0) * detSlice(2, 2) - detSlice(1, 2) * detSlice(2, 0))
+ detSlice(0, 2) * (detSlice(1, 0) * detSlice(2, 1) - detSlice(1, 1) * detSlice(2, 0));
else if (detSlice.rows() == 4) det = detSlice(0,3) * detSlice(1,2) * detSlice(2,1) * detSlice(3,0) - detSlice(0,2) * detSlice(1,3) * detSlice(2,1) * detSlice(3,0) -
detSlice(0,3) * detSlice(1,1) * detSlice(2,2) * detSlice(3,0) + detSlice(0,1) * detSlice(1,3) * detSlice(2,2) * detSlice(3,0) +
detSlice(0,2) * detSlice(1,1) * detSlice(2,3) * detSlice(3,0) - detSlice(0,1) * detSlice(1,2) * detSlice(2,3) * detSlice(3,0) -
detSlice(0,3) * detSlice(1,2) * detSlice(2,0) * detSlice(3,1) + detSlice(0,2) * detSlice(1,3) * detSlice(2,0) * detSlice(3,1) +
detSlice(0,3) * detSlice(1,0) * detSlice(2,2) * detSlice(3,1) - detSlice(0,0) * detSlice(1,3) * detSlice(2,2) * detSlice(3,1) -
detSlice(0,2) * detSlice(1,0) * detSlice(2,3) * detSlice(3,1) + detSlice(0,0) * detSlice(1,2) * detSlice(2,3) * detSlice(3,1) +
detSlice(0,3) * detSlice(1,1) * detSlice(2,0) * detSlice(3,2) - detSlice(0,1) * detSlice(1,3) * detSlice(2,0) * detSlice(3,2) -
detSlice(0,3) * detSlice(1,0) * detSlice(2,1) * detSlice(3,2) + detSlice(0,0) * detSlice(1,3) * detSlice(2,1) * detSlice(3,2) +
detSlice(0,1) * detSlice(1,0) * detSlice(2,3) * detSlice(3,2) - detSlice(0,0) * detSlice(1,1) * detSlice(2,3) * detSlice(3,2) -
detSlice(0,2) * detSlice(1,1) * detSlice(2,0) * detSlice(3,3) + detSlice(0,1) * detSlice(1,2) * detSlice(2,0) * detSlice(3,3) +
detSlice(0,2) * detSlice(1,0) * detSlice(2,1) * detSlice(3,3) - detSlice(0,0) * detSlice(1,2) * detSlice(2,1) * detSlice(3,3) -
detSlice(0,1) * detSlice(1,0) * detSlice(2,2) * detSlice(3,3) + detSlice(0,0) * detSlice(1,1) * detSlice(2,2) * detSlice(3,3);
//complex<double> det = detSlice.determinant();
double num = (det * refHelper.thetaDet[0][0] * refHelper.thetaDet[0][1]).real();
double den = (refHelper.thetaDet[0][0] * refHelper.thetaDet[0][1]).real();
return parity * num / den;
}
void update(int i, int a, bool sz, const Slater &ref, Corr &corr, bool doparity = true)
{
double p = 1.0;
if (doparity) p *= d.parity(a, i, sz);
d.setocc(i, sz, false);
d.setocc(a, sz, true);
if (refHelper.hftype == Generalized) {
int norbs = Determinant::norbs;
vector<int> cre{ a + sz * norbs }, des{ i + sz * norbs };
refHelper.excitationUpdateGhf(ref, cre, des, sz, p, d);
}
else
{
vector<int> cre{ a }, des{ i };
refHelper.excitationUpdate(ref, cre, des, sz, p, d);
}
corrHelper.updateHelper(corr, d, i, a, sz);
}
void update(int i, int j, int a, int b, bool sz, const Slater &ref, Corr& corr, bool doparity = true)
{
double p = 1.0;
Determinant dcopy = d;
if (doparity) p *= d.parity(a, i, sz);
d.setocc(i, sz, false);
d.setocc(a, sz, true);
if (doparity) p *= d.parity(b, j, sz);
d.setocc(j, sz, false);
d.setocc(b, sz, true);
if (refHelper.hftype == Generalized) {
int norbs = Determinant::norbs;
vector<int> cre{ a + sz * norbs, b + sz * norbs }, des{ i + sz * norbs, j + sz * norbs };
refHelper.excitationUpdateGhf(ref, cre, des, sz, p, d);
}
else {
vector<int> cre{ a, b }, des{ i, j };
refHelper.excitationUpdate(ref, cre, des, sz, p, d);
}
corrHelper.updateHelper(corr, d, i, j, a, b, sz);
}
void updateWalker(const Slater &ref, Corr& corr, int ex1, int ex2, bool doparity = true)
{
int norbs = Determinant::norbs;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
if (I % 2 == J % 2 && ex2 != 0) {
if (I % 2 == 1) {
update(I / 2, J / 2, A / 2, B / 2, 1, ref, corr, doparity);
}
else {
update(I / 2, J / 2, A / 2, B / 2, 0, ref, corr, doparity);
}
}
else {
if (I % 2 == 0)
update(I / 2, A / 2, 0, ref, corr, doparity);
else
update(I / 2, A / 2, 1, ref, corr, doparity);
if (ex2 != 0) {
if (J % 2 == 1) {
update(J / 2, B / 2, 1, ref, corr, doparity);
}
else {
update(J / 2, B / 2, 0, ref, corr, doparity);
}
}
}
}
void exciteWalker(const Slater &ref, Corr& corr, int excite1, int excite2, int norbs)
{
int I1 = excite1 / (2 * norbs), A1 = excite1 % (2 * norbs);
if (I1 % 2 == 0)
update(I1 / 2, A1 / 2, 0, ref, corr);
else
update(I1 / 2, A1 / 2, 1, ref, corr);
if (excite2 != 0) {
int I2 = excite2 / (2 * norbs), A2 = excite2 % (2 * norbs);
if (I2 % 2 == 0)
update(I2 / 2, A2 / 2, 0, ref, corr);
else
update(I2 / 2, A2 / 2, 1, ref, corr);
}
}
void OverlapWithOrbGradient(const Slater &ref, Eigen::VectorXd &grad, double detovlp) const
{
int norbs = Determinant::norbs;
Determinant walkerDet = d;
//K and L are relative row and col indices
int KA = 0, KB = 0;
for (int k = 0; k < norbs; k++) { //walker indices on the row
if (walkerDet.getoccA(k)) {
for (int det = 0; det < ref.getDeterminants().size(); det++) {
Determinant refDet = ref.getDeterminants()[det];
int L = 0;
for (int l = 0; l < norbs; l++) {
if (refDet.getoccA(l)) {
grad(2 * k * norbs + 2 * l) += ref.getciExpansion()[det] * (refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[det][0] * refHelper.thetaDet[det][1]).real() /detovlp;
grad(2 * k * norbs + 2 * l + 1) += ref.getciExpansion()[det] * (- refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[det][0] * refHelper.thetaDet[det][1]).imag() /detovlp;
L++;
}
}
}
KA++;
}
if (walkerDet.getoccB(k)) {
for (int det = 0; det < ref.getDeterminants().size(); det++) {
Determinant refDet = ref.getDeterminants()[det];
int L = 0;
for (int l = 0; l < norbs; l++) {
if (refDet.getoccB(l)) {
if (refHelper.hftype == UnRestricted) {
grad(2 * norbs * norbs + 2 * k * norbs + 2 * l) += ref.getciExpansion()[det] * (refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[det][0] * refHelper.thetaDet[det][1]).real() / detovlp;
grad(2 * norbs * norbs + 2 * k * norbs + 2 * l + 1) += ref.getciExpansion()[det] * (- refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[det][0] * refHelper.thetaDet[det][1]).imag() / detovlp;
}
else {
grad(2 * k * norbs + 2 * l) += ref.getciExpansion()[det] * (refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[det][0] * refHelper.thetaDet[det][1]).real() / detovlp;
grad(2 * k * norbs + 2 * l + 1) += ref.getciExpansion()[det] * (- refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[det][0] * refHelper.thetaDet[det][1]).imag() / detovlp;
}
L++;
}
}
}
KB++;
}
}
}
void OverlapWithOrbGradientGhf(const Slater &ref, Eigen::VectorXd &grad, double detovlp) const
{
int norbs = Determinant::norbs;
Determinant walkerDet = d;
Determinant refDet = ref.getDeterminants()[0];
//K and L are relative row and col indices
int K = 0;
for (int k = 0; k < norbs; k++) { //walker indices on the row
if (walkerDet.getoccA(k)) {
int L = 0;
for (int l = 0; l < norbs; l++) {
if (refDet.getoccA(l)) {
grad(4 * k * norbs + 2 * l) += (refHelper.thetaInv[0](L, K) * refHelper.thetaDet[0][0]).real() / detovlp;
grad(4 * k * norbs + 2 * l + 1) += (- refHelper.thetaInv[0](L, K) * refHelper.thetaDet[0][0]).imag() / detovlp;
L++;
}
}
for (int l = 0; l < norbs; l++) {
if (refDet.getoccB(l)) {
grad(4 * k * norbs + 2 * norbs + 2 * l) += (refHelper.thetaInv[0](L, K) * refHelper.thetaDet[0][0]).real() / detovlp;
grad(4 * k * norbs + 2 * norbs + 2 * l + 1) += (- refHelper.thetaInv[0](L, K) * refHelper.thetaDet[0][0]).imag() / detovlp;
L++;
}
}
K++;
}
}
for (int k = 0; k < norbs; k++) { //walker indices on the row
if (walkerDet.getoccB(k)) {
int L = 0;
for (int l = 0; l < norbs; l++) {
if (refDet.getoccA(l)) {
grad(4 * norbs * norbs + 4 * k * norbs + 2 * l) += (refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, K)).real() / detovlp;
grad(4 * norbs * norbs + 4 * k * norbs + 2 * l + 1) += (- refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, K)).imag() / detovlp;
L++;
}
}
for (int l = 0; l < norbs; l++) {
if (refDet.getoccB(l)) {
grad(4 * norbs * norbs + 4 * k * norbs + 2 * norbs + 2 * l) += (refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, K)).real() / detovlp;
grad(4 * norbs * norbs + 4 * k * norbs + 2 * norbs + 2 * l + 1) += (- refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, K)).imag() / detovlp;
L++;
}
}
K++;
}
}
}
void OverlapWithGradient(const Slater &ref, Eigen::VectorBlock<VectorXd> &grad) const
{
double detovlp = getDetOverlap(ref);
//for (int i = 0; i < ref.ciExpansion.size(); i++)
// grad[i] += getIndividualDetOverlap(i) / detovlp;
grad[0] = 0.;
if (ref.determinants.size() <= 1 && schd.optimizeOrbs) {
//if (hftype == UnRestricted)
VectorXd gradOrbitals;
if (ref.hftype == UnRestricted) {
gradOrbitals = VectorXd::Zero(4 * ref.HforbsA.rows() * ref.HforbsA.rows());
OverlapWithOrbGradient(ref, gradOrbitals, detovlp);
}
else {
gradOrbitals = VectorXd::Zero(2 * ref.HforbsA.rows() * ref.HforbsA.rows());
if (ref.hftype == Restricted) OverlapWithOrbGradient(ref, gradOrbitals, detovlp);
else OverlapWithOrbGradientGhf(ref, gradOrbitals, detovlp);
}
for (int i = 0; i < gradOrbitals.size(); i++)
grad[ref.ciExpansion.size() + i] += gradOrbitals[i];
}
//cout << "ref grad\n" << grad << endl;
}
friend ostream& operator<<(ostream& os, const Walker<Corr, Slater>& w) {
os << w.d << endl << endl;
os << "alphaTable\n" << w.refHelper.rTable[0][0] << endl << endl;
os << "betaTable\n" << w.refHelper.rTable[0][1] << endl << endl;
os << "dets\n" << w.refHelper.thetaDet[0][0] << " " << w.refHelper.thetaDet[0][1] << endl << endl;
os << "alphaInv\n" << w.refHelper.thetaInv[0] << endl << endl;
os << "betaInv\n" << w.refHelper.thetaInv[1] << endl << endl;
return os;
}
};
template<typename Corr>
struct Walker<Corr, MultiSlater> {
Determinant d;
WalkerHelper<Corr> corrHelper;
WalkerHelper<MultiSlater> refHelper;
unordered_set<int> excitedOrbs; //spin orbital indices of excited electrons (in virtual orbitals) in d
Walker() {};
Walker(Corr &corr, const MultiSlater &ref)
{
initDet();
refHelper = WalkerHelper<MultiSlater>(ref, d);
corrHelper = WalkerHelper<Corr>(corr, d);
}
Walker(Corr &corr, const MultiSlater &ref, const Determinant &pd) : d(pd), refHelper(ref, pd), corrHelper(corr, pd) {};
Determinant& getDet() {return d;}
void readBestDeterminant(Determinant& d) const
{
if (commrank == 0) {
char file[5000];
sprintf(file, "BestDeterminant.txt");
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> d;
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
/**
* makes det based on mo coeffs
*/
void guessBestDeterminant(Determinant& d) const
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
d = Determinant();
if (boost::iequals(schd.determinantFile, "")) {
// choose alpha occupations randomly
std::vector<int> bitmask(nalpha, 1);
bitmask.resize(norbs, 0); // N-K trailing 0's
vector<int> comb;
random_shuffle(bitmask.begin(), bitmask.end());
for (int i = 0; i < norbs; i++) {
if (bitmask[i] == 1) d.setoccA(i, true);
}
// fill beta, trying to avoid occupied alphas as much as possible
int nbetaFilled = 0;
// first pass, only fill empty orbs
for (int i = 0; i < norbs; i++) {
if (nbetaFilled == nbeta) break;
if (bitmask[i] == 0) { // empty
d.setoccB(i, true);
nbetaFilled++;
}
}
// if betas leftover, fill sequentially
if (nbetaFilled < nbeta) {
for (int i = 0; i < norbs; i++) {
if (nbetaFilled == nbeta) break;
if (bitmask[i] == 1) {// alpha occupied
d.setoccB(i, true);
nbetaFilled++;
}
}
}
}
else if (boost::iequals(schd.determinantFile, "bestDet")) {
std::vector<Determinant> dets;
std::vector<double> ci;
readDeterminants(schd.determinantFile, dets, ci);
d = dets[0];
}
}
void initDet()
{
bool readDeterminant = false;
char file[5000];
sprintf(file, "BestDeterminant.txt");
{
ifstream ofile(file);
if (ofile)
readDeterminant = true;
}
if (readDeterminant)
readBestDeterminant(d);
else
guessBestDeterminant(d);
}
double getIndividualDetOverlap(int i) const
{
return refHelper.ciOverlaps[i];
}
double getDetOverlap(const MultiSlater &ref) const
{
return refHelper.totalOverlap;
}
double getDetFactor(int i, int a, const MultiSlater &ref) const
{
if (i % 2 == 0)
return getDetFactor(i / 2, a / 2, 0, ref);
else
return getDetFactor(i / 2, a / 2, 1, ref);
}
double getDetFactor(int I, int J, int A, int B, const MultiSlater &ref) const
{
if (I % 2 == J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 0, ref);
else if (I % 2 == J % 2 && I % 2 == 1)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 1, ref);
else if (I % 2 != J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 1, ref);
else
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 0, ref);
}
double getDetFactor(int i, int a, bool sz, const MultiSlater &ref) const
{
int tableIndexi, tableIndexa;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz);
// make rt slice once, does not change with ci dets
complex<double> rtSlice = refHelper.rt(tableIndexa, tableIndexi);
VectorXi mCre(1); mCre << tableIndexa; // a
VectorXi mDes(1); mDes << tableIndexi; // i
// calculating < m | psi >
double overlap = ref.ciCoeffs[0] * (rtSlice * refHelper.refOverlap).real(); // c_0 Re < m | phi_0 >
// iterate over rest of ci expansion
for (int j = 1; j < ref.numDets; j++) {
// hand coding smaller cases to avoid slicing, and ensuing memory allocation costs
// psa: ugly code to follow
complex<double> detRatio;
if (ref.ciExcitations[j][0].size() == 1) {// 2x2 matrix
detRatio = rtSlice * refHelper.tc(ref.ciExcitations[j][0][0], ref.ciExcitations[j][1][0])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[j][1][0]) * refHelper.t(ref.ciExcitations[j][0][0], mDes[0]);
}
else if (ref.ciExcitations[j][0].size() == 2) {// 3x3 matrix
detRatio = rtSlice * refHelper.tc(ref.ciExcitations[j][0][0], ref.ciExcitations[j][1][0]) * refHelper.tc(ref.ciExcitations[j][0][1], ref.ciExcitations[j][1][1])
- rtSlice * refHelper.tc(ref.ciExcitations[j][0][0], ref.ciExcitations[j][1][1]) * refHelper.tc(ref.ciExcitations[j][0][1], ref.ciExcitations[j][1][0])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[j][1][0]) * refHelper.t(ref.ciExcitations[j][0][0], mDes[0]) * refHelper.tc(ref.ciExcitations[j][0][1], ref.ciExcitations[j][1][1])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[j][1][0]) * refHelper.tc(ref.ciExcitations[j][0][0], ref.ciExcitations[j][1][1]) * refHelper.t(ref.ciExcitations[j][0][1], mDes[0])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[j][1][1]) * refHelper.t(ref.ciExcitations[j][0][0], mDes[0]) * refHelper.tc(ref.ciExcitations[j][0][1], ref.ciExcitations[j][1][0])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[j][1][1]) * refHelper.tc(ref.ciExcitations[j][0][0], ref.ciExcitations[j][1][0]) * refHelper.t(ref.ciExcitations[j][0][1], mDes[0]);
}
else {// make a slice for bigger cases
//MatrixXcd rtc_bSlice, tSlice, tcSlice;
//igl::slice(refHelper.rtc_b, mCre, ref.ciExcitations[j][1], rtc_bSlice);
//igl::slice(refHelper.t, ref.ciExcitations[j][0], mDes, tSlice);
//igl::slice(refHelper.tc, ref.ciExcitations[j][0], ref.ciExcitations[j][1], tcSlice);
int rank = ref.ciExcitations[j][0].size();
MatrixXcd sliceMat = MatrixXcd::Zero(1 + rank, 1 + rank);
sliceMat(0, 0) = rtSlice;
for (int mu = 0; mu < rank; mu++) sliceMat(0, 1 + mu) = refHelper.rtc_b(mCre[0], ref.ciExcitations[j][1][mu]);
for (int mu = 0; mu < rank; mu++) sliceMat(1 + mu, 0) = refHelper.t(ref.ciExcitations[j][0][mu], mDes[0]);
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
sliceMat(1 + mu, 1+ nu) = refHelper.tc(ref.ciExcitations[j][0][mu], ref.ciExcitations[j][1][nu]);
//sliceMat.block(0, 1, 1, ref.ciExcitations[j][0].size()) = rtc_bSlice;
//sliceMat.block(1, 0, ref.ciExcitations[j][0].size(), 1) = tSlice;
//sliceMat.block(1, 1, ref.ciExcitations[j][0].size(), ref.ciExcitations[j][0].size()) = tcSlice;
//detRatio = calcDet(sliceMat);
detRatio = sliceMat.determinant();
}
overlap += ref.ciCoeffs[j] * ref.ciParity[j] * (detRatio * refHelper.refOverlap).real();
}
return overlap / refHelper.totalOverlap;
}
double getDetFactor(int i, int j, int a, int b, bool sz1, bool sz2, const MultiSlater &ref) const
{
int tableIndexi, tableIndexa, tableIndexj, tableIndexb;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz1);
refHelper.getRelIndices(j, tableIndexj, b, tableIndexb, sz2) ;
// make rt slice once, does not change with ci dets
VectorXi mCre(2); mCre << tableIndexa, tableIndexb;
VectorXi mDes(2); mDes << tableIndexi, tableIndexj;
MatrixXcd rtSlice;
igl::slice(refHelper.rt, mCre, mDes, rtSlice);
// calculating < m | psi >
//double overlap = ref.ciCoeffs[0] * (rtSlice.determinant() * refHelper.refOverlap).real(); // c_0 Re < m | phi_0 >
double overlap = ref.ciCoeffs[0] * (calcDet(rtSlice) * refHelper.refOverlap).real(); // c_0 Re < m | phi_0 >
// iterate over rest of ci expansion
for (int k = 1; k < ref.numDets; k++) {
complex<double> detRatio;
if (ref.ciExcitations[k][0].size() == 1) {// 3x3 det
detRatio = rtSlice(0, 0) * rtSlice(1, 1) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0])
- rtSlice(0, 0) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1])
- rtSlice(0, 1) * rtSlice(1, 0) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0])
+ rtSlice(0, 1) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * rtSlice(1, 0) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * rtSlice(1, 1) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0]);
}
else if (ref.ciExcitations[k][0].size() == 2) {// 4x4 det
detRatio = rtSlice(0, 0) * rtSlice(1, 1) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][1])
- rtSlice(0, 0) * rtSlice(1, 1) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][1]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][0])
- rtSlice(0, 0) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][1])
+ rtSlice(0, 0) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[1])
+ rtSlice(0, 0) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][0])
- rtSlice(0, 0) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][1]) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[1])
- rtSlice(0, 1) * rtSlice(1, 0) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][1])
+ rtSlice(0, 1) * rtSlice(1, 0) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][1]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][0])
+ rtSlice(0, 1) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][1])
- rtSlice(0, 1) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[0])
- rtSlice(0, 1) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][0])
+ rtSlice(0, 1) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][1]) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[0])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * rtSlice(1, 0) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][1])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * rtSlice(1, 0) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[1])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * rtSlice(1, 1) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][1])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * rtSlice(1, 1) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[0])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[1])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][0]) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][1]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[0])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][1]) * rtSlice(1, 0) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][0])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][1]) * rtSlice(1, 0) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[1])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][1]) * rtSlice(1, 1) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0]) * refHelper.tc(ref.ciExcitations[k][0][1], ref.ciExcitations[k][1][0])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][1]) * rtSlice(1, 1) * refHelper.tc(ref.ciExcitations[k][0][0], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[0])
- refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][1]) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[0]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[1])
+ refHelper.rtc_b(mCre[0], ref.ciExcitations[k][1][1]) * refHelper.rtc_b(mCre[1], ref.ciExcitations[k][1][0]) * refHelper.t(ref.ciExcitations[k][0][0], mDes[1]) * refHelper.t(ref.ciExcitations[k][0][1], mDes[0]);
}
else {// bigger cases
MatrixXcd rtc_bSlice, tSlice, tcSlice;
igl::slice(refHelper.rtc_b, mCre, ref.ciExcitations[k][1], rtc_bSlice);
igl::slice(refHelper.t, ref.ciExcitations[k][0], mDes, tSlice);
igl::slice(refHelper.tc, ref.ciExcitations[k][0], ref.ciExcitations[k][1], tcSlice);
MatrixXcd sliceMat = MatrixXcd::Zero(2 + ref.ciExcitations[k][0].size(), 2 + ref.ciExcitations[k][1].size());
sliceMat.block(0, 0, 2, 2) = rtSlice;
sliceMat.block(0, 2, 2, ref.ciExcitations[k][0].size()) = rtc_bSlice;
sliceMat.block(2, 0, ref.ciExcitations[k][0].size(), 2) = tSlice;
sliceMat.block(2, 2, ref.ciExcitations[k][0].size(), ref.ciExcitations[k][0].size()) = tcSlice;
//overlap += ref.ciCoeffs[k] * ref.ciParity[k] * (sliceMat.determinant() * refHelper.refOverlap).real();
detRatio = calcDet(sliceMat);
}
overlap += ref.ciCoeffs[k] * ref.ciParity[k] * (detRatio * refHelper.refOverlap).real();
}
return overlap / refHelper.totalOverlap;
}
// to be implemented for mrci/nevpt
double getDetFactor(std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to) const
{
return 0.;
}
void update(int i, int a, bool sz, const MultiSlater &ref, Corr &corr, bool doparity = true)
{
double p = 1.0;
if (doparity) p *= d.parity(a, i, sz);
d.setocc(i, sz, false);
d.setocc(a, sz, true);
int norbs = Determinant::norbs;
vector<int> cre{ a + sz * norbs }, des{ i + sz * norbs };
refHelper.excitationUpdate(ref, cre, des, sz, p, d);
corrHelper.updateHelper(corr, d, i, a, sz);
}
void update(int i, int j, int a, int b, bool sz, const MultiSlater &ref, Corr& corr, bool doparity = true)
{
double p = 1.0;
Determinant dcopy = d;
if (doparity) p *= d.parity(a, i, sz);
d.setocc(i, sz, false);
d.setocc(a, sz, true);
if (doparity) p *= d.parity(b, j, sz);
d.setocc(j, sz, false);
d.setocc(b, sz, true);
int norbs = Determinant::norbs;
vector<int> cre{ a + sz * norbs, b + sz * norbs }, des{ i + sz * norbs, j + sz * norbs };
refHelper.excitationUpdate(ref, cre, des, sz, p, d);
corrHelper.updateHelper(corr, d, i, j, a, b, sz);
}
void updateWalker(const MultiSlater &ref, Corr& corr, int ex1, int ex2, bool doparity = true)
{
int norbs = Determinant::norbs;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
if (I % 2 == J % 2 && ex2 != 0) {
if (I % 2 == 1) {
update(I / 2, J / 2, A / 2, B / 2, 1, ref, corr, doparity);
}
else {
update(I / 2, J / 2, A / 2, B / 2, 0, ref, corr, doparity);
}
}
else {
if (I % 2 == 0)
update(I / 2, A / 2, 0, ref, corr, doparity);
else
update(I / 2, A / 2, 1, ref, corr, doparity);
if (ex2 != 0) {
if (J % 2 == 1) {
update(J / 2, B / 2, 1, ref, corr, doparity);
}
else {
update(J / 2, B / 2, 0, ref, corr, doparity);
}
}
}
}
// not used
void exciteWalker(const MultiSlater &ref, Corr& corr, int excite1, int excite2, int norbs)
{
return;
}
void OverlapWithGradient(const MultiSlater &ref, Eigen::VectorBlock<VectorXd> &grad) const
{
// ciCoeffs
if (schd.optimizeCiCoeffs) {
for (int i = 0; i < ref.numDets; i++) grad[i] += refHelper.ciOverlaps[i] / (refHelper.totalOverlap);
}
}
friend ostream& operator<<(ostream& os, const Walker<Corr, MultiSlater>& w) {
os << w.d << endl << endl;
os << "t\n" << w.refHelper.t << endl << endl;
os << "rt\n" << w.refHelper.rt << endl << endl;
os << "tc\n" << w.refHelper.tc << endl << endl;
os << "rtc_b\n" << w.refHelper.rtc_b << endl << endl;
os << "totalOverlap\n" << w.refHelper.totalOverlap << endl << endl;
return os;
}
};
//template<typename Corr>
//struct Walker<Corr, BFSlater> {
//
// Determinant d;
// WalkerHelper<Corr> corrHelper;
// WalkerHelper<BFSlater> refHelper;
// unordered_set<int> excitedOrbs; //spin orbital indices of excited electrons (in virtual orbitals) in d
//
// Walker() {};
//
// Walker(Corr &corr, const BFSlater &ref)
// {
// initDet(ref.getHforbsA().real(), ref.getHforbsB().real());
// refHelper = WalkerHelper<BFSlater>(ref, d);
// corrHelper = WalkerHelper<Corr>(corr, d);
// }
//
// Walker(Corr &corr, const BFSlater &ref, const Determinant &pd) : d(pd), refHelper(ref, pd), corrHelper(corr, pd) {};
//
// Determinant& getDet() {return d;}
// void readBestDeterminant(Determinant& d) const
// {
// if (commrank == 0) {
// char file[5000];
// sprintf(file, "BestDeterminant.txt");
// std::ifstream ifs(file, std::ios::binary);
// boost::archive::binary_iarchive load(ifs);
// load >> d;
// }
//#ifndef SERIAL
// MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
// MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
//#endif
// }
//
// /**
// * makes det based on mo coeffs
// */
// void guessBestDeterminant(Determinant& d, const Eigen::MatrixXd& HforbsA, const Eigen::MatrixXd& HforbsB) const
// {
// int norbs = Determinant::norbs;
// int nalpha = Determinant::nalpha;
// int nbeta = Determinant::nbeta;
//
// d = Determinant();
// if (boost::iequals(schd.determinantFile, "")) {
// for (int i = 0; i < nalpha; i++) {
// int bestorb = 0;
// double maxovlp = 0;
// for (int j = 0; j < norbs; j++) {
// if (abs(HforbsA(i, j)) > maxovlp && !d.getoccA(j)) {
// maxovlp = abs(HforbsA(i, j));
// bestorb = j;
// }
// }
// d.setoccA(bestorb, true);
// }
// for (int i = 0; i < nbeta; i++) {
// int bestorb = 0;
// double maxovlp = 0;
// for (int j = 0; j < norbs; j++) {
// if (schd.hf == "rhf" || schd.hf == "uhf") {
// if (abs(HforbsB(i, j)) > maxovlp && !d.getoccB(j)) {
// bestorb = j;
// maxovlp = abs(HforbsB(i, j));
// }
// }
// else {
// if (abs(HforbsB(i+norbs, j)) > maxovlp && !d.getoccB(j)) {
// bestorb = j;
// maxovlp = abs(HforbsB(i+norbs, j));
// }
// }
// }
// d.setoccB(bestorb, true);
// }
// }
// else if (boost::iequals(schd.determinantFile, "bestDet")) {
// std::vector<Determinant> dets;
// std::vector<double> ci;
// readDeterminants(schd.determinantFile, dets, ci);
// d = dets[0];
// }
// }
//
// void initDet(const MatrixXd& HforbsA, const MatrixXd& HforbsB)
// {
// bool readDeterminant = false;
// char file[5000];
// sprintf(file, "BestDeterminant.txt");
//
// {
// ifstream ofile(file);
// if (ofile)
// readDeterminant = true;
// }
// if (readDeterminant)
// readBestDeterminant(d);
// else
// guessBestDeterminant(d, HforbsA, HforbsB);
// }
//
// double getDetOverlap(const BFSlater &ref) const
// {
// return (refHelper.thetaDet[0] * refHelper.thetaDet[1]).real();
// }
//
// double getDetFactor(int i, int a, const BFSlater &ref) const
// {
// if (i % 2 == 0)
// return getDetFactor(i / 2, a / 2, 0, ref);
// else
// return getDetFactor(i / 2, a / 2, 1, ref);
// }
//
// double getDetFactor(int I, int J, int A, int B, const BFSlater &ref) const
// {
// if (I % 2 == J % 2 && I % 2 == 0)
// return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 0, ref);
// else if (I % 2 == J % 2 && I % 2 == 1)
// return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 1, ref);
// else if (I % 2 != J % 2 && I % 2 == 0)
// return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 1, ref);
// else
// return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 0, ref);
// }
//
// double getDetFactor(int i, int a, bool sz, const BFSlater &ref) const
// {
// Determinant dcopy = d;
// double parity *= dcopy.parity(a, i, sz);
// dcopy.setocc(i, sz, false);
// dcopy.setocc(a, sz, true);
// WalkerHelper<BFSlater> refHelperCopy = WalkerHelper<BFSlater>(ref, dcopy);
// return parity * (refHelperCopy.thetaDet[0] * refHelperCopy.thetaDet[1]).real() / getDetOverlap(ref);
// }
//
// double getDetFactor(int i, int j, int a, int b, bool sz1, bool sz2, const BFSlater &ref) const
// {
// Determinant dcopy = d;
// double parity *= dcopy.parity(a, i, sz1);
// dcopy.setocc(i, sz1, false);
// dcopy.setocc(a, sz1, true);
// parity *= dcopy.parity(b, j, sz2);
// dcopy.setocc(j, sz2, false);
// dcopy.setocc(b, sz2, true);
// WalkerHelper<BFSlater> refHelperCopy = WalkerHelper<BFSlater>(ref, dcopy);
// return parity * (refHelperCopy.thetaDet[0] * refHelperCopy.thetaDet[1]).real() / getDetOverlap(ref);
// }
//
//// //only works for ghf
//// double getDetFactor(std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to) const
//// {
//// if (from[0].size() + from[1].size() == 0) return 1.;
//// int numExc = from[0].size() + from[1].size();
//// VectorXi tableIndicesRow = VectorXi::Zero(from[0].size() + from[1].size());
//// VectorXi tableIndicesCol = VectorXi::Zero(from[0].size() + from[1].size());
//// Determinant dcopy = d;
//// double parity = 1.;
//// int count = 0;
//// for (int sz = 0; sz < 2; sz++) {//iterate over spins
//// auto itFrom = from[sz].begin();
//// auto itTo = to[sz].begin();
//// for (int n = 0; n < from[sz].size(); n++) {//iterate over excitations
//// int i = *itFrom, a = *itTo;
//// itFrom = std::next(itFrom); itTo = std::next(itTo);
//// refHelper.getRelIndices(i, tableIndicesCol(count), a, tableIndicesRow(count), sz);
//// count++;
//// parity *= dcopy.parity(a, i, sz);
//// dcopy.setocc(i, sz, false);
//// dcopy.setocc(a, sz, true);
//// }
//// }
////
//// MatrixXcd detSlice = MatrixXcd::Zero(numExc,numExc);
//// igl::slice(refHelper.rTable[0][0], tableIndicesRow, tableIndicesCol, detSlice);
//// complex<double> det(0.,0.);
//// if (detSlice.rows() == 1) det = detSlice(0, 0);
//// else if (detSlice.rows() == 2) det = detSlice(0, 0) * detSlice(1, 1) - detSlice(0, 1) * detSlice(1, 0);
//// else if (detSlice.rows() == 3) det = detSlice(0, 0) * (detSlice(1, 1) * detSlice(2, 2) - detSlice(1, 2) * detSlice(2, 1))
//// - detSlice(0, 1) * (detSlice(1, 0) * detSlice(2, 2) - detSlice(1, 2) * detSlice(2, 0))
//// + detSlice(0, 2) * (detSlice(1, 0) * detSlice(2, 1) - detSlice(1, 1) * detSlice(2, 0));
//// else if (detSlice.rows() == 4) det = detSlice(0,3) * detSlice(1,2) * detSlice(2,1) * detSlice(3,0) - detSlice(0,2) * detSlice(1,3) * detSlice(2,1) * detSlice(3,0) -
//// detSlice(0,3) * detSlice(1,1) * detSlice(2,2) * detSlice(3,0) + detSlice(0,1) * detSlice(1,3) * detSlice(2,2) * detSlice(3,0) +
//// detSlice(0,2) * detSlice(1,1) * detSlice(2,3) * detSlice(3,0) - detSlice(0,1) * detSlice(1,2) * detSlice(2,3) * detSlice(3,0) -
//// detSlice(0,3) * detSlice(1,2) * detSlice(2,0) * detSlice(3,1) + detSlice(0,2) * detSlice(1,3) * detSlice(2,0) * detSlice(3,1) +
//// detSlice(0,3) * detSlice(1,0) * detSlice(2,2) * detSlice(3,1) - detSlice(0,0) * detSlice(1,3) * detSlice(2,2) * detSlice(3,1) -
//// detSlice(0,2) * detSlice(1,0) * detSlice(2,3) * detSlice(3,1) + detSlice(0,0) * detSlice(1,2) * detSlice(2,3) * detSlice(3,1) +
//// detSlice(0,3) * detSlice(1,1) * detSlice(2,0) * detSlice(3,2) - detSlice(0,1) * detSlice(1,3) * detSlice(2,0) * detSlice(3,2) -
//// detSlice(0,3) * detSlice(1,0) * detSlice(2,1) * detSlice(3,2) + detSlice(0,0) * detSlice(1,3) * detSlice(2,1) * detSlice(3,2) +
//// detSlice(0,1) * detSlice(1,0) * detSlice(2,3) * detSlice(3,2) - detSlice(0,0) * detSlice(1,1) * detSlice(2,3) * detSlice(3,2) -
//// detSlice(0,2) * detSlice(1,1) * detSlice(2,0) * detSlice(3,3) + detSlice(0,1) * detSlice(1,2) * detSlice(2,0) * detSlice(3,3) +
//// detSlice(0,2) * detSlice(1,0) * detSlice(2,1) * detSlice(3,3) - detSlice(0,0) * detSlice(1,2) * detSlice(2,1) * detSlice(3,3) -
//// detSlice(0,1) * detSlice(1,0) * detSlice(2,2) * detSlice(3,3) + detSlice(0,0) * detSlice(1,1) * detSlice(2,2) * detSlice(3,3);
////
//// //complex<double> det = detSlice.determinant();
//// double num = (det * refHelper.thetaDet[0][0] * refHelper.thetaDet[0][1]).real();
//// double den = (refHelper.thetaDet[0][0] * refHelper.thetaDet[0][1]).real();
//// return parity * num / den;
//// }
////
//// void update(int i, int a, bool sz, const BFSlater &ref, Corr &corr, bool doparity = true)
//// {
//// double p = 1.0;
//// if (doparity) p *= d.parity(a, i, sz);
//// d.setocc(i, sz, false);
//// d.setocc(a, sz, true);
//// if (refHelper.hftype == Generalized) {
//// int norbs = Determinant::norbs;
//// vector<int> cre{ a + sz * norbs }, des{ i + sz * norbs };
//// refHelper.excitationUpdateGhf(ref, cre, des, sz, p, d);
//// }
//// else
//// {
//// vector<int> cre{ a }, des{ i };
//// refHelper.excitationUpdate(ref, cre, des, sz, p, d);
//// }
////
//// corrHelper.updateHelper(corr, d, i, a, sz);
//// }
//
// void update(int i, int j, int a, int b, bool sz, const BFSlater &ref, Corr& corr, bool doparity = true)
// {
// d.setocc(i, sz, false);
// d.setocc(a, sz, true);
// d.setocc(j, sz, false);
// d.setocc(b, sz, true);
// if (refHelper.hftype == Generalized) {
// refHelper.excitationUpdateGhf(ref, d);
// }
// else {
// refHelper.excitationUpdate(ref, d);
// }
// corrHelper.updateHelper(corr, d, i, j, a, b, sz);
// }
//
// void updateWalker(const BFSlater &ref, Corr& corr, int ex1, int ex2, bool doparity = true)
// {
// int norbs = Determinant::norbs;
// int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
// int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
// if (I % 2 == J % 2 && ex2 != 0) {
// if (I % 2 == 1) {
// update(I / 2, J / 2, A / 2, B / 2, 1, ref, corr, doparity);
// }
// else {
// update(I / 2, J / 2, A / 2, B / 2, 0, ref, corr, doparity);
// }
// }
// else {
// if (I % 2 == 0)
// update(I / 2, A / 2, 0, ref, corr, doparity);
// else
// update(I / 2, A / 2, 1, ref, corr, doparity);
//
// if (ex2 != 0) {
// if (J % 2 == 1) {
// update(J / 2, B / 2, 1, ref, corr, doparity);
// }
// else {
// update(J / 2, B / 2, 0, ref, corr, doparity);
// }
// }
// }
// }
//
// void exciteWalker(const BFSlater &ref, Corr& corr, int excite1, int excite2, int norbs)
// {
// int I1 = excite1 / (2 * norbs), A1 = excite1 % (2 * norbs);
//
// if (I1 % 2 == 0)
// update(I1 / 2, A1 / 2, 0, ref, corr);
// else
// update(I1 / 2, A1 / 2, 1, ref, corr);
//
// if (excite2 != 0) {
// int I2 = excite2 / (2 * norbs), A2 = excite2 % (2 * norbs);
// if (I2 % 2 == 0)
// update(I2 / 2, A2 / 2, 0, ref, corr);
// else
// update(I2 / 2, A2 / 2, 1, ref, corr);
// }
// }
//
// void OverlapWithOrbGradient(const BFSlater &ref, Eigen::VectorXd &grad, double detovlp) const
// {
// int norbs = Determinant::norbs;
// Determinant walkerDet = d;
// Determinant refDet = ref.getDeterminant();
//
// //K and L are relative row and col indices
// int KA = 0, KB = 0;
// for (int k = 0; k < norbs; k++) { //walker indices on the row
// if (walkerDet.getoccA(k)) {
// int L = 0;
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccA(l)) {
// grad(2*k*norbs + 2*l) += (refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() /detovlp;
// grad(2*k*norbs + 2*l + 1) += * (-refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() /detovlp;
// L++;
// }
// }
// KA++;
// }
// if (walkerDet.getoccB(k)) {
// int L = 0;
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccB(l)) {
// if (refHelper.hftype == UnRestricted) {
// grad(2*norbs*norbs + 2*k*norbs + 2*l) += (refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() / detovlp;
// grad(2*norbs*norbs + 2*k*norbs + 2*l + 1) += (-refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() / detovlp;
// }
// else {
// grad(2*k*norbs + 2*l) += (refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() / detovlp;
// grad(2*k*norbs + 2*l + 1) += (-refHelper.thetaInv[1](L, KB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() / detovlp;
// }
// L++;
// }
// }
// KB++;
// }
// if (!walkerDet.getoccA(k) && !walkerDet.getoccB(k)) {
// for (int i = 0; i < refHelper.doublons.size(); i++) {
// int LA = 0, LB = 0;
// int relIndexA = std::search_n(refHelper.closedOrbs[0].begin(), refHelper.closedOrbs[0].end(), 1, refHelper.doublons[i]) - refHelper.closedOrbs[0].begin();
// int relIndexB = std::search_n(refHelper.closedOrbs[1].begin(), refHelper.closedOrbs[1].end(), 1, refHelper.doublons[i]) - refHelper.closedOrbs[1].begin();
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccA(l)) {
// grad(2*k*norbs + 2*l) += ref.bf(refHelper.doublons[i], k) * (refHelper.thetaInv[0](LA, relIndexA) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() / detovlp;
// grad(2*k*norbs + 2*l + 1) += ref.bf(refHelper.doublons[i], k) * (-refHelper.thetaInv[0](LA, relIndexA) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() /detovlp;
// LA++;
// }
// if (refDet.getoccB(l)) {
// if (refHelper.hftype == UnRestricted) {
// grad(2*norbs*norbs + 2*k*norbs + 2*l) += ref.bf(refHelper.doublons[i], k) * (refHelper.thetaInv[1](LB, relIndexB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() / detovlp;
// grad(2*norbs*norbs + 2*k*norbs + 2*l + 1) += ref.bf(refHelper.doublons[i], k) * (-refHelper.thetaInv[1](LB, relIndexB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() /detovlp;
// }
// else {
// grad(2*k*norbs + 2*l) += ref.bf(refHelper.doublons[i], k) * (refHelper.thetaInv[1](LB, relIndexB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() / detovlp;
// grad(2*k*norbs + 2*l + 1) += ref.bf(refHelper.doublons[i], k) * (-refHelper.thetaInv[1](LB, relIndexB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() /detovlp;
// }
// LB++;
// }
// }
// }
// }
// }
// }
//
// void OverlapWithOrbGradientGhf(const BFSlater &ref, Eigen::VectorXd &grad, double detovlp) const
// {
// int norbs = Determinant::norbs;
// Determinant walkerDet = d;
// Determinant refDet = ref.getDeterminants()[0];
//
// //K and L are relative row and col indices
// int KA = 0, KB = 0;
// for (int k = 0; k < norbs; k++) { //walker indices on the row
// if (walkerDet.getoccA(k)) {
// int L = 0;
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccA(l)) {
// grad(4*k*norbs + 2*l) += (refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[0][0]).real() / detovlp;
// grad(4*k*norbs + 2*l + 1) += (-refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[0][0]).imag() / detovlp;
// L++;
// }
// }
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccB(l)) {
// grad(4*k*norbs + 2*norbs + 2*l) += (refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[0][0]).real() / detovlp;
// grad(4*k*norbs + 2*norbs + 2*l + 1) += (-refHelper.thetaInv[0](L, KA) * refHelper.thetaDet[0][0]).imag() / detovlp;
// L++;
// }
// }
// KA++;
// }
// if (walkerDet.getoccB(k)) {
// int L = 0;
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccA(l)) {
// grad(4*norbs*norbs + 4*k*norbs + 2*l) += (refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, KB)).real() / detovlp;
// grad(4*norbs*norbs + 4*k*norbs + 2*l + 1) += (-refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, KB)).imag() / detovlp;
// L++;
// }
// }
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccB(l)) {
// grad(4*norbs*norbs + 4*k*norbs + 2*norbs + 2*l) += (refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, KB)).real() / detovlp;
// grad(4*norbs*norbs + 4*k*norbs + 2*norbs + 2*l + 1) += (-refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, KB)).imag() / detovlp;
// L++;
// }
// }
// KB++;
// }
// if (!walkerDet.getoccA(k) && !walkerDet.getoccB(k)) {
// for (int i = 0; i < refHelper.doublons.size(); i++) {
// int L = 0;
// int relIndexA = std::search_n(refHelper.closedOrbs[0].begin(), refHelper.closedOrbs[0].end(), 1, refHelper.doublons[i]) - refHelper.closedOrbs[0].begin();
// int relIndexB = std::search_n(refHelper.closedOrbs[1].begin(), refHelper.closedOrbs[1].end(), 1, refHelper.doublons[i]) - refHelper.closedOrbs[1].begin();
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccA(l)) {
// grad(4*k*norbs + 2*l) += ref.bf(refHelper.doublons[i], k) * (refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, relIndexA)).real() / detovlp;
// grad(4*k*norbs + 2*l + 1) += ref.bf(refHelper.doublons[i], k) * (-refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, relIndexA)).imag() / detovlp;
// grad(4*norbs*norbs + 4*k*norbs + 2*l) += ref.bf(refHelper.doublons[i], k) * (refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, relIndexB)).real() / detovlp;
// grad(4*norbs*norbs + 4*k*norbs + 2*l + 1) += ref.bf(refHelper.doublons[i], k) * (-refHelper.thetaDet[0][0] * refHelper.thetaInv[0](L, relIndexB)).imag() / detovlp;
// L++;
// }
// }
// for (int l = 0; l < norbs; l++) {
// if (refDet.getoccB(l)) {
// grad(4*k*norbs + 2*norbs + 2*l) += ref.bf(refHelper.doublons[i], k) * (refHelper.thetaInv[1](L, relIndexA) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() / detovlp;
// grad(4*k*norbs + 2*norbs + 2*l + 1) += ref.bf(refHelper.doublons[i], k) * (-refHelper.thetaInv[1](L, relIndexA) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() /detovlp;
// grad(4*norbs*norbs + 4*k*norbs + 2*norbs + 2*l) += ref.bf(refHelper.doublons[i], k) * (refHelper.thetaInv[1](L, relIndexB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).real() / detovlp;
// grad(4*norbs*norbs + 4*k*norbs + 2*norbs + 2*l + 1) += ref.bf(refHelper.doublons[i], k) * (-refHelper.thetaInv[1](L, relIndexB) * refHelper.thetaDet[0] * refHelper.thetaDet[1]).imag() /detovlp;
// L++;
// }
// }
// }
// }
// }
// }
//
// void OverlapWithGradient(const BFSlater &ref, Eigen::VectorBlock<VectorXd> &grad) const
// {
// double detovlp = getDetOverlap(ref);
// if (schd.optimizeOrbs) {
// //if (hftype == UnRestricted)
// VectorXd gradOrbitals;
// if (ref.hftype == UnRestricted) {
// gradOrbitals = VectorXd::Zero(4 * ref.HforbsA.rows() * ref.HforbsA.rows());
// OverlapWithOrbGradient(ref, gradOrbitals, detovlp);
// }
// else {
// gradOrbitals = VectorXd::Zero(2 * ref.HforbsA.rows() * ref.HforbsA.rows());
// if (ref.hftype == Restricted) OverlapWithOrbGradient(ref, gradOrbitals, detovlp);
// else OverlapWithOrbGradientGhf(ref, gradOrbitals, detovlp);
// }
// for (int i = 0; i < gradOrbitals.size(); i++)
// grad[i] += gradOrbitals[i];
// }
// }
//
// friend ostream& operator<<(ostream& os, const Walker<Corr, BFSlater>& w) {
// os << w.d << endl << endl;
// os << "alphaTable\n" << w.refHelper.rTable[0][0] << endl << endl;
// os << "betaTable\n" << w.refHelper.rTable[0][1] << endl << endl;
// os << "dets\n" << w.refHelper.thetaDet[0][0] << " " << w.refHelper.thetaDet[0][1] << endl << endl;
// os << "alphaInv\n" << w.refHelper.thetaInv[0] << endl << endl;
// os << "betaInv\n" << w.refHelper.thetaInv[1] << endl << endl;
// return os;
// }
//
//};
template<typename Corr>
struct Walker<Corr, AGP> {
Determinant d;
WalkerHelper<Corr> corrHelper;
WalkerHelper<AGP> refHelper;
unordered_set<int> excitedHoles; //spin orbital indices of excited electrons (in core orbitals) in d
unordered_set<int> excitedOrbs; //spin orbital indices of excited electrons (in virtual orbitals) in d
Walker() {};
Walker(Corr &corr, const AGP &ref)
{
initDet(ref.getPairMat().real());
refHelper = WalkerHelper<AGP>(ref, d);
corrHelper = WalkerHelper<Corr>(corr, d);
}
template<typename Wave>
Walker(Wave &wave, const Determinant &pd)
{
d = pd;
refHelper = WalkerHelper<AGP>(wave.ref, pd);
corrHelper = WalkerHelper<Corr>(wave.corr, pd);
}
Walker(Corr &corr, const AGP &ref, const Determinant &pd) : d(pd), refHelper(ref, pd), corrHelper(corr, pd) {};
Determinant& getDet() {return d;}
void readBestDeterminant(Determinant& d) const
{
if (commrank == 0) {
char file[5000];
sprintf(file, "BestDeterminant.txt");
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> d;
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
void guessBestDeterminant(Determinant& d, const Eigen::MatrixXd& pairMat) const
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
for (int i = 0; i < nalpha; i++)
d.setoccA(i, true);
for (int i = 0; i < nbeta; i++)
d.setoccB(i, true);
}
void initDet(const MatrixXd& pairMat)
{
bool readDeterminant = false;
char file[5000];
sprintf(file, "BestDeterminant.txt");
{
ifstream ofile(file);
if (ofile)
readDeterminant = true;
}
if (readDeterminant)
readBestDeterminant(d);
else
guessBestDeterminant(d, pairMat);
}
double getDetOverlap(const AGP &ref) const
{
return refHelper.thetaDet.real();
}
double getDetFactor(int i, int a, const AGP &ref) const
{
if (i % 2 == 0)
return getDetFactor(i / 2, a / 2, 0, ref);
else
return getDetFactor(i / 2, a / 2, 1, ref);
}
double getDetFactor(int I, int J, int A, int B, const AGP &ref) const
{
if (I % 2 == J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 0, ref);
else if (I % 2 == J % 2 && I % 2 == 1)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 1, ref);
else if (I % 2 != J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 1, ref);
else
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 0, ref);
}
double getDetFactor(int i, int a, bool sz, const AGP &ref) const
{
int tableIndexi, tableIndexa;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz);
return (refHelper.rTable[sz](tableIndexa, tableIndexi) * refHelper.thetaDet).real() / (refHelper.thetaDet).real();
}
double getDetFactor(int i, int j, int a, int b, bool sz1, bool sz2, const AGP &ref) const
{
int tableIndexi, tableIndexa, tableIndexj, tableIndexb;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz1);
refHelper.getRelIndices(j, tableIndexj, b, tableIndexb, sz2) ;
complex<double> factor;
if (sz1 == sz2)
factor = refHelper.rTable[sz1](tableIndexa, tableIndexi) * refHelper.rTable[sz1](tableIndexb, tableIndexj)
- refHelper.rTable[sz1](tableIndexb, tableIndexi) *refHelper.rTable[sz1](tableIndexa, tableIndexj);
else
if (sz1 == 0) {
factor = refHelper.rTable[sz1](tableIndexa, tableIndexi) * refHelper.rTable[sz2](tableIndexb, tableIndexj)
+ refHelper.thetaInv(tableIndexj, tableIndexi) * refHelper.rTable[2](tableIndexa, tableIndexb);
}
else {
factor = refHelper.rTable[sz1](tableIndexa, tableIndexi) * refHelper.rTable[sz2](tableIndexb, tableIndexj)
+ refHelper.thetaInv(tableIndexi, tableIndexj) * refHelper.rTable[2](tableIndexb, tableIndexa);
}
return (factor * refHelper.thetaDet).real() / (refHelper.thetaDet).real();
}
double getDetFactor(std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to) const
{
return 0.;
}
void update(int i, int a, bool sz, const AGP &ref, Corr &corr, bool doparity = true)
{
double p = 1.0;
if (doparity) p *= d.parity(a, i, sz);
d.setocc(i, sz, false);
d.setocc(a, sz, true);
vector<int> cre{ a }, des{ i };
refHelper.excitationUpdate(ref, cre, des, sz, p, d);
corrHelper.updateHelper(corr, d, i, a, sz);
}
void update(int i, int j, int a, int b, bool sz, const AGP &ref, Corr &corr, bool doparity = true)
{
double p = 1.0;
Determinant dcopy = d;
if (doparity) p *= d.parity(a, i, sz);
d.setocc(i, sz, false);
d.setocc(a, sz, true);
if (doparity) p *= d.parity(b, j, sz);
d.setocc(j, sz, false);
d.setocc(b, sz, true);
vector<int> cre{ a, b }, des{ i, j };
refHelper.excitationUpdate(ref, cre, des, sz, p, d);
corrHelper.updateHelper(corr, d, i, j, a, b, sz);
}
void updateWalker(const AGP& ref, Corr &corr, int ex1, int ex2, bool doparity = true)
{
int norbs = Determinant::norbs;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
if (I % 2 == J % 2 && ex2 != 0) {
if (I % 2 == 1) {
update(I / 2, J / 2, A / 2, B / 2, 1, ref, corr, doparity);
}
else {
update(I / 2, J / 2, A / 2, B / 2, 0, ref, corr, doparity);
}
}
else {
if (I % 2 == 0)
update(I / 2, A / 2, 0, ref, corr, doparity);
else
update(I / 2, A / 2, 1, ref, corr, doparity);
if (ex2 != 0) {
if (J % 2 == 1) {
update(J / 2, B / 2, 1, ref, corr, doparity);
}
else {
update(J / 2, B / 2, 0, ref, corr, doparity);
}
}
}
}
void exciteWalker(const AGP& ref, Corr &corr, int excite1, int excite2, int norbs)
{
int I1 = excite1 / (2 * norbs), A1 = excite1 % (2 * norbs);
if (I1 % 2 == 0)
update(I1 / 2, A1 / 2, 0, ref, corr);
else
update(I1 / 2, A1 / 2, 1, ref, corr);
if (excite2 != 0) {
int I2 = excite2 / (2 * norbs), A2 = excite2 % (2 * norbs);
if (I2 % 2 == 0)
update(I2 / 2, A2 / 2, 0, ref, corr);
else
update(I2 / 2, A2 / 2, 1, ref, corr);
}
}
void OverlapWithGradient(const AGP &ref, Eigen::VectorBlock<VectorXd> &grad) const
{
if (schd.optimizeOrbs) {
double detOvlp = getDetOverlap(ref);
int norbs = Determinant::norbs;
Determinant walkerDet = d;
//K and L are relative row and col indices
int K = 0;
for (int k = 0; k < norbs; k++) { //walker indices on the row
if (walkerDet.getoccA(k)) {
int L = 0;
for (int l = 0; l < norbs; l++) {
if (walkerDet.getoccB(l)) {
grad(2 * k * norbs + 2 * l) += (refHelper.thetaInv(L, K) * refHelper.thetaDet).real() / detOvlp ;
grad(2 * k * norbs + 2 * l + 1) += (- refHelper.thetaInv(L, K) * refHelper.thetaDet).imag() / detOvlp ;
L++;
}
}
K++;
}
}
}
}
friend ostream& operator<<(ostream& os, const Walker<Corr, AGP>& w) {
os << w.d << endl << endl;
os << "alphaTable\n" << w.refHelper.rTable[0] << endl << endl;
os << "betaTable\n" << w.refHelper.rTable[1] << endl << endl;
os << "thirdTable\n" << w.refHelper.rTable[2] << endl << endl;
os << "dets\n" << w.refHelper.thetaDet << endl << endl;
os << "thetaInv\n" << w.refHelper.thetaInv << endl << endl;
return os;
}
};
template<typename Corr>
struct Walker<Corr, Pfaffian> {
Determinant d;
WalkerHelper<Corr> corrHelper;
WalkerHelper<Pfaffian> refHelper;
unordered_set<int> excitedHoles; //spin orbital indices of excited electrons (in core orbitals) in d
unordered_set<int> excitedOrbs; //spin orbital indices of excited electrons (in virtual orbitals) in d
Walker() {};
Walker(Corr &corr, const Pfaffian &ref)
{
initDet(ref.getPairMat().real());
refHelper = WalkerHelper<Pfaffian>(ref, d);
corrHelper = WalkerHelper<Corr>(corr, d);
}
Walker(Corr &corr, const Pfaffian &ref, const Determinant &pd) : d(pd), refHelper(ref, pd), corrHelper(corr, pd) {};
Determinant& getDet() {return d;}
void readBestDeterminant(Determinant& d) const
{
if (commrank == 0) {
char file[5000];
sprintf(file, "BestDeterminant.txt");
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> d;
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
void guessBestDeterminant(Determinant& d, const Eigen::MatrixXd& pairMat) const
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
for (int i = 0; i < nalpha; i++)
d.setoccA(i, true);
for (int i = 0; i < nbeta; i++)
d.setoccB(i, true);
}
void initDet(const MatrixXd& pairMat)
{
bool readDeterminant = false;
char file[5000];
sprintf(file, "BestDeterminant.txt");
{
ifstream ofile(file);
if (ofile)
readDeterminant = true;
}
if (readDeterminant)
readBestDeterminant(d);
else
guessBestDeterminant(d, pairMat);
}
double getDetOverlap(const Pfaffian &ref) const
{
return refHelper.thetaPfaff.real();
}
double getDetFactor(int i, int a, const Pfaffian &ref) const
{
if (i % 2 == 0)
return getDetFactor(i / 2, a / 2, 0, ref);
else
return getDetFactor(i / 2, a / 2, 1, ref);
}
double getDetFactor(int I, int J, int A, int B, const Pfaffian &ref) const
{
if (I % 2 == J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 0, ref);
else if (I % 2 == J % 2 && I % 2 == 1)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 1, ref);
else if (I % 2 != J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 1, ref);
else
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 0, ref);
}
double getDetFactor(int i, int a, bool sz, const Pfaffian &ref) const
{
int nopen = refHelper.openOrbs[0].size() + refHelper.openOrbs[1].size();
int tableIndexi, tableIndexa;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz);
//return refHelper.rTable[0](tableIndexi * nopen + tableIndexa, tableIndexi);
//return ((refHelper.fMat.row(tableIndexi * nopen + tableIndexa) * refHelper.thetaInv.col(tableIndexi))(0,0) * refHelper.thetaPfaff).real() / (refHelper.thetaPfaff).real();
return (refHelper.rTable[0](tableIndexa, tableIndexi) * refHelper.thetaPfaff).real() / (refHelper.thetaPfaff).real();
}
double getDetFactor(int i, int j, int a, int b, bool sz1, bool sz2, const Pfaffian &ref) const
{
int norbs = Determinant::norbs;
int nopen = refHelper.openOrbs[0].size() + refHelper.openOrbs[1].size();
int tableIndexi, tableIndexa, tableIndexj, tableIndexb;
refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz1);
refHelper.getRelIndices(j, tableIndexj, b, tableIndexb, sz2);
//cout << "nopen " << nopen << endl;
//cout << "sz1 " << sz1 << " ti " << tableIndexi << " ta " << tableIndexa << endl;
//cout << "sz2 " << sz2 << " tj " << tableIndexj << " tb " << tableIndexb << endl;
complex<double> summand1, summand2, crossTerm;
if (tableIndexi < tableIndexj) {
crossTerm = (ref.getPairMat())(b + sz2 * norbs, a + sz1 * norbs);
//summand1 = refHelper.rTable[0](tableIndexi * nopen + tableIndexa, tableIndexi) * refHelper.rTable[0](tableIndexj * nopen + tableIndexb, tableIndexj)
// - refHelper.rTable[0](tableIndexj * nopen + tableIndexb, tableIndexi) * refHelper.rTable[0](tableIndexi * nopen + tableIndexa, tableIndexj);
//summand2 = refHelper.thetaInv(tableIndexi, tableIndexj) * (refHelper.rTable[1](tableIndexi * nopen + tableIndexa, tableIndexj * nopen + tableIndexb) + crossTerm);
//complex<double> term1 = refHelper.fMat.row(tableIndexi * nopen + tableIndexa) * refHelper.thetaInv.col(tableIndexi);
//complex<double> term2 = refHelper.fMat.row(tableIndexj * nopen + tableIndexb) * refHelper.thetaInv.col(tableIndexj);
//complex<double> term3 = refHelper.fMat.row(tableIndexj * nopen + tableIndexb) * refHelper.thetaInv.col(tableIndexi);
//complex<double> term4 = refHelper.fMat.row(tableIndexi * nopen + tableIndexa) * refHelper.thetaInv.col(tableIndexj);
complex<double> term1 = refHelper.rTable[0](tableIndexa, tableIndexi);
complex<double> term2 = refHelper.rTable[0](tableIndexb, tableIndexj);
complex<double> term3 = refHelper.rTable[0](tableIndexb, tableIndexi);
complex<double> term4 = refHelper.rTable[0](tableIndexa, tableIndexj);
summand1 = term1 * term2 - term3 * term4;
//complex<double> term5 = refHelper.fMat.row(tableIndexi * nopen + tableIndexa) * refHelper.thetaInv * (-refHelper.fMat.transpose().col(tableIndexj * nopen + tableIndexb));
complex<double> term5 = refHelper.rTable[1](tableIndexa, tableIndexb);
summand2 = refHelper.thetaInv(tableIndexi, tableIndexj) * (term5 + crossTerm);
}
else {
crossTerm = (ref.getPairMat())(a + sz1 * norbs, b + sz2 * norbs);
//summand1 = refHelper.rTable[0](tableIndexj * nopen + tableIndexb, tableIndexj) * refHelper.rTable[0](tableIndexi * nopen + tableIndexa, tableIndexi)
// - refHelper.rTable[0](tableIndexi * nopen + tableIndexa, tableIndexj) * refHelper.rTable[0](tableIndexj * nopen + tableIndexb, tableIndexi);
//summand2 = refHelper.thetaInv(tableIndexj, tableIndexi) * (refHelper.rTable[1](tableIndexj * nopen + tableIndexb, tableIndexi * nopen + tableIndexa) + crossTerm);
//complex<double> term1 = refHelper.fMat.row(tableIndexj * nopen + tableIndexb) * refHelper.thetaInv.col(tableIndexj);
//complex<double> term2 = refHelper.fMat.row(tableIndexi * nopen + tableIndexa) * refHelper.thetaInv.col(tableIndexi);
//complex<double> term3 = refHelper.fMat.row(tableIndexi * nopen + tableIndexa) * refHelper.thetaInv.col(tableIndexj);
//complex<double> term4 = refHelper.fMat.row(tableIndexj * nopen + tableIndexb) * refHelper.thetaInv.col(tableIndexi);
complex<double> term1 = refHelper.rTable[0](tableIndexb, tableIndexj);
complex<double> term2 = refHelper.rTable[0](tableIndexa, tableIndexi);
complex<double> term3 = refHelper.rTable[0](tableIndexa, tableIndexj);
complex<double> term4 = refHelper.rTable[0](tableIndexb, tableIndexi);
summand1 = term1 * term2 - term3 * term4;
//complex<double> term5 = refHelper.fMat.row(tableIndexj * nopen + tableIndexb) * refHelper.thetaInv * (-refHelper.fMat.transpose().col(tableIndexi * nopen + tableIndexa));
complex<double> term5 = refHelper.rTable[1](tableIndexb, tableIndexa);
summand2 = refHelper.thetaInv(tableIndexj, tableIndexi) * (term5 + crossTerm);
}
//cout << "double " << crossTerm << " " << summand1 << " " << summand2 << endl;
return ((summand1 + summand2) * refHelper.thetaPfaff).real() / (refHelper.thetaPfaff).real();
}
double getDetFactor(std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to) const
{
return 0.;
}
void update(int i, int a, bool sz, const Pfaffian &ref, Corr &corr, bool doparity = true)
{
double p = 1.0;
p *= d.parity(a, i, sz);
d.setocc(i, sz, false);
d.setocc(a, sz, true);
refHelper.excitationUpdate(ref, i, a, sz, p, d);
corrHelper.updateHelper(corr, d, i, a, sz);
}
void updateWalker(const Pfaffian& ref, Corr &corr, int ex1, int ex2, bool doparity = true)
{
int norbs = Determinant::norbs;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
if (I % 2 == 0)
update(I / 2, A / 2, 0, ref, corr, doparity);
else
update(I / 2, A / 2, 1, ref, corr, doparity);
if (ex2 != 0) {
if (J % 2 == 1)
update(J / 2, B / 2, 1, ref, corr, doparity);
else
update(J / 2, B / 2, 0, ref, corr, doparity);
}
}
void exciteWalker(const Pfaffian& ref, Corr &corr, int excite1, int excite2, int norbs)
{
int I1 = excite1 / (2 * norbs), A1 = excite1 % (2 * norbs);
if (I1 % 2 == 0)
update(I1 / 2, A1 / 2, 0, ref, corr);
else
update(I1 / 2, A1 / 2, 1, ref, corr);
if (excite2 != 0) {
int I2 = excite2 / (2 * norbs), A2 = excite2 % (2 * norbs);
if (I2 % 2 == 0)
update(I2 / 2, A2 / 2, 0, ref, corr);
else
update(I2 / 2, A2 / 2, 1, ref, corr);
}
}
void OverlapWithGradient(const Pfaffian &ref, Eigen::VectorBlock<VectorXd> &grad) const
{
if (schd.optimizeOrbs) {
int norbs = Determinant::norbs;
Determinant walkerDet = d;
double detOvlp = getDetOverlap(ref);
//K and L are relative row and col indices
int K = 0;
for (int k = 0; k < norbs; k++) { //walker indices on the row
if (walkerDet.getoccA(k)) {
int L = 0;
for (int l = 0; l < norbs; l++) {
if (walkerDet.getoccA(l)) {
grad(4 * k * norbs + 2 * l) += (refHelper.thetaInv(L, K) * refHelper.thetaPfaff).real() / detOvlp / 2;
grad(4 * k * norbs + 2 * l + 1) += (- refHelper.thetaInv(L, K) * refHelper.thetaPfaff).imag() / detOvlp / 2;
L++;
}
}
for (int l = 0; l < norbs; l++) {
if (walkerDet.getoccB(l)) {
grad(4 * k * norbs + 2 * norbs + 2 * l) += (refHelper.thetaInv(L, K) * refHelper.thetaPfaff).real() / detOvlp / 2;
grad(4 * k * norbs + 2 * norbs + 2 * l + 1) += (- refHelper.thetaInv(L, K) * refHelper.thetaPfaff).imag() / detOvlp / 2;
L++;
}
}
K++;
}
}
for (int k = 0; k < norbs; k++) { //walker indices on the row
if (walkerDet.getoccB(k)) {
int L = 0;
for (int l = 0; l < norbs; l++) {
if (walkerDet.getoccA(l)) {
grad(4 * norbs * norbs + 4 * k * norbs + 2 * l) += (refHelper.thetaInv(L, K) * refHelper.thetaPfaff).real() / detOvlp / 2;
grad(4 * norbs * norbs + 4 * k * norbs + 2 * l + 1) += (- refHelper.thetaInv(L, K) * refHelper.thetaPfaff).imag() / detOvlp / 2;
L++;
}
}
for (int l = 0; l < norbs; l++) {
if (walkerDet.getoccB(l)) {
grad(4 * norbs * norbs + 4 * k * norbs + 2 * norbs + 2 * l) += (refHelper.thetaInv(L, K) * refHelper.thetaPfaff).real() / detOvlp / 2;
grad(4 * norbs * norbs + 4 * k * norbs + 2 * norbs + 2 * l + 1) += (- refHelper.thetaInv(L, K) * refHelper.thetaPfaff).imag() / detOvlp / 2;
L++;
}
}
K++;
}
}
}
}
friend ostream& operator<<(ostream& os, const Walker<Corr, Pfaffian>& w) {
os << w.d << endl << endl;
os << "fMat\n" << w.refHelper.fMat << endl << endl;
os << "fThetaInv\n" << w.refHelper.rTable[0] << endl << endl;
os << "fThetaInvf\n" << w.refHelper.rTable[1] << endl << endl;
os << "pfaff\n" << w.refHelper.thetaPfaff << endl << endl;
os << "thetaInv\n" << w.refHelper.thetaInv << endl << endl;
return os;
}
};
#endif
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SHCI_SHM_H
#define SHCI_SHM_H
#include <vector>
#include <string>
#include <Eigen/Dense>
#include <Eigen/Core>
#include "global.h"
#include <boost/interprocess/managed_shared_memory.hpp>
using namespace Eigen;
void initSHM();
void removeSHM();
template <typename T>
void SHMVecFromVecs(std::vector<T>& vec, T* &SHMvec, std::string& SHMname,
boost::interprocess::shared_memory_object& SHMsegment,
boost::interprocess::mapped_region& SHMregion) {
size_t totalMemory = 0;
int comm_rank=0, comm_size=1;
#ifndef SERIAL
MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
#endif
if (comm_rank == 0)
totalMemory = vec.size()*sizeof(T);
#ifndef SERIAL
MPI_Bcast(&totalMemory, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
SHMsegment.truncate(totalMemory);
SHMregion = boost::interprocess::mapped_region{SHMsegment, boost::interprocess::read_write};
if (localrank == 0)
memset(SHMregion.get_address(), 0., totalMemory);
SHMvec = (T*)(SHMregion.get_address());
#ifndef SERIAL
MPI_Barrier(MPI_COMM_WORLD);
#endif
if (comm_rank == 0) {
for (size_t i=0; i<vec.size(); i++)
SHMvec[i] = vec[i];
}
#ifndef SERIAL
MPI_Barrier(MPI_COMM_WORLD);
#endif
if (localrank == 0) {
long intdim = totalMemory;
long maxint = 26843540; //mpi cannot transfer more than these number of doubles
long maxIter = intdim/maxint;
#ifndef SERIAL
MPI_Barrier(shmcomm);
char* shrdMem = static_cast<char*>(SHMregion.get_address());
for (int i=0; i<maxIter; i++) {
MPI_Bcast ( shrdMem+i*maxint, maxint, MPI_CHAR, 0, shmcomm);
MPI_Barrier(shmcomm);
}
MPI_Bcast ( shrdMem+(maxIter)*maxint, totalMemory - maxIter*maxint, MPI_CHAR, 0, shmcomm);
#endif
}
#ifndef SERIAL
MPI_Barrier(MPI_COMM_WORLD);
#endif
boost::interprocess::shared_memory_object::remove(SHMname.c_str());
}
template <typename T>
void SHMVecFromVecs(T *vec, int vecsize, T* &SHMvec, std::string& SHMname,
boost::interprocess::shared_memory_object& SHMsegment,
boost::interprocess::mapped_region& SHMregion) {
boost::interprocess::shared_memory_object::remove(SHMname.c_str());
size_t totalMemory = 0;
int comm_rank=0, comm_size=1;
#ifndef SERIAL
MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
#endif
if (comm_rank == 0)
totalMemory = vecsize*sizeof(T);
#ifndef SERIAL
MPI_Bcast(&totalMemory, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
SHMsegment.truncate(totalMemory);
SHMregion = boost::interprocess::mapped_region{SHMsegment, boost::interprocess::read_write};
if (localrank == 0)
memset(SHMregion.get_address(), 0., totalMemory);
SHMvec = (T*)(SHMregion.get_address());
#ifndef SERIAL
MPI_Barrier(MPI_COMM_WORLD);
#endif
if (comm_rank == 0) {
for (size_t i=0; i<vecsize; i++)
SHMvec[i] = vec[i];
}
#ifndef SERIAL
MPI_Barrier(MPI_COMM_WORLD);
#endif
if (localrank == 0) {
long intdim = totalMemory;
long maxint = 26843540; //mpi cannot transfer more than these number of doubles
long maxIter = intdim/maxint;
#ifndef SERIAL
MPI_Barrier(shmcomm);
char* shrdMem = static_cast<char*>(SHMregion.get_address());
for (int i=0; i<maxIter; i++) {
MPI_Bcast ( shrdMem+i*maxint, maxint, MPI_CHAR, 0, shmcomm);
MPI_Barrier(shmcomm);
}
MPI_Bcast ( shrdMem+(maxIter)*maxint, totalMemory - maxIter*maxint, MPI_CHAR, 0, shmcomm);
#endif
}
#ifndef SERIAL
MPI_Barrier(MPI_COMM_WORLD);
#endif
}
#endif
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRWalker_HEADER_H
#define TRWalker_HEADER_H
#include "Walker.h"
using namespace Eigen;
/**
Vector of Jastrow-Slater walkers to work with the TRWavefunction
*
*/
class TRWalker
{
public:
std::array<Walker<Jastrow, Slater>, 2> walkerPair;
Determinant d;
std::array<double, 2> overlaps;
double totalOverlap;
// constructors
// default
TRWalker(){};
// the following constructors are used by the wave function initWalker function
// for deterministic
TRWalker(Jastrow &corr, const Slater &ref, Determinant &pd)
{
d = pd;
walkerPair[0] = Walker<Jastrow, Slater>(corr, ref, pd);
Determinant dcopy = pd;
dcopy.flipAlphaBeta();
walkerPair[1] = Walker<Jastrow, Slater>(corr, ref, dcopy);
overlaps[0] = corr.Overlap(walkerPair[0].d) * walkerPair[0].getDetOverlap(ref);
overlaps[1] = corr.Overlap(walkerPair[1].d) * walkerPair[1].getDetOverlap(ref);
totalOverlap = overlaps[0] + overlaps[1];
};
TRWalker(Jastrow &corr, const Slater &ref)
{
walkerPair[0] = Walker<Jastrow, Slater>(corr, ref);
Determinant dcopy = walkerPair[0].d;
d = walkerPair[0].d;
dcopy.flipAlphaBeta();
walkerPair[1] = Walker<Jastrow, Slater>(corr, ref, dcopy);
overlaps[0] = corr.Overlap(walkerPair[0].d) * walkerPair[0].getDetOverlap(ref);
overlaps[1] = corr.Overlap(walkerPair[1].d) * walkerPair[1].getDetOverlap(ref);
totalOverlap = overlaps[0] + overlaps[1];
};
// this is used for storing bestDet
Determinant getDet() { return walkerPair[0].getDet(); }
// used during sampling
void updateWalker(const Slater &ref, Jastrow &corr, int ex1, int ex2, bool doparity = true) {
walkerPair[0].updateWalker(ref, corr, ex1, ex2, doparity);
d = walkerPair[0].d;
int norbs = Determinant::norbs;
// for the flipped determinant, flip the excitations
if (ex1%2 == 0) ex1 += 2*norbs + 1;
else ex1 -= (2*norbs + 1);
if (ex2 != 0) {
if (ex2%2 == 0) ex2 += 2*norbs + 1;
else ex2 -= (2*norbs + 1);
}
walkerPair[1].updateWalker(ref, corr, ex1, ex2, doparity);
overlaps[0] = corr.Overlap(walkerPair[0].d) * walkerPair[0].getDetOverlap(ref);
overlaps[1] = corr.Overlap(walkerPair[1].d) * walkerPair[1].getDetOverlap(ref);
totalOverlap = overlaps[0] + overlaps[1];
}
//to be defined for metropolis
void update(int i, int a, bool sz, const Slater &ref, const Jastrow &corr) { return; };
// used for debugging
friend ostream& operator<<(ostream& os, const TRWalker& w) {
os << "Walker 0" << endl << endl;
os << w.walkerPair[0] << endl;
os << "Walker 1" << endl << endl;
os << w.walkerPair[1] << endl;
return os;
}
};
#endif
<file_sep>#include "Walker.h"
#include "Wfn.h"
#include "integral.h"
#include "global.h"
#include "input.h"
using namespace Eigen;
void Walker::genAllMoves(CPSSlater& w, vector<Determinant>& dout,
vector<double>& prob, vector<size_t>& alphaExcitation,
vector<size_t>& betaExcitation) {
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
//generate all single excitation
for (int i=0; i<closed.size(); i++) {
for (int a=0; a<open.size(); a++) {
if (closed[i]%2 == open[a]%2) {
if (closed[i]%2 == 0) {
Determinant dcopy = d;
dcopy.setoccA(closed[i]/2, false); dcopy.setoccA(open[a]/2, true);
dout.push_back(dcopy);
prob.push_back(getDetFactorA(closed[i]/2, open[a]/2, w));
alphaExcitation.push_back(closed[i]/2*Determinant::norbs+open[a]/2);
betaExcitation.push_back(0);
//cout << " alpha "<<*alphaExcitation.rbegin()<<" "<<closed[i]<<" "<<open[a]<<endl;
}
else {
Determinant dcopy = d;
dcopy.setoccB(closed[i]/2, false); dcopy.setoccB(open[a]/2, true);
dout.push_back(dcopy);
prob.push_back(getDetFactorB(closed[i]/2, open[a]/2, w));
alphaExcitation.push_back(0);
betaExcitation.push_back(closed[i]/2*Determinant::norbs+open[a]/2);
//cout << " beta "<<*betaExcitation.rbegin()<<" "<<closed[i]<<" "<<open[a]<<endl;
}
}
}
}
//alpha-beta electron exchanges
for (int i=0; i<closed.size(); i++) {
if (closed[i]%2 == 0 && !d.getocc(closed[i]+1)) {//alpha orbital and single alpha occupation
for (int j=0; j<closed.size(); j++) {
if (closed[j]%2 == 1 && !d.getocc(closed[j]-1)) {//beta orbital and single beta occupation
Determinant dcopy = d;
dcopy.setoccA(closed[i]/2, false); dcopy.setoccB(closed[i]/2, true);
dcopy.setoccA(closed[j]/2, true) ; dcopy.setoccB(closed[j]/2, false);
prob.push_back(getDetFactorA(closed[i]/2, closed[j]/2,w)
*getDetFactorB(closed[j]/2, closed[i]/2,w));
alphaExcitation.push_back(closed[i]/2*Determinant::norbs+closed[j]/2);
betaExcitation.push_back(closed[j]/2*Determinant::norbs+closed[i]/2);
//cout << " alpha/beta "<<*alphaExcitation.rbegin()<<" "<<*betaExcitation.rbegin()<<" "<<closed[i]<<" "<<closed[j]<<endl;
}
}
}
}
}
void Walker::genAllMoves2(CPSSlater& w, vector<Determinant>& dout,
vector<double>& prob, vector<size_t>& alphaExcitation,
vector<size_t>& betaExcitation) {
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
//alpha-beta electron exchanges
if (schd.doubleProbability > 1.e-10) {
for (int i=0; i<closed.size(); i++) {
if (closed[i]%2 == 0 && !d.getocc(closed[i]+1)) {//alpha orbital and single alpha occupation
for (int j=0; j<closed.size(); j++) {
if (closed[j]%2 == 1 && !d.getocc(closed[j]-1)) {//beta orbital and single beta occupation
Determinant dcopy = d;
dcopy.setoccA(closed[i]/2, false); dcopy.setoccB(closed[i]/2, true);
dcopy.setoccA(closed[j]/2, true) ; dcopy.setoccB(closed[j]/2, false);
prob.push_back(schd.doubleProbability);
alphaExcitation.push_back(closed[i]/2*Determinant::norbs+closed[j]/2);
betaExcitation.push_back(closed[j]/2*Determinant::norbs+closed[i]/2);
//cout << " alpha/beta "<<*alphaExcitation.rbegin()<<" "<<*betaExcitation.rbegin()<<" "<<closed[i]<<" "<<closed[j]<<endl;
}
}
}
}
}
if (prob.size() == 0 || schd.singleProbability > 1.e-10) {
//generate all single excitation
for (int i=0; i<closed.size(); i++) {
for (int a=0; a<open.size(); a++) {
if (closed[i]%2 == open[a]%2) {
if (closed[i]%2 == 0) {
Determinant dcopy = d;
dcopy.setoccA(closed[i]/2, false); dcopy.setoccA(open[a]/2, true);
dout.push_back(dcopy);
//if (dcopy.getocc(open[a]+1))
prob.push_back(schd.singleProbability);
//else
//prob.push_back(10.*schd.singleProbability);
alphaExcitation.push_back(closed[i]/2*Determinant::norbs+open[a]/2);
betaExcitation.push_back(0);
//cout << " alpha "<<*alphaExcitation.rbegin()<<" "<<closed[i]<<" "<<open[a]<<endl;
}
else {
Determinant dcopy = d;
dcopy.setoccB(closed[i]/2, false); dcopy.setoccB(open[a]/2, true);
dout.push_back(dcopy);
//if (dcopy.getocc(open[a]-1))
prob.push_back(schd.singleProbability);
//else
//prob.push_back(10.*schd.singleProbability);
alphaExcitation.push_back(0);
betaExcitation.push_back(closed[i]/2*Determinant::norbs+open[a]/2);
//cout << " beta "<<*betaExcitation.rbegin()<<" "<<closed[i]<<" "<<open[a]<<endl;
}
}
}
}
}
}
bool Walker::makeCleverMove(CPSSlater& w) {
auto random = std::bind(std::uniform_real_distribution<double>(0,1),
std::ref(generator));
double probForward, ovlpForward=1.0;
Walker wcopy = *this;
{
vector<Determinant> dout;
vector<double> prob;
vector<size_t> alphaExcitation, betaExcitation;
genAllMoves2(w, dout, prob, alphaExcitation, betaExcitation);
//pick one determinant at random
double cumulForward = 0;
vector<double> cumulative(prob.size(), 0);
double prev = 0.;
for (int i=0; i<prob.size(); i++) {
cumulForward += prob[i];
cumulative[i] = prev + prob[i];
prev = cumulative[i];
}
double selectForward = random()*cumulForward;
//cout << selectForward/cumulForward<<endl;
int detIndex= std::lower_bound(cumulative.begin(), cumulative.end(), selectForward)-cumulative.begin();
probForward = prob[detIndex]/cumulForward;
if (alphaExcitation[detIndex] != 0) {
int I = alphaExcitation[detIndex]/Determinant::norbs;
int A = alphaExcitation[detIndex]-I*Determinant::norbs;
//cout <<" a "<<I<<" "<<A<<" "<<wcopy.d<<" "<<alphaExcitation[detIndex]<<endl;
ovlpForward *= getDetFactorA(I, A, w);
wcopy.updateA(I, A, w);
}
if (betaExcitation[detIndex] != 0) {
int I = betaExcitation[detIndex]/Determinant::norbs;
int A = betaExcitation[detIndex]-I*Determinant::norbs;
//cout <<" b "<<I<<" "<<A<<endl;
ovlpForward *= getDetFactorB(I, A, w);
wcopy.updateB(I, A, w);
}
}
double probBackward, ovlpBackward;
{
vector<Determinant> dout;
vector<double> prob;
vector<size_t> alphaExcitation, betaExcitation;
wcopy.genAllMoves2(w, dout, prob, alphaExcitation, betaExcitation);
//pick one determinant at random
double cumulBackward = 0;
int index = -1;
for (int i=0; i<prob.size(); i++) {
cumulBackward += prob[i];
if (dout[i] == this->d)
index = i;
}
//cout << "backward "<<prob[index]<<" "<<dout[index]<<" "<<cumulBackward<<endl;
probBackward = prob[index]/cumulBackward;
}
//cout << ovlpForward<<" "<<probBackward<<" "<<probForward<<endl;
double acceptance = pow(ovlpForward,2)*probBackward/probForward;
if (acceptance > random()) {
*this = wcopy;
return true;
}
return false;
}
<file_sep>import numpy
import numpy.linalg
import math
import cmath, sys
#from pyscf import gto, scf, ao2mo
def findSiteInUnitCell(newsite, size, latticeVectors, sites):
for a in range(-1, 2):
for b in range(-1, 2):
newsitecopy = [newsite[0]+a*size*latticeVectors[0][0]+b*size*latticeVectors[1][0], newsite[1]+a*size*latticeVectors[0][1]+b*size*latticeVectors[1][\
1]]
for i in range(len(sites)):
if ( abs(sites[i][0] - newsitecopy[0]) <1e-10 and abs(sites[i][1] - newsitecopy[1]) <1e-10):
return True, i
return False, -1
sqrt2 = 2.**0.5
latticeV = [[0, sqrt2], [sqrt2, 0]]
unitCell = [[1./2., 1./2.], [1/2.+1./sqrt2, 1/2.+1./sqrt2]]
connectedSteps = [[-1./sqrt2,-1./sqrt2], [-1./sqrt2,1./sqrt2], [1./sqrt2,-1./sqrt2], [1./sqrt2,1./sqrt2]] #all the moves from a site to a interacting site
size = int(sys.argv[1])
U = 4.0
uhf = True
sites = []
for i in range(size):
for j in range(size):
sites.append([unitCell[0][0]+i*latticeV[0][0]+j*latticeV[1][0], unitCell[0][1]+i*latticeV[0][1]+j*latticeV[1][1]])
sites.append([unitCell[1][0]+i*latticeV[0][0]+j*latticeV[1][0], unitCell[1][1]+i*latticeV[0][1]+j*latticeV[1][1]])
nsites = len(sites)
print nsites
integrals = open("FCIDUMP", "w")
integrals.write("&FCI NORB=%d ,NELEC=%d ,MS2=0,\n"%(nsites, nsites))
integrals.write("ORBSYM=")
for i in range(nsites):
integrals.write("%1d,"%(1))
integrals.write("\n")
integrals.write("ISYM=1,\n")
integrals.write("&END\n")
int1 = numpy.zeros(shape=(nsites, nsites))
int2 = numpy.zeros(shape=(nsites, nsites, nsites, nsites))
fockUp = numpy.zeros(shape=(nsites, nsites))
fockDn = numpy.zeros(shape=(nsites, nsites))
for i in range(len(sites)):
for step in connectedSteps:
newsite = [sites[i][0]+step[0], sites[i][1]+step[1]]
#make all possible steps to try to come back to the lattice
found, index = findSiteInUnitCell(newsite, size, latticeV, sites)
if (found):
int1[i,index] = -1.0
fockUp[i, index] = -1.0
fockDn[i, index] = -1.0
integrals.write("%16.8f %4d %4d %4d %4d \n"%(-1., i+1, index+1, 0, 0))
#print -1.0, i+1,index+1,0,0
for i in range(len(sites)):
int2[i,i,i,i] = U
integrals.write("%16.8f %4d %4d %4d %4d \n"%(4., i+1, i+1, i+1, i+1))
#energies = numpy.zeros(shape=(size, size))
m = 0.3
n = nsites/2
for i in range(nsites):
fockUp[i, i] = U*(n-m*(-1)**(i+1))
fockDn[i, i] = U*(n+m*(-1)**(i+1))
ekUp, orbUp = numpy.linalg.eigh(fockUp)
ekDn, orbDn = numpy.linalg.eigh(fockDn)
fileHF = open("hf.txt", 'w')
for i in range(nsites):
for j in range(nsites):
fileHF.write('%16.10e '%(orbUp[i,j]))
for j in range(nsites):
fileHF.write('%16.10e '%(orbDn[i,j]))
fileHF.write('\n')
#mol = gto.M(verbose=4)
#mol.nelectron = nsites
#mol.incore_anyway = True
#mf = scf.RHF(mol)
#
#mf.get_hcore = lambda *args: int1
#mf.get_ovlp = lambda *args: numpy.eye(nsites)
#mf._eri = ao2mo.restore(8, int2, nsites)
#mf.level_shift_factor = 0.04
#mf.max_cycle = 200
#print mf.kernel()
#print mf.mo_energy
#
#fileHF = open("rhf.txt", 'w')
#for i in range(nsites):
# for j in range(nsites):
# fileHF.write('%16.10e '%(mf.mo_coeff[i,j]))
# fileHF.write('\n')
#
#delta = 1
#
#fileHF = open("hf.txt", 'w')
#for i in range(nsites):
# for j in range(nsites):
# uj = (1-mf.mo_energy[j]/(delta**2+mf.mo_energy[j]**2))**0.5/sqrt2
# vj = (1+mf.mo_energy[j]/(delta**2+mf.mo_energy[j]**2))**0.5/sqrt2
# coeff = uj*mf.mo_coeff[i,j] + (-1)**(i)*vj*mf.mo_coeff[i,j]
# fileHF.write('%16.10e '%(coeff))
# for j in range(nsites):
# uj = (1-mf.mo_energy[j]/(delta**2+mf.mo_energy[j]**2))**0.5/sqrt2
# vj = (1+mf.mo_energy[j]/(delta**2+mf.mo_energy[j]**2))**0.5/sqrt2
# coeff = uj*mf.mo_coeff[i,j] - (-1)**(i)*vj*mf.mo_coeff[i,j]
# fileHF.write('%16.10e '%(coeff))
# fileHF.write('\n')
#
correlators = []
for i in range(nsites):
c = [i]
for j in range(nsites):
if (int1[i,j] != 0):
c.append(j)
c = list(set(c))
correlators.append(c)
f = open("correlators.txt", 'w')
for c in correlators:
for t in c:
f.write("%d "%(t))
f.write("\n")
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "Determinants.h"
#include "SelectedCI.h"
#include "workingArray.h"
#include "integral.h"
SelectedCI::SelectedCI() {}
void SelectedCI::readWave() {
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
if (commrank == 0) cout << "Reading active space determinants\n";
shortSimpleDet NULL_SIMPLE_DET;
//for (int i=0; i++; i<2*innerDetLen)
// NULL_SIMPLE_DET[i] = 0.0;
DetsMap.set_empty_key(NULL_SIMPLE_DET);
if (boost::iequals(schd.determinantFile, "") || boost::iequals(schd.determinantFile, "bestDet"))
{
Determinant det;
for (int i = 0; i < nalpha; i++)
det.setoccA(i, true);
for (int i = 0; i < nbeta; i++)
det.setoccB(i, true);
DetsMap[det.getShortSimpleDet()] = 1.0;
bestDeterminant = det;
}
else
{
ifstream dump(schd.determinantFile.c_str());
int index = 0;
double bestCoeff = 0.0;
int orbsToLoopOver;
int offset;
Determinant detCAS;
if (schd.detsInCAS) {
orbsToLoopOver = schd.nciAct;
offset = schd.nciCore;
// Create determinant with all core orbitals occupied
for (int i=0; i<schd.nciCore; i++) {
detCAS.setoccA(i, true);
detCAS.setoccB(i, true);
}
} else {
orbsToLoopOver = Determinant::norbs;
offset = 0;
}
while (dump.good())
{
std::string Line;
std::getline(dump, Line);
boost::trim_if(Line, boost::is_any_of(", \t\n"));
vector<string> tok;
boost::split(tok, Line, boost::is_any_of(", \t\n"), boost::token_compress_on);
if (tok.size() > 2 )
{
double ci = atof(tok[0].c_str());
Determinant det ;
if (schd.detsInCAS) det = detCAS;
for (int i=0; i<orbsToLoopOver; i++)
{
if (boost::iequals(tok[1+i], "2"))
{
det.setoccA(i+offset, true);
det.setoccB(i+offset, true);
}
else if (boost::iequals(tok[1+i], "a"))
{
det.setoccA(i+offset, true);
det.setoccB(i+offset, false);
}
if (boost::iequals(tok[1+i], "b"))
{
det.setoccA(i+offset, false);
det.setoccB(i+offset, true);
}
if (boost::iequals(tok[1+i], "0"))
{
det.setoccA(i+offset, false);
det.setoccB(i+offset, false);
}
}
DetsMap[det.getShortSimpleDet()] = ci;
if (abs(ci) > abs(bestCoeff)) {
bestCoeff = ci;
bestDeterminant = det;
}
}
}
}
if (commrank == 0) {
cout << "Finished reading determinants, hash table bucket count: " << DetsMap.bucket_count() << endl;
}
}
//assuming bestDeterminant is an active space det, so no excitedOrbs
void SelectedCI::initWalker(SimpleWalker &walk) {
int norbs = Determinant::norbs;
walk.d = bestDeterminant;
walk.excitedHoles.clear();
walk.excitedOrbs.clear();
for (int i = 0; i < schd.nciCore; i++) {
if (!walk.d.getoccA(i)) walk.excitedHoles.insert(2*i);
if (!walk.d.getoccB(i)) walk.excitedHoles.insert(2*i+1);
}
for (int i = schd.nciCore + schd.nciAct; i < Determinant::norbs; i++) {
if (walk.d.getoccA(i)) walk.excitedOrbs.insert(2*i);
if (walk.d.getoccB(i)) walk.excitedOrbs.insert(2*i+1);
}
walk.getExcitationClass();
//vector<int> open;
//vector<int> closed;
//walk.d.getOpenClosed(open, closed);
//walk.energyIntermediates[0]= VectorXd::Zero(norbs);
//walk.energyIntermediates[1]= VectorXd::Zero(norbs);
//for (int i = 0; i < norbs; i++) {
// for (int j = 0; j < closed.size(); j++) {
// walk.energyIntermediates[0][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// walk.energyIntermediates[1][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// walk.energyIntermediates[closed[j] % 2][i] -= I2.Exchange(i, closed[j]/2);
// }
//}
}
void SelectedCI::initWalker(SimpleWalker &walk, Determinant& d) {
int norbs = Determinant::norbs;
walk.d = d;
walk.excitedHoles.clear();
walk.excitedOrbs.clear();
for (int i = 0; i < schd.nciCore; i++) {
if (!walk.d.getoccA(i)) walk.excitedHoles.insert(2*i);
if (!walk.d.getoccB(i)) walk.excitedHoles.insert(2*i+1);
}
for (int i = schd.nciCore + schd.nciAct; i < Determinant::norbs; i++) {
if (d.getoccA(i)) walk.excitedOrbs.insert(2*i);
if (d.getoccB(i)) walk.excitedOrbs.insert(2*i+1);
}
walk.getExcitationClass();
//vector<int> open;
//vector<int> closed;
//walk.d.getOpenClosed(open, closed);
//walk.energyIntermediates[0]= VectorXd::Zero(norbs);
//walk.energyIntermediates[1]= VectorXd::Zero(norbs);
//for (int i = 0; i < norbs; i++) {
// for (int j = 0; j < closed.size(); j++) {
// walk.energyIntermediates[0][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// walk.energyIntermediates[1][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// walk.energyIntermediates[closed[j] % 2][i] -= I2.Exchange(i, closed[j]/2);
// }
//}
}
//only used in deterministic calcs
double SelectedCI::getOverlapFactor(SimpleWalker& walk, Determinant& dcopy, bool doparity) {
auto it1 = DetsMap.find(walk.d.getShortSimpleDet());
auto it2 = DetsMap.find(dcopy.getShortSimpleDet());
if (it1 != DetsMap.end() && it2 != DetsMap.end())
return it2->second/it1->second;
else
return 0.0;
}
double SelectedCI::getOverlapFactor(int I, int A, SimpleWalker& walk, bool doparity) {
Determinant dcopy = walk.d;
dcopy.setocc(I, false);
dcopy.setocc(A, true);
auto it1 = DetsMap.find(walk.d.getShortSimpleDet());
auto it2 = DetsMap.find(dcopy.getShortSimpleDet());
if (it1 != DetsMap.end() && it2 != DetsMap.end())
return it2->second/it1->second;
else
return 0.0;
}
double SelectedCI::getOverlapFactor(int I, int J, int A, int B,
SimpleWalker& walk, bool doparity) {
// Single excitation
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, doparity);
Determinant dcopy = walk.d;
dcopy.setocc(I, false);
dcopy.setocc(A, true);
dcopy.setocc(J, false);
dcopy.setocc(B, true);
auto it1 = DetsMap.find(walk.d.getShortSimpleDet());
auto it2 = DetsMap.find(dcopy.getShortSimpleDet());
if (it1 != DetsMap.end() && it2 != DetsMap.end())
return it2->second/it1->second;
else
return 0.0;
}
double SelectedCI::Overlap(SimpleWalker& walk) {
auto it1 = DetsMap.find(walk.d.getShortSimpleDet());
if (it1 != DetsMap.end())
return it1->second;
else
return 0.0;
}
double SelectedCI::Overlap(Determinant& d) {
auto it1 = DetsMap.find(d.getShortSimpleDet());
if (it1 != DetsMap.end())
return it1->second;
else
return 0.0;
}
inline double SelectedCI::Overlap(shortSimpleDet& d) {
auto it1 = DetsMap.find(d);
if (it1 != DetsMap.end())
return it1->second;
else
return 0.0;
}
void SelectedCI::OverlapWithGradient(SimpleWalker &walk,
double &factor,
Eigen::VectorXd &grad) {
auto it1 = DetsMap.find(walk.d.getShortSimpleDet());
if (it1 != DetsMap.end())
grad[it1->second] = 1.0;
}
// This version of HamAndOvlp is the standard version, appropriate when
// performing VMC in the usual way, using a SelectedCI wave function.
// This function calculations both ovlp and ham. ovlp is the overlap of
// walk.d with the selected CI wave function. ham is the local energy
// on determinant walk.d, including the 1/ovlp factor.
void SelectedCI::HamAndOvlp(SimpleWalker &walk, double &ovlp, double &ham,
workingArray& work, double epsilon)
{
int norbs = Determinant::norbs;
ovlp = Overlap(walk);
ham = walk.d.Energy(I1, I2, coreE);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, epsilon, schd.screen,
work, false);
//loop over all the screened excitations
if (schd.debug) cout << "eloc excitations\nphi0 d.energy " << ham << endl;
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
// Find the parity
double parity = 1.;
Determinant dcopy = walk.d;
parity *= dcopy.parity(A/2, I/2, I%2);
dcopy.setocc(I, false);
dcopy.setocc(A, true);
if (ex2 != 0) {
parity *= dcopy.parity(B/2, J/2, J%2);
dcopy.setocc(J, false);
dcopy.setocc(B, true);
}
shortSimpleDet dcopySimple = dcopy.getShortSimpleDet();
double ovlpcopy = Overlap(dcopySimple);
double ovlpRatio = ovlpcopy / ovlp;
ham += parity * tia * ovlpRatio;
work.ovlpRatio[i] = ovlpRatio;
}
if (schd.debug) cout << endl;
}
void SelectedCI::HamAndOvlpAndSVTotal(SimpleWalker &walk, double &ovlp,
double &ham, double& SVTotal,
workingArray& work, double epsilon)
{
int norbs = Determinant::norbs;
ovlp = Overlap(walk);
ham = walk.d.Energy(I1, I2, coreE);
SVTotal = 0.0;
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, epsilon, schd.screen, work, false);
generateAllScreenedDoubleExcitation(walk.d, epsilon, schd.screen, work, false);
// Loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i];
int ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
// Find the parity
double parity = 1.;
Determinant dcopy = walk.d;
parity *= dcopy.parity(A/2, I/2, I%2);
dcopy.setocc(I, false);
dcopy.setocc(A, true);
if (ex2 != 0) {
parity *= dcopy.parity(B/2, J/2, J%2);
dcopy.setocc(J, false);
dcopy.setocc(B, true);
}
shortSimpleDet dcopySimple = dcopy.getShortSimpleDet();
double ovlpcopy = Overlap(dcopySimple);
double ovlpRatio = ovlpcopy / ovlp;
double contrib = parity * tia * ovlpRatio;
ham += contrib;
if (contrib > 0.0) {
SVTotal += contrib;
}
work.ovlpRatio[i] = ovlpRatio;
}
}
// This version of HamAndOvlp is used for MRCI and NEVPT calculations,
// where excitations occur into the first-order interacting space, but
// the selected CI wave function only has non-zero coefficients
// within the complete active space.
// *IMPORTANT* - ham here is <n|H|phi0>, *not* the ratio, to avoid out
// of active space singularitites. Also, ovlp = ham when ham is calculated.
void SelectedCI::HamAndOvlp(SimpleWalker &walk, double &ovlp, double &ham,
workingArray& work, bool dontCalcEnergy) {
walk.getExcitationClass();
int norbs = Determinant::norbs;
if (dontCalcEnergy) {
ovlp = Overlap(walk);
return;//ham *= ovlp;
}
else ham = 0.;//ham = ovlp * walk.d.Energy(I1, I2, coreE);
work.setCounterToZero();
if (walk.excitation_class == 0) {
generateAllScreenedSingleExcitationsCAS_0h0p(walk.d, schd.epsilon, schd.screen, work, false);
generateAllScreenedDoubleExcitationsCAS_0h0p(walk.d, schd.epsilon, work);
}
else if (walk.excitation_class == 1) {
generateAllScreenedSingleExcitationsCAS_0h1p(walk.d, schd.epsilon, schd.screen,
work, *walk.excitedOrbs.begin(), false);
generateAllScreenedDoubleExcitationsCAS_0h1p(walk.d, schd.epsilon, work, *walk.excitedOrbs.begin());
}
else if (walk.excitation_class == 2) {
generateAllScreenedExcitationsCAS_0h2p(walk.d, schd.epsilon, work, *walk.excitedOrbs.begin(),
*std::next(walk.excitedOrbs.begin()));
}
else if (walk.excitation_class == 3) {
generateAllScreenedSingleExcitationsCAS_1h0p(walk.d, schd.epsilon, schd.screen,
work, *walk.excitedHoles.begin(), false);
generateAllScreenedDoubleExcitationsCAS_1h0p(walk.d, schd.epsilon, work, *walk.excitedHoles.begin());
}
else if (walk.excitation_class == 4) {
generateAllScreenedSingleExcitationsCAS_1h1p(walk.d, schd.epsilon, schd.screen, work,
*walk.excitedOrbs.begin(), *walk.excitedHoles.begin(), false);
generateAllScreenedDoubleExcitationsCAS_1h1p(walk.d, schd.epsilon, work,
*walk.excitedOrbs.begin(), *walk.excitedHoles.begin());
}
else if (walk.excitation_class == 5) {
generateAllScreenedExcitationsCAS_1h2p(walk.d, schd.epsilon, work, *walk.excitedOrbs.begin(),
*std::next(walk.excitedOrbs.begin()), *walk.excitedHoles.begin());
}
else if (walk.excitation_class == 6) {
generateAllScreenedExcitationsCAS_2h0p(walk.d, schd.epsilon, work, *walk.excitedHoles.begin(),
*std::next(walk.excitedHoles.begin()));
}
else if (walk.excitation_class == 7) {
generateAllScreenedExcitationsCAS_2h1p(walk.d, schd.epsilon, work, *walk.excitedOrbs.begin(),
*walk.excitedHoles.begin(), *std::next(walk.excitedHoles.begin()));
}
else if (walk.excitation_class == 8) {
generateAllScreenedExcitationsCAS_2h2p(schd.epsilon, work,
*walk.excitedOrbs.begin(), *std::next(walk.excitedOrbs.begin()),
*walk.excitedHoles.begin(), *std::next(walk.excitedHoles.begin()));
}
//if (schd.debug) cout << "phi0 d.energy " << ham / ovlp << endl;
//loop over all the screened excitations
//cout << "m " << walk.d << endl;
//cout << "eloc excitations" << endl;
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double parity = 1.;
Determinant dcopy = walk.d;
parity *= dcopy.parity(A/2, I/2, I%2);
//if (A > I) parity *= -1. * dcopy.parity(A/2, I/2, I%2);
//else parity *= dcopy.parity(A/2, I/2, I%2);
dcopy.setocc(I, false);
dcopy.setocc(A, true);
if (ex2 != 0) {
parity *= dcopy.parity(B/2, J/2, J%2);
//if (B > J) parity *= -1 * dcopy.parity(B/2, J/2, J%2);
//else parity *= dcopy.parity(B/2, J/2, J%2);
dcopy.setocc(J, false);
dcopy.setocc(B, true);
}
shortSimpleDet dcopySimple = dcopy.getShortSimpleDet();
double ovlpcopy = Overlap(dcopySimple);
ham += tia * ovlpcopy * parity;
//if (schd.debug) cout << ex1 << " " << ex2 << " tia " << tia << " ovlpRatio " << ovlpcopy * parity << endl;
//work.ovlpRatio[i] = ovlp;
}
//if (schd.debug) cout << "ham " << ham << " ovlp " << ovlp << endl << endl;
ovlp = ham;
}
void SelectedCI::HamAndOvlpLanczos(SimpleWalker &walk,
Eigen::VectorXd &lanczosCoeffsSample,
double &ovlpSample,
workingArray& work,
workingArray& moreWork, double &alpha) {
work.setCounterToZero();
int norbs = Determinant::norbs;
double el0 = 0., el1 = 0., ovlp0 = 0., ovlp1 = 0.;
//ovlp0 = Overlap(walk);
HamAndOvlp(walk, ovlp0, el0, work);
std::vector<double> ovlp{0., 0., 0.};
ovlp[0] = ovlp0;
ovlp[1] = el0;
ovlp[2] = ovlp[0] + alpha * ovlp[1];
if (ovlp[2] == 0) return;
lanczosCoeffsSample[0] = ovlp[0] * el0 / (ovlp[2] * ovlp[2]);
lanczosCoeffsSample[1] = ovlp[1] * el0 / (ovlp[2] * ovlp[2]);
el1 = walk.d.Energy(I1, I2, coreE);
//workingArray work1;
//if (schd.debug) cout << "phi1 d.energy " << el1 << endl;
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
SimpleWalker walkCopy = walk;
double parity = 1.;
Determinant dcopy = walkCopy.d;
//if (A > I) parity *= -1. * dcopy.parity(A/2, I/2, I%2);
//else parity *= dcopy.parity(A/2, I/2, I%2);
parity *= dcopy.parity(A/2, I/2, I%2);
dcopy.setocc(I, false);
dcopy.setocc(A, true);
if (ex2 != 0) {
//if (B > J) parity *= -1 * dcopy.parity(B/2, J/2, J%2);
//else parity *= dcopy.parity(B/2, J/2, J%2);
parity *= dcopy.parity(B/2, J/2, J%2);
}
walkCopy.updateWalker(this->bestDeterminant, this->bestDeterminant, work.excitation1[i], work.excitation2[i], false);
moreWork.setCounterToZero();
HamAndOvlp(walkCopy, ovlp0, el0, moreWork);
ovlp1 = el0;
el1 += parity * tia * ovlp1 / ovlp[1];
work.ovlpRatio[i] = (ovlp0 + alpha * ovlp1) / ovlp[2];
//if (schd.debug) cout << work.excitation1[i] << " " << work.excitation2[i] << " tia " << tia << " ovlpRatio " << parity * ovlp1 / ovlp[1] << endl;
}
//if (schd.debug) cout << endl;
lanczosCoeffsSample[2] = ovlp[1] * ovlp[1] * el1 / (ovlp[2] * ovlp[2]);
lanczosCoeffsSample[3] = ovlp[0] * ovlp[0] / (ovlp[2] * ovlp[2]);
ovlpSample = ovlp[2];
}
//void SelectedCI::getVariables(Eigen::VectorXd &v) {
// for (int i=0; i<v.rows(); i++)
// v[i] = coeffs[i];
//}
//long SelectedCI::getNumVariables() {
// return DetsMap.size();
//}
//void SelectedCI::updateVariables(Eigen::VectorXd &v) {
// for (int i=0; i<v.rows(); i++)
// coeffs[i] = v[i];
//}
//void SelectedCI::printVariables() {
// for (int i=0; i<coeffs.size(); i++)
// cout << coeffs[i]<<endl;
//}
<file_sep>
#include "Determinants.h"
#include <boost/interprocess/managed_shared_memory.hpp>
#include "Eigen/Dense"
#include <string>
#include <ctime>
#include <sys/time.h>
#include "input.h"
#include "Profile.h"
#include "integral.h"
#ifndef SERIAL
#include "mpi.h"
#endif
int Determinant::norbs = 1;
int Determinant::nalpha = 1;
int Determinant::nbeta = 1;
int Determinant::EffDetLen = 1;
char Determinant::Trev = 0;
twoInt I2;
oneInt I1;
double coreE;
twoIntHeatBathSHM I2hb(1e-10);
twoIntHeatBathSHM I2hbCAS(1e-10);
Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic> Determinant::LexicalOrder ;
boost::interprocess::shared_memory_object int2Segment;
boost::interprocess::mapped_region regionInt2;
std::string shciint2;
boost::interprocess::shared_memory_object int2SHMSegment;
boost::interprocess::mapped_region regionInt2SHM;
std::string shciint2shm;
boost::interprocess::shared_memory_object int2SHMCASSegment;
boost::interprocess::mapped_region regionInt2SHMCAS;
std::string shciint2shmcas;
std::mt19937 generator;
#ifndef SERIAL
MPI_Comm shmcomm, localcomm;
#endif
int commrank, shmrank, localrank;
int commsize, shmsize, localsize;
schedule schd;
Profile prof;
double getTime() {
struct timeval start;
gettimeofday(&start, NULL);
return start.tv_sec + 1.e-6*start.tv_usec;
}
double startofCalc;
void license() {
return;
if (commrank == 0) {
cout << endl;
cout << endl;
cout << "**************************************************************"<<endl;
cout << "Dice Copyright (C) 2017 <NAME>"<<endl;
cout <<"This program is distributed in the hope that it will be useful,"<<endl;
cout <<"but WITHOUT ANY WARRANTY; without even the implied warranty of"<<endl;
cout <<"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."<<endl;
cout <<"See the GNU General Public License for more details."<<endl;
cout << endl<<endl;
cout << "Author: <NAME>"<<endl;
cout << "Please visit our group page for up to date information on other projects"<<endl;
cout << "http://www.colorado.edu/lab/sharmagroup/"<<endl;
cout << "**************************************************************"<<endl;
cout << endl;
cout << endl;
}
}
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace MRLCC_CAAV {
FTensorDecl TensorDecls[47] = {
/* 0*/{"t", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "cAae", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"k", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"k", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"k", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"W", "caca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 6*/{"W", "caac", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 7*/{"W", "cece", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 8*/{"W", "ceec", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 9*/{"W", "aeae", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"W", "aeea", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"W", "cccc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 13*/{"W", "e", "",USAGE_Intermediate, STORAGE_Memory},
/* 14*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"S1", "AaAa", "",USAGE_Density, STORAGE_Memory},
/* 18*/{"T", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 19*/{"p1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"p2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"Ap1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"Ap2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"b1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"b2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"b", "", "",USAGE_PlaceHolder, STORAGE_Memory},
/* 26*/{"P", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 27*/{"AP", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 28*/{"B1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 29*/{"B2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 30*/{"B", "", "",USAGE_PlaceHolder, STORAGE_Memory},
/* 31*/{"W", "eaca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 32*/{"W", "aeca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 33*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 34*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 35*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 36*/{"p", "", "",USAGE_PlaceHolder, STORAGE_Memory},
/* 37*/{"Ap", "", "",USAGE_PlaceHolder, STORAGE_Memory},
/* 38*/{"f", "ec", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 39*/{"I1", "ce", "", USAGE_PlaceHolder, STORAGE_Memory}, //21 SB
/* 40*/{"I2", "aaaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //16 S
/* 41*/{"I3", "aaaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //16 notused
/* 42*/{"I4", "ceaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //10 b
/* 43*/{"I5", "ceaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //22 SB
/* 44*/{"I6", "ce", "", USAGE_PlaceHolder, STORAGE_Memory}, //19 B
/* 45*/{"I7", "caa", "", USAGE_PlaceHolder, STORAGE_Memory}, //20 B
/* 46*/{"I8", "aea", "", USAGE_PlaceHolder, STORAGE_Memory}, //9 B
};
//Number of terms : 24
/*
FEqInfo EqsHandCode2[8] = {
{"JRSB,aAbB,QPbaRS,JPQA", 2.0 , 4, {21,9,16,19}}, //Ap1[JRSB] += 2.0 W[aAbB] E3[PSaQRb] p1[JPQA]
{"JRSB,aBAb,PQSRab,JPQA", -1.0 , 4, {21,10,16,19}}, //Ap1[JRSB] += -1.0 W[aBAb] E3[PSaQRb] p1[JPQA]
{"JRSB,IaJb,QPbaRS,IPQB", -2.0 , 4, {21,5,16,19}}, //Ap1[JRSB] += -2.0 W[IaJb] E3[PSaQRb] p1[IPQB]
{"JRSB,IabJ,QPbaRS,IPQB", 1.0 , 4, {21,6,16,19}}, //Ap1[JRSB] += 1.0 W[IabJ] E3[PSaQRb] p1[IPQB]
{"JRSB,Pabc,caQbRS,JPQB", 2.0 , 4, {21,12,16,19}}, //Ap1[JRSB] += 2.0 W[Pabc] E3[SabRcQ] p1[JPQB]
{"JRSB,Qabc,bPcaRS,JPQB", -2.0 , 4, {21,12,16,19}}, //Ap1[JRSB] += -2.0 W[Qabc] E3[PSabRc] p1[JPQB]
//
{"JRSB,aAbB,QPbaRS,JPQA", -1.0 , 4, {21,9,16,20}}, //Ap1[JRSB] += -1.0 W[aAbB] E3[PSaQRb] p2[JPQA]
{"JRSB,aBAb,bPQaRS,JPQA", -1.0 , 4, {21,10,16,20}}, //Ap1[JRSB] += -1.0 W[aBAb] E3[PSabRQ] p2[JPQA]
{"JRSB,IaJb,QPbaRS,IPQB", 1.0 , 4, {21,5,16,20}}, //Ap1[JRSB] += 1.0 W[IaJb] E3[PSaQRb] p2[IPQB]
{"JRSB,IabJ,bPQaRS,IPQB", 1.0 , 4, {21,6,16,20}}, //Ap1[JRSB] += 1.0 W[IabJ] E3[PSabRQ] p2[IPQB]
{"JRSB,Pabc,caQbRS,JPQB", -1.0 , 4, {21,12,16,20}}, //Ap1[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p2[JPQB]
{"JRSB,Qabc,bPcaRS,JPQB", 1.0 , 4, {21,12,16,20}}, //Ap1[JRSB] += 1.0 W[Qabc] E3[PSabRc] p2[JPQB]
//
{"JRSB,IaJb,QPbaRS,IPQB", 1.0 , 4, {22,5,16,19}}, //Ap2[JRSB] += 1.0 W[IaJb] E3[PSaQRb] p1[IPQB]
{"JRSB,Pabc,caQbRS,JPQB", -1.0 , 4, {22,12,16,19}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p1[JPQB]
{"JRSB,Qabc,bPcaRS,JPQB", 1.0 , 4, {22,12,16,19}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSabRc] p1[JPQB]
{"JRSB,aAbB,QPbaRS,JPQA", -1.0 , 4, {22,9,16,19}}, //Ap2[JRSB] += -1.0 W[aAbB] E3[PSaQRb] p1[JPQA]
{"JRSB,IabJ,QPRabS,IPQB", 1.0 , 4, {22,6,16,19}}, //Ap2[JRSB] += 1.0 W[IabJ] E3[PSaQbR] p1[IPQB]
{"JRSB,aBAb,PQaRSb,JPQA", -1.0 , 4, {22,10,16,19}}, //Ap2[JRSB] += -1.0 W[aBAb] E3[PSaQbR] p1[JPQA]
//
{"JRSB,aAbB,RPbaQS,JPQA", -1.0 , 4, {22,9,16,20}}, //Ap2[JRSB] += -1.0 W[aAbB] E3[PSaRQb] p2[JPQA]
{"JRSB,aBAb,RPQabS,JPQA", -1.0 , 4, {22,10,16,20}}, //Ap2[JRSB] += -1.0 W[aBAb] E3[PSaRbQ] p2[JPQA]
{"JRSB,IaJb,RPbaQS,IPQB", 1.0 , 4, {22,5,16,20}}, //Ap2[JRSB] += 1.0 W[IaJb] E3[PSaRQb] p2[IPQB]
{"JRSB,IabJ,bPRaQS,IPQB", 1.0 , 4, {22,6,16,20}}, //Ap2[JRSB] += 1.0 W[IabJ] E3[PSabQR] p2[IPQB]
{"JRSB,Pabc,caRbQS,JPQB", -1.0 , 4, {22,12,16,20}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabQcR] p2[JPQB]
{"JRSB,Qabc,RPcabS,JPQB", 1.0 , 4, {22,12,16,20}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSaRbc] p2[JPQB]
};
*/
//Number of terms : 24
FEqInfo EqsHandCode[24] = {
{"JB,aAbB,QPba,JPQA", 2.0 , 4, {39,9,40,19}}, //Ap1[JRSB] += 2.0 W[aAbB] E3[PSaQRb] p1[JPQA]
{"JB,aBAb,QPba,JPQA", -1.0 , 4, {39,10,40,19}}, //Ap1[JRSB] += -1.0 W[aBAb] E3[PSaQRb] p1[JPQA]
{"JB,IaJb,QPba,IPQB", -2.0 , 4, {39,5,40,19}}, //Ap1[JRSB] += -2.0 W[IaJb] E3[PSaQRb] p1[IPQB]
{"JB,IabJ,QPba,IPQB", 1.0 , 4, {39,6,40,19}}, //Ap1[JRSB] += 1.0 W[IabJ] E3[PSaQRb] p1[IPQB]
{"JB,Pabc,caQb,JPQB", 2.0 , 4, {39,12,40,19}}, //Ap1[JRSB] += 2.0 W[Pabc] E3[SabRcQ] p1[JPQB]
{"JB,Qabc,bPca,JPQB", -2.0 , 4, {39,12,40,19}}, //Ap1[JRSB] += -2.0 W[Qabc] E3[PSabRc] p1[JPQB]
//
{"JB,aAbB,QPba,JPQA", -1.0 , 4, {39,9,40,20}}, //Ap1[JRSB] += -1.0 W[aAbB] E3[PSaQRb] p2[JPQA]
{"JB,aBAb,bPQa,JPQA", -1.0 , 4, {39,10,40,20}}, //Ap1[JRSB] += -1.0 W[aBAb] E3[PSabRQ] p2[JPQA]
{"JB,IaJb,QPba,IPQB", 1.0 , 4, {39,5,40,20}}, //Ap1[JRSB] += 1.0 W[IaJb] E3[PSaQRb] p2[IPQB]
{"JB,IabJ,bPQa,IPQB", 1.0 , 4, {39,6,40,20}}, //Ap1[JRSB] += 1.0 W[IabJ] E3[PSabRQ] p2[IPQB]
{"JB,Pabc,caQb,JPQB", -1.0 , 4, {39,12,40,20}}, //Ap1[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p2[JPQB]
{"JB,Qabc,bPca,JPQB", 1.0 , 4, {39,12,40,20}}, //Ap1[JRSB] += 1.0 W[Qabc] E3[PSabRc] p2[JPQB]
//
{"JB,IaJb,QPba,IPQB", 1.0 , 4, {44,5,40,19}}, //Ap2[JRSB] += 1.0 W[IaJb] E3[PSaQRb] p1[IPQB]
{"JB,Pabc,caQb,JPQB", -1.0 , 4, {44,12,40,19}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p1[JPQB]
{"JB,Qabc,bPca,JPQB", 1.0 , 4, {44,12,40,19}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSabRc] p1[JPQB]
{"JB,aAbB,QPba,JPQA", -1.0 , 4, {44,9,40,19}}, //Ap2[JRSB] += -1.0 W[aAbB] E3[PSaQRb] p1[JPQA]
};
FEqInfo EqsHandCode2[8] = {
{"JB,IabJ,aQPb,IPQB", 1.0 , 4, {44,6,41,19}}, //Ap2[JRSB] += 1.0 W[IabJ] E3[PSaQbR] p1[IPQB]
{"JB,aBAb,aQPb,JPQA", -1.0 , 4, {44,10,41,19}}, //Ap2[JRSB] += -1.0 W[aBAb] E3[PSaQbR] p1[JPQA]
//
{"JB,aAbB,PbaQ,JPQA", -1.0 , 4, {44,9,41,20}}, //Ap2[JRSB] += -1.0 W[aAbB] E3[PSaRQb] p2[JPQA]
{"JB,aBAb,PQab,JPQA", -1.0 , 4, {44,10,41,20}}, //Ap2[JRSB] += -1.0 W[aBAb] E3[PSaRbQ] p2[JPQA]
{"JB,IaJb,PbaQ,IPQB", 1.0 , 4, {44,5,41,20}}, //Ap2[JRSB] += 1.0 W[IaJb] E3[PSaRQb] p2[IPQB]
{"JB,Qabc,Pcab,JPQB", 1.0 , 4, {44,12,41,20}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSaRbc] p2[JPQB]
{"JB,IabJ,abPQ,IPQB", 1.0 , 4, {44,6,41,20}}, //Ap2[JRSB] += 1.0 W[IabJ] E3[PSabQR] p2[IPQB]
{"JB,Pabc,bcaQ,JPQB", -1.0 , 4, {44,12,41,20}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabQcR] p2[JPQB]
};
//Number of terms : 192
FEqInfo EqsRes[192] = {
{"JRSB,PARB,SQ,JPQA", 2.0 , 4, {21,9,14,19}}, //Ap1[JRSB] += 2.0 W[PARB] E1[SQ] p1[JPQA]
{"JRSB,RBAP,SQ,JPQA", -1.0 , 4, {21,10,14,19}}, //Ap1[JRSB] += -1.0 W[RBAP] E1[SQ] p1[JPQA]
{"JRSB,IPJR,SQ,IPQB", -2.0 , 4, {21,5,14,19}}, //Ap1[JRSB] += -2.0 W[IPJR] E1[SQ] p1[IPQB]
{"JRSB,IRPJ,SQ,IPQB", 1.0 , 4, {21,6,14,19}}, //Ap1[JRSB] += 1.0 W[IRPJ] E1[SQ] p1[IPQB]
{"JRSB,IAJB,SQ,IRQA", -2.0 , 4, {21,7,14,19}}, //Ap1[JRSB] += -2.0 W[IAJB] E1[SQ] p1[IRQA]
{"JRSB,IBAJ,SQ,IRQA", 4.0 , 4, {21,8,14,19}}, //Ap1[JRSB] += 4.0 W[IBAJ] E1[SQ] p1[IRQA]
{"JRSB,PR,SQ,JPQB", 2.0 , 4, {21,3,14,19}}, //Ap1[JRSB] += 2.0 k[PR] E1[SQ] p1[JPQB]
{"JRSB,IJ,SQ,IRQB", -2.0 , 4, {21,2,14,19}}, //Ap1[JRSB] += -2.0 k[IJ] E1[SQ] p1[IRQB]
{"JRSB,AB,SQ,JRQA", 2.0 , 4, {21,4,14,19}}, //Ap1[JRSB] += 2.0 k[AB] E1[SQ] p1[JRQA]
{"JRSB,IJab,SQ,ba,IRQB", 2.0 , 5, {21,11,14,33,19}}, //Ap1[JRSB] += 2.0 W[IJab] E1[SQ] delta[ba] p1[IRQB]
{"JRSB,IaJb,SQ,ba,IRQB", -4.0 , 5, {21,11,14,33,19}}, //Ap1[JRSB] += -4.0 W[IaJb] E1[SQ] delta[ba] p1[IRQB]
{"JRSB,aPbR,SQ,ba,JPQB", 4.0 , 5, {21,5,14,33,19}}, //Ap1[JRSB] += 4.0 W[aPbR] E1[SQ] delta[ba] p1[JPQB]
{"JRSB,aRPb,SQ,ba,JPQB", -2.0 , 5, {21,6,14,33,19}}, //Ap1[JRSB] += -2.0 W[aRPb] E1[SQ] delta[ba] p1[JPQB]
{"JRSB,aAbB,SQ,ba,JRQA", 4.0 , 5, {21,7,14,33,19}}, //Ap1[JRSB] += 4.0 W[aAbB] E1[SQ] delta[ba] p1[JRQA]
{"JRSB,aBAb,SQ,ba,JRQA", -2.0 , 5, {21,8,14,33,19}}, //Ap1[JRSB] += -2.0 W[aBAb] E1[SQ] delta[ba] p1[JRQA]
{"JRSB,Qa,Sa,JRQB", -2.0 , 4, {21,3,14,19}}, //Ap1[JRSB] += -2.0 k[Qa] E1[Sa] p1[JRQB]
{"JRSB,aQcb,Sb,ca,JRQB", -4.0 , 5, {21,5,14,33,19}}, //Ap1[JRSB] += -4.0 W[aQcb] E1[Sb] delta[ca] p1[JRQB]
{"JRSB,aQbc,Sb,ca,JRQB", 2.0 , 5, {21,6,14,33,19}}, //Ap1[JRSB] += 2.0 W[aQbc] E1[Sb] delta[ca] p1[JRQB]
{"JRSB,IAJB,PSQR,IPQA", -2.0 , 4, {21,7,15,19}}, //Ap1[JRSB] += -2.0 W[IAJB] E2[PSQR] p1[IPQA]
{"JRSB,IBAJ,PSQR,IPQA", 4.0 , 4, {21,8,15,19}}, //Ap1[JRSB] += 4.0 W[IBAJ] E2[PSQR] p1[IPQA]
{"JRSB,IJ,PSQR,IPQB", -2.0 , 4, {21,2,15,19}}, //Ap1[JRSB] += -2.0 k[IJ] E2[PSQR] p1[IPQB]
{"JRSB,AB,PSQR,JPQA", 2.0 , 4, {21,4,15,19}}, //Ap1[JRSB] += 2.0 k[AB] E2[PSQR] p1[JPQA]
{"JRSB,PAaB,SaRQ,JPQA", 2.0 , 4, {21,9,15,19}}, //Ap1[JRSB] += 2.0 W[PAaB] E2[SaRQ] p1[JPQA]
{"JRSB,RAaB,PSQa,JPQA", 2.0 , 4, {21,9,15,19}}, //Ap1[JRSB] += 2.0 W[RAaB] E2[PSQa] p1[JPQA]
{"JRSB,RBAa,PSQa,JPQA", -1.0 , 4, {21,10,15,19}}, //Ap1[JRSB] += -1.0 W[RBAa] E2[PSQa] p1[JPQA]
{"JRSB,aBAP,SaRQ,JPQA", -1.0 , 4, {21,10,15,19}}, //Ap1[JRSB] += -1.0 W[aBAP] E2[SaRQ] p1[JPQA]
{"JRSB,IJab,PSQR,ba,IPQB", 2.0 , 5, {21,11,15,33,19}}, //Ap1[JRSB] += 2.0 W[IJab] E2[PSQR] delta[ba] p1[IPQB]
{"JRSB,IaJb,PSQR,ba,IPQB", -4.0 , 5, {21,11,15,33,19}}, //Ap1[JRSB] += -4.0 W[IaJb] E2[PSQR] delta[ba] p1[IPQB]
{"JRSB,IPJa,SaRQ,IPQB", -2.0 , 4, {21,5,15,19}}, //Ap1[JRSB] += -2.0 W[IPJa] E2[SaRQ] p1[IPQB]
{"JRSB,IRJa,PSQa,IPQB", -2.0 , 4, {21,5,15,19}}, //Ap1[JRSB] += -2.0 W[IRJa] E2[PSQa] p1[IPQB]
{"JRSB,IRaJ,PSQa,IPQB", 1.0 , 4, {21,6,15,19}}, //Ap1[JRSB] += 1.0 W[IRaJ] E2[PSQa] p1[IPQB]
{"JRSB,IaPJ,SaRQ,IPQB", 1.0 , 4, {21,6,15,19}}, //Ap1[JRSB] += 1.0 W[IaPJ] E2[SaRQ] p1[IPQB]
{"JRSB,aAbB,PSQR,ba,JPQA", 4.0 , 5, {21,7,15,33,19}}, //Ap1[JRSB] += 4.0 W[aAbB] E2[PSQR] delta[ba] p1[JPQA]
{"JRSB,aBAb,PSQR,ba,JPQA", -2.0 , 5, {21,8,15,33,19}}, //Ap1[JRSB] += -2.0 W[aBAb] E2[PSQR] delta[ba] p1[JPQA]
{"JRSB,Pa,SaRQ,JPQB", 2.0 , 4, {21,3,15,19}}, //Ap1[JRSB] += 2.0 k[Pa] E2[SaRQ] p1[JPQB]
{"JRSB,Qa,PSaR,JPQB", -2.0 , 4, {21,3,15,19}}, //Ap1[JRSB] += -2.0 k[Qa] E2[PSaR] p1[JPQB]
{"JRSB,PRab,SabQ,JPQB", 2.0 , 4, {21,12,15,19}}, //Ap1[JRSB] += 2.0 W[PRab] E2[SabQ] p1[JPQB]
{"JRSB,PaRb,SaQb,JPQB", 2.0 , 4, {21,12,15,19}}, //Ap1[JRSB] += 2.0 W[PaRb] E2[SaQb] p1[JPQB]
{"JRSB,QRab,PSab,JPQB", -2.0 , 4, {21,12,15,19}}, //Ap1[JRSB] += -2.0 W[QRab] E2[PSab] p1[JPQB]
{"JRSB,aAbB,SaQb,JRQA", 2.0 , 4, {21,9,15,19}}, //Ap1[JRSB] += 2.0 W[aAbB] E2[SaQb] p1[JRQA]
{"JRSB,aBAb,SaQb,JRQA", -1.0 , 4, {21,10,15,19}}, //Ap1[JRSB] += -1.0 W[aBAb] E2[SaQb] p1[JRQA]
{"JRSB,IaJb,SaQb,IRQB", -2.0 , 4, {21,5,15,19}}, //Ap1[JRSB] += -2.0 W[IaJb] E2[SaQb] p1[IRQB]
{"JRSB,aPcb,SbRQ,ca,JPQB", 4.0 , 5, {21,5,15,33,19}}, //Ap1[JRSB] += 4.0 W[aPcb] E2[SbRQ] delta[ca] p1[JPQB]
{"JRSB,aQcb,PSbR,ca,JPQB", -4.0 , 5, {21,5,15,33,19}}, //Ap1[JRSB] += -4.0 W[aQcb] E2[PSbR] delta[ca] p1[JPQB]
{"JRSB,IabJ,SaQb,IRQB", 1.0 , 4, {21,6,15,19}}, //Ap1[JRSB] += 1.0 W[IabJ] E2[SaQb] p1[IRQB]
{"JRSB,aQbc,PSbR,ca,JPQB", 2.0 , 5, {21,6,15,33,19}}, //Ap1[JRSB] += 2.0 W[aQbc] E2[PSbR] delta[ca] p1[JPQB]
{"JRSB,abPc,SbRQ,ca,JPQB", -2.0 , 5, {21,6,15,33,19}}, //Ap1[JRSB] += -2.0 W[abPc] E2[SbRQ] delta[ca] p1[JPQB]
{"JRSB,Qabc,Sabc,JRQB", -2.0 , 4, {21,12,15,19}}, //Ap1[JRSB] += -2.0 W[Qabc] E2[Sabc] p1[JRQB]
//
{"JRSB,PARB,SQ,JPQA", -1.0 , 4, {22,9,14,19}}, //Ap2[JRSB] += -1.0 W[PARB] E1[SQ] p1[JPQA]
{"JRSB,RBAP,SQ,JPQA", 2.0 , 4, {22,10,14,19}}, //Ap2[JRSB] += 2.0 W[RBAP] E1[SQ] p1[JPQA]
{"JRSB,IPJR,SQ,IPQB", 1.0 , 4, {22,5,14,19}}, //Ap2[JRSB] += 1.0 W[IPJR] E1[SQ] p1[IPQB]
{"JRSB,IRPJ,SQ,IPQB", -2.0 , 4, {22,6,14,19}}, //Ap2[JRSB] += -2.0 W[IRPJ] E1[SQ] p1[IPQB]
{"JRSB,IAJB,SQ,IRQA", 1.0 , 4, {22,7,14,19}}, //Ap2[JRSB] += 1.0 W[IAJB] E1[SQ] p1[IRQA]
{"JRSB,IBAJ,SQ,IRQA", -2.0 , 4, {22,8,14,19}}, //Ap2[JRSB] += -2.0 W[IBAJ] E1[SQ] p1[IRQA]
{"JRSB,PR,SQ,JPQB", -1.0 , 4, {22,3,14,19}}, //Ap2[JRSB] += -1.0 k[PR] E1[SQ] p1[JPQB]
{"JRSB,IJ,SQ,IRQB", 1.0 , 4, {22,2,14,19}}, //Ap2[JRSB] += 1.0 k[IJ] E1[SQ] p1[IRQB]
{"JRSB,AB,SQ,JRQA", -1.0 , 4, {22,4,14,19}}, //Ap2[JRSB] += -1.0 k[AB] E1[SQ] p1[JRQA]
{"JRSB,IJab,SQ,ba,IRQB", -1.0 , 5, {22,11,14,33,19}}, //Ap2[JRSB] += -1.0 W[IJab] E1[SQ] delta[ba] p1[IRQB]
{"JRSB,IaJb,SQ,ba,IRQB", 2.0 , 5, {22,11,14,33,19}}, //Ap2[JRSB] += 2.0 W[IaJb] E1[SQ] delta[ba] p1[IRQB]
{"JRSB,aPbR,SQ,ba,JPQB", -2.0 , 5, {22,5,14,33,19}}, //Ap2[JRSB] += -2.0 W[aPbR] E1[SQ] delta[ba] p1[JPQB]
{"JRSB,aRPb,SQ,ba,JPQB", 1.0 , 5, {22,6,14,33,19}}, //Ap2[JRSB] += 1.0 W[aRPb] E1[SQ] delta[ba] p1[JPQB]
{"JRSB,aAbB,SQ,ba,JRQA", -2.0 , 5, {22,7,14,33,19}}, //Ap2[JRSB] += -2.0 W[aAbB] E1[SQ] delta[ba] p1[JRQA]
{"JRSB,aBAb,SQ,ba,JRQA", 1.0 , 5, {22,8,14,33,19}}, //Ap2[JRSB] += 1.0 W[aBAb] E1[SQ] delta[ba] p1[JRQA]
{"JRSB,Qa,Sa,JRQB", 1.0 , 4, {22,3,14,19}}, //Ap2[JRSB] += 1.0 k[Qa] E1[Sa] p1[JRQB]
{"JRSB,aQcb,Sb,ca,JRQB", 2.0 , 5, {22,5,14,33,19}}, //Ap2[JRSB] += 2.0 W[aQcb] E1[Sb] delta[ca] p1[JRQB]
{"JRSB,aQbc,Sb,ca,JRQB", -1.0 , 5, {22,6,14,33,19}}, //Ap2[JRSB] += -1.0 W[aQbc] E1[Sb] delta[ca] p1[JRQB]
{"JRSB,IAJB,PSQR,IPQA", 1.0 , 4, {22,7,15,19}}, //Ap2[JRSB] += 1.0 W[IAJB] E2[PSQR] p1[IPQA]
{"JRSB,IBAJ,PSQR,IPQA", -2.0 , 4, {22,8,15,19}}, //Ap2[JRSB] += -2.0 W[IBAJ] E2[PSQR] p1[IPQA]
{"JRSB,IJ,PSQR,IPQB", 1.0 , 4, {22,2,15,19}}, //Ap2[JRSB] += 1.0 k[IJ] E2[PSQR] p1[IPQB]
{"JRSB,AB,PSQR,JPQA", -1.0 , 4, {22,4,15,19}}, //Ap2[JRSB] += -1.0 k[AB] E2[PSQR] p1[JPQA]
{"JRSB,PAaB,SaRQ,JPQA", -1.0 , 4, {22,9,15,19}}, //Ap2[JRSB] += -1.0 W[PAaB] E2[SaRQ] p1[JPQA]
{"JRSB,RAaB,PSQa,JPQA", -1.0 , 4, {22,9,15,19}}, //Ap2[JRSB] += -1.0 W[RAaB] E2[PSQa] p1[JPQA]
{"JRSB,RBAa,PSQa,JPQA", 2.0 , 4, {22,10,15,19}}, //Ap2[JRSB] += 2.0 W[RBAa] E2[PSQa] p1[JPQA]
{"JRSB,aBAP,SaQR,JPQA", -1.0 , 4, {22,10,15,19}}, //Ap2[JRSB] += -1.0 W[aBAP] E2[SaQR] p1[JPQA]
{"JRSB,IJab,PSQR,ba,IPQB", -1.0 , 5, {22,11,15,33,19}}, //Ap2[JRSB] += -1.0 W[IJab] E2[PSQR] delta[ba] p1[IPQB]
{"JRSB,IaJb,PSQR,ba,IPQB", 2.0 , 5, {22,11,15,33,19}}, //Ap2[JRSB] += 2.0 W[IaJb] E2[PSQR] delta[ba] p1[IPQB]
{"JRSB,IPJa,SaRQ,IPQB", 1.0 , 4, {22,5,15,19}}, //Ap2[JRSB] += 1.0 W[IPJa] E2[SaRQ] p1[IPQB]
{"JRSB,IRJa,PSQa,IPQB", 1.0 , 4, {22,5,15,19}}, //Ap2[JRSB] += 1.0 W[IRJa] E2[PSQa] p1[IPQB]
{"JRSB,IRaJ,PSQa,IPQB", -2.0 , 4, {22,6,15,19}}, //Ap2[JRSB] += -2.0 W[IRaJ] E2[PSQa] p1[IPQB]
{"JRSB,IaPJ,SaQR,IPQB", 1.0 , 4, {22,6,15,19}}, //Ap2[JRSB] += 1.0 W[IaPJ] E2[SaQR] p1[IPQB]
{"JRSB,aAbB,PSQR,ba,JPQA", -2.0 , 5, {22,7,15,33,19}}, //Ap2[JRSB] += -2.0 W[aAbB] E2[PSQR] delta[ba] p1[JPQA]
{"JRSB,aBAb,PSQR,ba,JPQA", 1.0 , 5, {22,8,15,33,19}}, //Ap2[JRSB] += 1.0 W[aBAb] E2[PSQR] delta[ba] p1[JPQA]
{"JRSB,Pa,SaRQ,JPQB", -1.0 , 4, {22,3,15,19}}, //Ap2[JRSB] += -1.0 k[Pa] E2[SaRQ] p1[JPQB]
{"JRSB,Qa,PSaR,JPQB", 1.0 , 4, {22,3,15,19}}, //Ap2[JRSB] += 1.0 k[Qa] E2[PSaR] p1[JPQB]
{"JRSB,PRab,SabQ,JPQB", -1.0 , 4, {22,12,15,19}}, //Ap2[JRSB] += -1.0 W[PRab] E2[SabQ] p1[JPQB]
{"JRSB,PaRb,SaQb,JPQB", -1.0 , 4, {22,12,15,19}}, //Ap2[JRSB] += -1.0 W[PaRb] E2[SaQb] p1[JPQB]
{"JRSB,QRab,PSab,JPQB", 1.0 , 4, {22,12,15,19}}, //Ap2[JRSB] += 1.0 W[QRab] E2[PSab] p1[JPQB]
{"JRSB,aAbB,SaQb,JRQA", -1.0 , 4, {22,9,15,19}}, //Ap2[JRSB] += -1.0 W[aAbB] E2[SaQb] p1[JRQA]
{"JRSB,aBAb,SabQ,JRQA", -1.0 , 4, {22,10,15,19}}, //Ap2[JRSB] += -1.0 W[aBAb] E2[SabQ] p1[JRQA]
{"JRSB,IaJb,SaQb,IRQB", 1.0 , 4, {22,5,15,19}}, //Ap2[JRSB] += 1.0 W[IaJb] E2[SaQb] p1[IRQB]
{"JRSB,aPcb,SbRQ,ca,JPQB", -2.0 , 5, {22,5,15,33,19}}, //Ap2[JRSB] += -2.0 W[aPcb] E2[SbRQ] delta[ca] p1[JPQB]
{"JRSB,aQcb,PSbR,ca,JPQB", 2.0 , 5, {22,5,15,33,19}}, //Ap2[JRSB] += 2.0 W[aQcb] E2[PSbR] delta[ca] p1[JPQB]
{"JRSB,IabJ,SabQ,IRQB", 1.0 , 4, {22,6,15,19}}, //Ap2[JRSB] += 1.0 W[IabJ] E2[SabQ] p1[IRQB]
{"JRSB,aQbc,PSbR,ca,JPQB", -1.0 , 5, {22,6,15,33,19}}, //Ap2[JRSB] += -1.0 W[aQbc] E2[PSbR] delta[ca] p1[JPQB]
{"JRSB,abPc,SbRQ,ca,JPQB", 1.0 , 5, {22,6,15,33,19}}, //Ap2[JRSB] += 1.0 W[abPc] E2[SbRQ] delta[ca] p1[JPQB]
{"JRSB,Qabc,Sabc,JRQB", 1.0 , 4, {22,12,15,19}}, //Ap2[JRSB] += 1.0 W[Qabc] E2[Sabc] p1[JRQB]
//
{"JRSB,PARB,SQ,JPQA", -1.0 , 4, {21,9,14,20}}, //Ap1[JRSB] += -1.0 W[PARB] E1[SQ] p2[JPQA]
{"JRSB,RBAP,SQ,JPQA", 2.0 , 4, {21,10,14,20}}, //Ap1[JRSB] += 2.0 W[RBAP] E1[SQ] p2[JPQA]
{"JRSB,IPJR,SQ,IPQB", 1.0 , 4, {21,5,14,20}}, //Ap1[JRSB] += 1.0 W[IPJR] E1[SQ] p2[IPQB]
{"JRSB,IRPJ,SQ,IPQB", -2.0 , 4, {21,6,14,20}}, //Ap1[JRSB] += -2.0 W[IRPJ] E1[SQ] p2[IPQB]
{"JRSB,IAJB,SQ,IRQA", 1.0 , 4, {21,7,14,20}}, //Ap1[JRSB] += 1.0 W[IAJB] E1[SQ] p2[IRQA]
{"JRSB,IBAJ,SQ,IRQA", -2.0 , 4, {21,8,14,20}}, //Ap1[JRSB] += -2.0 W[IBAJ] E1[SQ] p2[IRQA]
{"JRSB,PR,SQ,JPQB", -1.0 , 4, {21,3,14,20}}, //Ap1[JRSB] += -1.0 k[PR] E1[SQ] p2[JPQB]
{"JRSB,IJ,SQ,IRQB", 1.0 , 4, {21,2,14,20}}, //Ap1[JRSB] += 1.0 k[IJ] E1[SQ] p2[IRQB]
{"JRSB,AB,SQ,JRQA", -1.0 , 4, {21,4,14,20}}, //Ap1[JRSB] += -1.0 k[AB] E1[SQ] p2[JRQA]
{"JRSB,IJab,SQ,ba,IRQB", -1.0 , 5, {21,11,14,33,20}}, //Ap1[JRSB] += -1.0 W[IJab] E1[SQ] delta[ba] p2[IRQB]
{"JRSB,IaJb,SQ,ba,IRQB", 2.0 , 5, {21,11,14,33,20}}, //Ap1[JRSB] += 2.0 W[IaJb] E1[SQ] delta[ba] p2[IRQB]
{"JRSB,aPbR,SQ,ba,JPQB", -2.0 , 5, {21,5,14,33,20}}, //Ap1[JRSB] += -2.0 W[aPbR] E1[SQ] delta[ba] p2[JPQB]
{"JRSB,aRPb,SQ,ba,JPQB", 1.0 , 5, {21,6,14,33,20}}, //Ap1[JRSB] += 1.0 W[aRPb] E1[SQ] delta[ba] p2[JPQB]
{"JRSB,aAbB,SQ,ba,JRQA", -2.0 , 5, {21,7,14,33,20}}, //Ap1[JRSB] += -2.0 W[aAbB] E1[SQ] delta[ba] p2[JRQA]
{"JRSB,aBAb,SQ,ba,JRQA", 1.0 , 5, {21,8,14,33,20}}, //Ap1[JRSB] += 1.0 W[aBAb] E1[SQ] delta[ba] p2[JRQA]
{"JRSB,Qa,Sa,JRQB", 1.0 , 4, {21,3,14,20}}, //Ap1[JRSB] += 1.0 k[Qa] E1[Sa] p2[JRQB]
{"JRSB,aQcb,Sb,ca,JRQB", 2.0 , 5, {21,5,14,33,20}}, //Ap1[JRSB] += 2.0 W[aQcb] E1[Sb] delta[ca] p2[JRQB]
{"JRSB,aQbc,Sb,ca,JRQB", -1.0 , 5, {21,6,14,33,20}}, //Ap1[JRSB] += -1.0 W[aQbc] E1[Sb] delta[ca] p2[JRQB]
{"JRSB,IAJB,PSQR,IPQA", 1.0 , 4, {21,7,15,20}}, //Ap1[JRSB] += 1.0 W[IAJB] E2[PSQR] p2[IPQA]
{"JRSB,IBAJ,PSQR,IPQA", -2.0 , 4, {21,8,15,20}}, //Ap1[JRSB] += -2.0 W[IBAJ] E2[PSQR] p2[IPQA]
{"JRSB,IJ,PSQR,IPQB", 1.0 , 4, {21,2,15,20}}, //Ap1[JRSB] += 1.0 k[IJ] E2[PSQR] p2[IPQB]
{"JRSB,AB,PSQR,JPQA", -1.0 , 4, {21,4,15,20}}, //Ap1[JRSB] += -1.0 k[AB] E2[PSQR] p2[JPQA]
{"JRSB,PAaB,SaRQ,JPQA", -1.0 , 4, {21,9,15,20}}, //Ap1[JRSB] += -1.0 W[PAaB] E2[SaRQ] p2[JPQA]
{"JRSB,RAaB,PSQa,JPQA", -1.0 , 4, {21,9,15,20}}, //Ap1[JRSB] += -1.0 W[RAaB] E2[PSQa] p2[JPQA]
{"JRSB,RBAa,PSaQ,JPQA", -1.0 , 4, {21,10,15,20}}, //Ap1[JRSB] += -1.0 W[RBAa] E2[PSaQ] p2[JPQA]
{"JRSB,aBAP,SaRQ,JPQA", 2.0 , 4, {21,10,15,20}}, //Ap1[JRSB] += 2.0 W[aBAP] E2[SaRQ] p2[JPQA]
{"JRSB,IJab,PSQR,ba,IPQB", -1.0 , 5, {21,11,15,33,20}}, //Ap1[JRSB] += -1.0 W[IJab] E2[PSQR] delta[ba] p2[IPQB]
{"JRSB,IaJb,PSQR,ba,IPQB", 2.0 , 5, {21,11,15,33,20}}, //Ap1[JRSB] += 2.0 W[IaJb] E2[PSQR] delta[ba] p2[IPQB]
{"JRSB,IPJa,SaRQ,IPQB", 1.0 , 4, {21,5,15,20}}, //Ap1[JRSB] += 1.0 W[IPJa] E2[SaRQ] p2[IPQB]
{"JRSB,IRJa,PSQa,IPQB", 1.0 , 4, {21,5,15,20}}, //Ap1[JRSB] += 1.0 W[IRJa] E2[PSQa] p2[IPQB]
{"JRSB,IRaJ,PSaQ,IPQB", 1.0 , 4, {21,6,15,20}}, //Ap1[JRSB] += 1.0 W[IRaJ] E2[PSaQ] p2[IPQB]
{"JRSB,IaPJ,SaRQ,IPQB", -2.0 , 4, {21,6,15,20}}, //Ap1[JRSB] += -2.0 W[IaPJ] E2[SaRQ] p2[IPQB]
{"JRSB,aAbB,PSQR,ba,JPQA", -2.0 , 5, {21,7,15,33,20}}, //Ap1[JRSB] += -2.0 W[aAbB] E2[PSQR] delta[ba] p2[JPQA]
{"JRSB,aBAb,PSQR,ba,JPQA", 1.0 , 5, {21,8,15,33,20}}, //Ap1[JRSB] += 1.0 W[aBAb] E2[PSQR] delta[ba] p2[JPQA]
{"JRSB,Pa,SaRQ,JPQB", -1.0 , 4, {21,3,15,20}}, //Ap1[JRSB] += -1.0 k[Pa] E2[SaRQ] p2[JPQB]
{"JRSB,Qa,PSaR,JPQB", 1.0 , 4, {21,3,15,20}}, //Ap1[JRSB] += 1.0 k[Qa] E2[PSaR] p2[JPQB]
{"JRSB,PRab,SabQ,JPQB", -1.0 , 4, {21,12,15,20}}, //Ap1[JRSB] += -1.0 W[PRab] E2[SabQ] p2[JPQB]
{"JRSB,PaRb,SaQb,JPQB", -1.0 , 4, {21,12,15,20}}, //Ap1[JRSB] += -1.0 W[PaRb] E2[SaQb] p2[JPQB]
{"JRSB,QRab,PSab,JPQB", 1.0 , 4, {21,12,15,20}}, //Ap1[JRSB] += 1.0 W[QRab] E2[PSab] p2[JPQB]
{"JRSB,aAbB,SaQb,JRQA", -1.0 , 4, {21,9,15,20}}, //Ap1[JRSB] += -1.0 W[aAbB] E2[SaQb] p2[JRQA]
{"JRSB,aBAb,SabQ,JRQA", -1.0 , 4, {21,10,15,20}}, //Ap1[JRSB] += -1.0 W[aBAb] E2[SabQ] p2[JRQA]
{"JRSB,IaJb,SaQb,IRQB", 1.0 , 4, {21,5,15,20}}, //Ap1[JRSB] += 1.0 W[IaJb] E2[SaQb] p2[IRQB]
{"JRSB,aPcb,SbRQ,ca,JPQB", -2.0 , 5, {21,5,15,33,20}}, //Ap1[JRSB] += -2.0 W[aPcb] E2[SbRQ] delta[ca] p2[JPQB]
{"JRSB,aQcb,PSbR,ca,JPQB", 2.0 , 5, {21,5,15,33,20}}, //Ap1[JRSB] += 2.0 W[aQcb] E2[PSbR] delta[ca] p2[JPQB]
{"JRSB,IabJ,SabQ,IRQB", 1.0 , 4, {21,6,15,20}}, //Ap1[JRSB] += 1.0 W[IabJ] E2[SabQ] p2[IRQB]
{"JRSB,aQbc,PSbR,ca,JPQB", -1.0 , 5, {21,6,15,33,20}}, //Ap1[JRSB] += -1.0 W[aQbc] E2[PSbR] delta[ca] p2[JPQB]
{"JRSB,abPc,SbRQ,ca,JPQB", 1.0 , 5, {21,6,15,33,20}}, //Ap1[JRSB] += 1.0 W[abPc] E2[SbRQ] delta[ca] p2[JPQB]
{"JRSB,Qabc,Sabc,JRQB", 1.0 , 4, {21,12,15,20}}, //Ap1[JRSB] += 1.0 W[Qabc] E2[Sabc] p2[JRQB]
//
{"JRSB,PARB,SQ,JPQA", 2.0 , 4, {22,9,14,20}}, //Ap2[JRSB] += 2.0 W[PARB] E1[SQ] p2[JPQA]
{"JRSB,RBAP,SQ,JPQA", -1.0 , 4, {22,10,14,20}}, //Ap2[JRSB] += -1.0 W[RBAP] E1[SQ] p2[JPQA]
{"JRSB,IPJR,SQ,IPQB", -2.0 , 4, {22,5,14,20}}, //Ap2[JRSB] += -2.0 W[IPJR] E1[SQ] p2[IPQB]
{"JRSB,IRPJ,SQ,IPQB", 4.0 , 4, {22,6,14,20}}, //Ap2[JRSB] += 4.0 W[IRPJ] E1[SQ] p2[IPQB]
{"JRSB,IAJB,SQ,IRQA", -2.0 , 4, {22,7,14,20}}, //Ap2[JRSB] += -2.0 W[IAJB] E1[SQ] p2[IRQA]
{"JRSB,IBAJ,SQ,IRQA", 1.0 , 4, {22,8,14,20}}, //Ap2[JRSB] += 1.0 W[IBAJ] E1[SQ] p2[IRQA]
{"JRSB,PR,SQ,JPQB", 2.0 , 4, {22,3,14,20}}, //Ap2[JRSB] += 2.0 k[PR] E1[SQ] p2[JPQB]
{"JRSB,IJ,SQ,IRQB", -2.0 , 4, {22,2,14,20}}, //Ap2[JRSB] += -2.0 k[IJ] E1[SQ] p2[IRQB]
{"JRSB,AB,SQ,JRQA", 2.0 , 4, {22,4,14,20}}, //Ap2[JRSB] += 2.0 k[AB] E1[SQ] p2[JRQA]
{"JRSB,IJab,SQ,ba,IRQB", 2.0 , 5, {22,11,14,33,20}}, //Ap2[JRSB] += 2.0 W[IJab] E1[SQ] delta[ba] p2[IRQB]
{"JRSB,IaJb,SQ,ba,IRQB", -4.0 , 5, {22,11,14,33,20}}, //Ap2[JRSB] += -4.0 W[IaJb] E1[SQ] delta[ba] p2[IRQB]
{"JRSB,aPbR,SQ,ba,JPQB", 4.0 , 5, {22,5,14,33,20}}, //Ap2[JRSB] += 4.0 W[aPbR] E1[SQ] delta[ba] p2[JPQB]
{"JRSB,aRPb,SQ,ba,JPQB", -2.0 , 5, {22,6,14,33,20}}, //Ap2[JRSB] += -2.0 W[aRPb] E1[SQ] delta[ba] p2[JPQB]
{"JRSB,aAbB,SQ,ba,JRQA", 4.0 , 5, {22,7,14,33,20}}, //Ap2[JRSB] += 4.0 W[aAbB] E1[SQ] delta[ba] p2[JRQA]
{"JRSB,aBAb,SQ,ba,JRQA", -2.0 , 5, {22,8,14,33,20}}, //Ap2[JRSB] += -2.0 W[aBAb] E1[SQ] delta[ba] p2[JRQA]
{"JRSB,Qa,Sa,JRQB", -2.0 , 4, {22,3,14,20}}, //Ap2[JRSB] += -2.0 k[Qa] E1[Sa] p2[JRQB]
{"JRSB,aQcb,Sb,ca,JRQB", -4.0 , 5, {22,5,14,33,20}}, //Ap2[JRSB] += -4.0 W[aQcb] E1[Sb] delta[ca] p2[JRQB]
{"JRSB,aQbc,Sb,ca,JRQB", 2.0 , 5, {22,6,14,33,20}}, //Ap2[JRSB] += 2.0 W[aQbc] E1[Sb] delta[ca] p2[JRQB]
{"JRSB,IAJB,PSRQ,IPQA", 1.0 , 4, {22,7,15,20}}, //Ap2[JRSB] += 1.0 W[IAJB] E2[PSRQ] p2[IPQA]
{"JRSB,IBAJ,PSQR,IPQA", 1.0 , 4, {22,8,15,20}}, //Ap2[JRSB] += 1.0 W[IBAJ] E2[PSQR] p2[IPQA]
{"JRSB,IJ,PSRQ,IPQB", 1.0 , 4, {22,2,15,20}}, //Ap2[JRSB] += 1.0 k[IJ] E2[PSRQ] p2[IPQB]
{"JRSB,AB,PSRQ,JPQA", -1.0 , 4, {22,4,15,20}}, //Ap2[JRSB] += -1.0 k[AB] E2[PSRQ] p2[JPQA]
{"JRSB,PAaB,SaQR,JPQA", -1.0 , 4, {22,9,15,20}}, //Ap2[JRSB] += -1.0 W[PAaB] E2[SaQR] p2[JPQA]
{"JRSB,RAaB,PSaQ,JPQA", -1.0 , 4, {22,9,15,20}}, //Ap2[JRSB] += -1.0 W[RAaB] E2[PSaQ] p2[JPQA]
{"JRSB,RBAa,PSQa,JPQA", -1.0 , 4, {22,10,15,20}}, //Ap2[JRSB] += -1.0 W[RBAa] E2[PSQa] p2[JPQA]
{"JRSB,aBAP,SaRQ,JPQA", -1.0 , 4, {22,10,15,20}}, //Ap2[JRSB] += -1.0 W[aBAP] E2[SaRQ] p2[JPQA]
{"JRSB,IJab,PSRQ,ba,IPQB", -1.0 , 5, {22,11,15,33,20}}, //Ap2[JRSB] += -1.0 W[IJab] E2[PSRQ] delta[ba] p2[IPQB]
{"JRSB,IaJb,PSRQ,ba,IPQB", 2.0 , 5, {22,11,15,33,20}}, //Ap2[JRSB] += 2.0 W[IaJb] E2[PSRQ] delta[ba] p2[IPQB]
{"JRSB,IPJa,SaQR,IPQB", 1.0 , 4, {22,5,15,20}}, //Ap2[JRSB] += 1.0 W[IPJa] E2[SaQR] p2[IPQB]
{"JRSB,IRJa,PSaQ,IPQB", 1.0 , 4, {22,5,15,20}}, //Ap2[JRSB] += 1.0 W[IRJa] E2[PSaQ] p2[IPQB]
{"JRSB,IRaJ,PSaQ,IPQB", -2.0 , 4, {22,6,15,20}}, //Ap2[JRSB] += -2.0 W[IRaJ] E2[PSaQ] p2[IPQB]
{"JRSB,IaPJ,SaQR,IPQB", -2.0 , 4, {22,6,15,20}}, //Ap2[JRSB] += -2.0 W[IaPJ] E2[SaQR] p2[IPQB]
{"JRSB,aAbB,PSRQ,ba,JPQA", -2.0 , 5, {22,7,15,33,20}}, //Ap2[JRSB] += -2.0 W[aAbB] E2[PSRQ] delta[ba] p2[JPQA]
{"JRSB,aBAb,PSRQ,ba,JPQA", 1.0 , 5, {22,8,15,33,20}}, //Ap2[JRSB] += 1.0 W[aBAb] E2[PSRQ] delta[ba] p2[JPQA]
{"JRSB,Pa,SaQR,JPQB", -1.0 , 4, {22,3,15,20}}, //Ap2[JRSB] += -1.0 k[Pa] E2[SaQR] p2[JPQB]
{"JRSB,Qa,PSRa,JPQB", 1.0 , 4, {22,3,15,20}}, //Ap2[JRSB] += 1.0 k[Qa] E2[PSRa] p2[JPQB]
{"JRSB,PRab,SaQb,JPQB", -1.0 , 4, {22,12,15,20}}, //Ap2[JRSB] += -1.0 W[PRab] E2[SaQb] p2[JPQB]
{"JRSB,PaRb,SaQb,JPQB", 2.0 , 4, {22,12,15,20}}, //Ap2[JRSB] += 2.0 W[PaRb] E2[SaQb] p2[JPQB]
{"JRSB,QRab,PSba,JPQB", 1.0 , 4, {22,12,15,20}}, //Ap2[JRSB] += 1.0 W[QRab] E2[PSba] p2[JPQB]
{"JRSB,aAbB,SaQb,JRQA", 2.0 , 4, {22,9,15,20}}, //Ap2[JRSB] += 2.0 W[aAbB] E2[SaQb] p2[JRQA]
{"JRSB,aBAb,SabQ,JRQA", 2.0 , 4, {22,10,15,20}}, //Ap2[JRSB] += 2.0 W[aBAb] E2[SabQ] p2[JRQA]
{"JRSB,IaJb,SaQb,IRQB", -2.0 , 4, {22,5,15,20}}, //Ap2[JRSB] += -2.0 W[IaJb] E2[SaQb] p2[IRQB]
{"JRSB,aPcb,SbQR,ca,JPQB", -2.0 , 5, {22,5,15,33,20}}, //Ap2[JRSB] += -2.0 W[aPcb] E2[SbQR] delta[ca] p2[JPQB]
{"JRSB,aQcb,PSRb,ca,JPQB", 2.0 , 5, {22,5,15,33,20}}, //Ap2[JRSB] += 2.0 W[aQcb] E2[PSRb] delta[ca] p2[JPQB]
{"JRSB,IabJ,SaQb,IRQB", 1.0 , 4, {22,6,15,20}}, //Ap2[JRSB] += 1.0 W[IabJ] E2[SaQb] p2[IRQB]
{"JRSB,aQbc,PSRb,ca,JPQB", -1.0 , 5, {22,6,15,33,20}}, //Ap2[JRSB] += -1.0 W[aQbc] E2[PSRb] delta[ca] p2[JPQB]
{"JRSB,abPc,SbQR,ca,JPQB", 1.0 , 5, {22,6,15,33,20}}, //Ap2[JRSB] += 1.0 W[abPc] E2[SbQR] delta[ca] p2[JPQB]
{"JRSB,Qabc,Sabc,JRQB", -2.0 , 4, {22,12,15,20}}, //Ap2[JRSB] += -2.0 W[Qabc] E2[Sabc] p2[JRQB]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[8] = {
{"IPSA,QS,APIQ", 2.0, 3, {23, 14, 31}},
{"IRSA,PSQR,APIQ", 2.0, 3, {23, 15, 31}},
{"IPSA,QS,APIQ", -1.0, 3, {24, 14, 31}},
{"IRSA,PSQR,APIQ",-1.0, 3, {24, 15, 31}},
{"IPSA,QS,PAIQ", -1.0, 3, {23, 14, 32}},
{"IRSA,PSQR,PAIQ",-1.0, 3, {23, 15, 32}},
{"IPSA,QS,PAIQ", 2.0, 3, {24, 14, 32}},
{"IRSA,PSRQ,PAIQ",-1.0, 3, {24, 15, 32}},
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "MRLCC_CAAV";
Out.perturberClass = "CAAV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 47;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsHandCode = FEqSet(&EqsHandCode[0], 16, "MRLCC_CAAV/Res");
Out.EqsHandCode2 = FEqSet(&EqsHandCode2[0], 8, "MRLCC_CAAV/Res");
Out.EqsRes = FEqSet(&EqsRes[0], 192, "MRLCC_CAAV/Res");
Out.Overlap = FEqSet(&Overlap[0], 8, "MRLCC_CAAV/Overlap");
};
};
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ExcitationOperators_HEADER_H
#define ExcitationOperators_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/array.hpp>
#include <utility>
#include <unordered_set>
class Determinant;
using namespace std;
class Operator {
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & cre
& des
& n
& nops;
}
public:
std::array<short, 4> cre;
std::array<short, 4> des;
int n;
int nops;
Operator();
//a1^\dag i1
Operator(short a1, short i1);
//a2^\dag i2 a1^\dag i1
Operator(short a1, short a2, short i1, short i2);
friend ostream& operator << (ostream& os, Operator& o);
bool apply(Determinant &dcopy, int op);
bool apply(Determinant &dcopy, const unordered_set<int> &excitedOrbs);
static void populateSinglesToOpList(vector<Operator>& oplist, vector<double>& hamElements, double screen=0.0);
static void populateScreenedDoublesToOpList(vector<Operator>& oplist, vector<double>& hamElements, double screen);
static void populateDoublesToOpList(vector<Operator>& oplist, vector<double>& hamElements);
};
////normal ordered
//class NormalOperator {
// private:
// friend class boost::serialization::access;
// template <class Archive>
// void serialize(Archive &ar, const unsigned int version)
// {
// ar & cre
// & des
// & n
// & nops;
// }
//
// public:
//
// std::array<short, 4> cre;
// std::array<short, 4> des;
// int n;
// int nops;
//
// NormalOperator() : cre ({0,0,0,0}), des ({0,0,0,0})
// {
// n = 0;
// nops = 1;
// }
//
// //a1^\dag i1
// NormalOperator(short a1, short i1) : cre ({a1}), des ({i1})
// {
// n = 1;
// nops = 1;
// }
//
// //a2^\dag a1^\dag i2 i1
// NormalOperator(short a2, short a1, short i2, short i1) :cre ({a2, a1}), des ({i2, i1})
// {
// n = 2;
// nops = 1;
// }
//
// friend ostream& operator << (ostream& os, Operator& o)
// {
// for (int i = 0; i < o.n; i++)
// os << o.cre[i] << " ";
// os << "; ";
// for (int i = 0; i < o.n; i++)
// os << o.des[i] << " ";
// os << endl;
// return os;
// }
//
// //apply to a bra: < dcopy | NormalOperator
// bool apply(Determinant &dcopy, int op)
// {
// for (int j = 0; j < n; j++) {
// if (dcopy.getocc(cre[j]) == true)
// dcopy.setocc(cre[j], false);
// else
// return false;
// }
//
// for (int j = 0; j < n; j++) {
// if (dcopy.getocc(des[j]) == false)
// dcopy.setocc(des[j], true);
// else
// return false;
// }
//
// return true;
// }
//
// static void populateSinglesToOpList(vector<NormalOperator>& oplist)
// {
// int norbs = Determinant::norbs;
// for (int i = 0; i < 2 * norbs; i++) {
// for (int j = 0; j < 2 * norbs; j++) {
// //if (I2hb.Singles(i, j) > schd.epsilon )
// if (i % 2 == j % 2)
// oplist.push_back(NormalOperator(i, j));
// }
// }
// }
//
// //used in Lanczos
// static void populateSinglesToOpList(vector<NormalOperator>& oplist, vector<double>& hamElements) {
// int norbs = Determinant::norbs;
// for (int i = 0; i < 2 * norbs; i++) {
// for (int j = 0; j < 2 * norbs; j++) {
// //if (I2hb.Singles(i, j) > schd.epsilon )
// if (i % 2 == j % 2) {
// oplist.push_back(NormalOperator(i, j));
// hamElements.push_back(I1(i, j));
// }
// }
// }
// }
//
// static void populateScreenedDoublesToOpList(vector<NormalOperator>& oplist, double screen)
// {
// int norbs = Determinant::norbs;
// for (int p = 0; p < 2 * norbs; i++) {
// for (int q = 0; q < 2 * norbs; j++) {
// for (int r = 0; r < 2 * norbs; k++) {
// for (int s = 0; s < 2 * norbs; k++) {
// if (p != r && s != q) {
// double hamCoeff = I2(p, q, r, s);
// if (hamCoeff > screen)
// oplist.push_back(NormalOperator(p, r, s, q));
// }
// }
// }
// }
// }
// }
//
// //used in Lanczos
// static void populateScreenedDoublesToOpList(vector<NormalOperator>& oplist, vector<double>& hamElements, double screen)
// {
// int norbs = Determinant::norbs;
// for (int p = 0; p < 2 * norbs; i++) {
// for (int q = 0; q < 2 * norbs; j++) {
// for (int r = 0; r < 2 * norbs; k++) {
// for (int s = 0; s < 2 * norbs; k++) {
// if (p != r && s != q) {
// double hamCoeff = I2(p, q, r, s);
// if (hamCoeff > screen) {
// oplist.push_back(NormalOperator(p, r, s, q));
// hamElements.push_back(hamCoeff);
// }
// }
// }
// }
// }
// }
// }
//
//};
class SpinFreeOperator {
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & ops
& nops;
}
public:
vector<Operator> ops;
int nops;
SpinFreeOperator();
//a1^\dag i1
SpinFreeOperator(short a1, short i1);
//a2^\dag i2 a1^\dag i1
SpinFreeOperator(short a1, short a2, short i1, short i2);
friend ostream& operator << (ostream& os, const SpinFreeOperator& o);
bool apply(Determinant &dcopy, int op);
bool apply(Determinant &dcopy, const unordered_set<int> &excitedOrbs) {};
static void populateSinglesToOpList(vector<SpinFreeOperator>& oplist, vector<double>& hamElements, double screen =0.0);
static void populateScreenedDoublesToOpList(vector<SpinFreeOperator>& oplist, vector<double>& hamElements, double screen);
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CorrelatedWavefunction_HEADER_H
#define CorrelatedWavefunction_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <unordered_set>
#include "input.h"
#include "Walker.h"
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
class workingArray;
class Determinant;
/**
* This is the wavefunction, it is a product of the CPS and a linear combination of
* slater determinants
*/
template<typename Corr, typename Reference> //Corr = CPS/JAstrow or Reference = RHF/U
struct CorrelatedWavefunction {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & corr
& ref;
}
public:
using CorrType = Corr;
using ReferenceType = Reference;
Corr corr; //The jastrow factors
Reference ref; //reference
CorrelatedWavefunction() {};
Reference& getRef() { return ref; }
Corr& getCorr() { return corr; }
void initWalker(Walker<Corr, Reference> &walk)
{
walk = Walker<Corr, Reference>(corr, ref);
}
void initWalker(Walker<Corr, Reference> &walk, Determinant &d)
{
walk = Walker<Corr, Reference>(corr, ref, d);
}
/**
*This calculates the overlap of the walker with the
*jastrow and the ciexpansion
*/
double Overlap(const Walker<Corr, Reference> &walk) const
{
return corr.Overlap(walk.d) * walk.getDetOverlap(ref);
}
double getOverlapFactor(const Walker<Corr, Reference>& walk, Determinant& dcopy, bool doparity=false) const
{
double ovlpdetcopy;
int excitationDistance = dcopy.ExcitationDistance(walk.d);
if (excitationDistance == 0)
{
ovlpdetcopy = 1.0;
}
else if (excitationDistance == 1)
{
int I, A;
getDifferenceInOccupation(walk.d, dcopy, I, A);
ovlpdetcopy = getOverlapFactor(I, A, walk, doparity);
}
else if (excitationDistance == 2)
{
int I, J, A, B;
getDifferenceInOccupation(walk.d, dcopy, I, J, A, B);
ovlpdetcopy = getOverlapFactor(I, J, A, B, walk, doparity);
}
else
{
cout << "higher than triple excitation not yet supported." << endl;
exit(0);
}
return ovlpdetcopy;
}
double getOverlapFactor(int i, int a, const Walker<Corr, Reference>& walk, bool doparity) const
{
Determinant dcopy = walk.d;
dcopy.setocc(i, false);
dcopy.setocc(a, true);
double overlapRatio = walk.corrHelper.OverlapRatio(i, a, corr, dcopy, walk.d)
* walk.getDetFactor(i, a, ref);
if (doparity) {
overlapRatio *= walk.d.parityFull(0, i, 0, a, 0);
}
return overlapRatio;
}
double getOverlapFactor(int I, int J, int A, int B, const Walker<Corr, Reference>& walk, bool doparity) const
{
// Single excitation
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, doparity);
Determinant dcopy = walk.d;
dcopy.setocc(I, false);
dcopy.setocc(J, false);
dcopy.setocc(A, true);
dcopy.setocc(B, true);
double overlapRatio = walk.corrHelper.OverlapRatio(I, J, A, B, corr, dcopy, walk.d)
* walk.getDetFactor(I, J, A, B, ref);
if (doparity) {
int ex2 = J * 2 * Determinant::norbs + B;
overlapRatio *= walk.d.parityFull(ex2, I, J, A, B);
}
return overlapRatio;
}
double getOverlapFactor(const Walker<Corr, Reference>& walk, std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to) const
{
//cout << "\ndet " << walk.getDetFactor(from, to) << " corr " << walk.corrHelper.OverlapRatio(from, to, corr) << endl;
return walk.getDetFactor(from, to) * walk.corrHelper.OverlapRatio(from, to, corr);
}
/**
* This basically calls the overlapwithgradient(determinant, factor, grad)
*/
void OverlapWithGradient(const Walker<Corr, Reference> &walk,
double &factor,
Eigen::VectorXd &grad) const
{
double factor1 = 1.0;
Eigen::VectorBlock<VectorXd> gradhead = grad.head(corr.getNumVariables());
corr.OverlapWithGradient(walk.d, gradhead, factor1);
Eigen::VectorBlock<VectorXd> gradtail = grad.tail(grad.rows() - corr.getNumVariables());
walk.OverlapWithGradient(ref, gradtail);
}
void printVariables() const
{
corr.printVariables();
ref.printVariables();
}
void printCorrToFile() const
{
corr.printVariablesToFile();
}
void updateVariables(Eigen::VectorXd &v)
{
Eigen::VectorBlock<VectorXd> vhead = v.head(corr.getNumVariables());
corr.updateVariables(vhead);
Eigen::VectorBlock<VectorXd> vtail = v.tail(v.rows() - corr.getNumVariables());
ref.updateVariables(vtail);
}
void getVariables(Eigen::VectorXd &v) const
{
if (v.rows() != getNumVariables())
v = VectorXd::Zero(getNumVariables());
Eigen::VectorBlock<VectorXd> vhead = v.head(corr.getNumVariables());
corr.getVariables(vhead);
Eigen::VectorBlock<VectorXd> vtail = v.tail(v.rows() - corr.getNumVariables());
ref.getVariables(vtail);
}
long getNumJastrowVariables() const
{
return corr.getNumVariables();
}
//factor = <psi|w> * prefactor;
long getNumVariables() const
{
int norbs = Determinant::norbs;
long numVars = 0;
numVars += getNumJastrowVariables();
numVars += ref.getNumVariables();
return numVars;
}
string getfileName() const {
return ref.getfileName() + corr.getfileName();
}
void writeWave() const
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
//if (commrank == 0)
//{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
//}
#ifndef SERIAL
//boost::mpi::communicator world;
//boost::mpi::broadcast(world, *this, 0);
#endif
}
//<psi_t| (H-E0) |D>
void HamAndOvlp(const Walker<Corr, Reference> &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true, double epsilon=schd.epsilon) const
{
int norbs = Determinant::norbs;
ovlp = Overlap(walk);
ham = walk.d.Energy(I1, I2, coreE);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, epsilon, schd.screen,
work, false);
//loop over all the screened excitations
if (schd.debug) cout << "eloc excitations\nphi0 d.energy " << ham << endl;
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double ovlpRatio = getOverlapFactor(I, J, A, B, walk, false);
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, dbig, dbigcopy, false);
ham += tia * ovlpRatio;
if (schd.debug) cout << I << " " << A << " " << J << " " << B << " tia " << tia << " ovlpRatio " << ovlpRatio << endl;
work.ovlpRatio[i] = ovlpRatio;
}
if (schd.debug) cout << endl;
}
void HamAndOvlpAndSVTotal(const Walker<Corr, Reference> &walk, double &ovlp,
double &ham, double& SVTotal, workingArray& work,
double epsilon=schd.epsilon) const
{
int norbs = Determinant::norbs;
ovlp = Overlap(walk);
ham = walk.d.Energy(I1, I2, coreE);
SVTotal = 0.0;
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, epsilon, schd.screen, work, false);
generateAllScreenedDoubleExcitation(walk.d, epsilon, schd.screen, work, false);
// Loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i];
int ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double ovlpRatio = getOverlapFactor(I, J, A, B, walk, false);
double contrib = tia * ovlpRatio;
ham += contrib;
// Accumulate the sign violating terms for the appropriate Hamiltonian.
if (contrib > 0.0) {
SVTotal += contrib;
}
work.ovlpRatio[i] = ovlpRatio;
}
}
void HamAndOvlpLanczos(const Walker<Corr, Reference> &walk,
Eigen::VectorXd &lanczosCoeffsSample,
double &ovlpSample,
workingArray& work,
workingArray& moreWork, double &alpha)
{
work.setCounterToZero();
int norbs = Determinant::norbs;
double el0 = 0., el1 = 0., ovlp0 = 0., ovlp1 = 0.;
HamAndOvlp(walk, ovlp0, el0, work);
std::vector<double> ovlp{0., 0., 0.};
ovlp[0] = ovlp0;
ovlp[1] = el0 * ovlp0;
ovlp[2] = ovlp[0] + alpha * ovlp[1];
lanczosCoeffsSample[0] = ovlp[0] * ovlp[0] * el0 / (ovlp[2] * ovlp[2]);
lanczosCoeffsSample[1] = ovlp[0] * ovlp[1] * el0 / (ovlp[2] * ovlp[2]);
el1 = walk.d.Energy(I1, I2, coreE);
//if (schd.debug) cout << "phi1 d.energy " << el1 << endl;
//workingArray work1;
//cout << "E0 " << el1 << endl;
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
Walker<Corr, Reference> walkCopy = walk;
walkCopy.updateWalker(ref, corr, work.excitation1[i], work.excitation2[i], false);
moreWork.setCounterToZero();
HamAndOvlp(walkCopy, ovlp0, el0, moreWork, true, schd.lanczosEpsilon);
ovlp1 = el0 * ovlp0;
el1 += tia * ovlp1 / ovlp[1];
work.ovlpRatio[i] = (ovlp0 + alpha * ovlp1) / ovlp[2];
//if (schd.debug) cout << work.excitation1[i] << " " << work.excitation2[i] << " tia " << tia << " ovlpRatio " << ovlp1 / ovlp[1] << endl;
}
//if (schd.debug) cout << endl;
lanczosCoeffsSample[2] = ovlp[1] * ovlp[1] * el1 / (ovlp[2] * ovlp[2]);
lanczosCoeffsSample[3] = ovlp[0] * ovlp[0] / (ovlp[2] * ovlp[2]);
ovlpSample = ovlp[2];
}
// not used
template<typename Walker>
bool checkWalkerExcitationClass(Walker &walk) {
return true;
}
// For some situation, such as FCIQMC, we want to know the ratio of
// overlaps with the correct parity. This function will calculate
// this parity, relative to what is returned by getOverlapFactor.
// (For some wave functions this is always 1).
double parityFactor(Determinant& d, const int ex2, const int i,
const int j, const int a, const int b) const {
return d.parityFull(ex2, i, j, a, b);
}
};
#endif
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SimpleWalker_HEADER_H
#define SimpleWalker_HEADER_H
#include "Determinants.h"
#include <boost/serialization/serialization.hpp>
#include <Eigen/Dense>
#include "input.h"
#include <unordered_set>
#include <iterator>
#include "integral.h"
using namespace Eigen;
/**
* Is essentially a single determinant used in the VMC/DMC simulation
* At each step in VMC one need to be able to calculate the following
* quantities
* a. The local energy = <walker|H|Psi>/<walker|Psi>
*
*/
class SimpleWalker
{
public:
Determinant d; //The current determinant
unordered_set<int> excitedHoles; //spin orbital indices of excited holes in core orbitals in d
unordered_set<int> excitedOrbs; //spin orbital indices of excited electrons in virtual orbitals in d
std::array<VectorXd, 2> energyIntermediates;
// The excitation classes are used in MRCI/MRPT calculations, depending on
// the type of excitation out of the CAS. They are:
// 0: determinant in the CAS (0h,0p)
// 1: 0 holes in the core, 1 partiCle in the virtuals (0h,1p)
// 2: 0 holes in the core, 2 particles in the virtuals (0h,2p)
// 3: 1 hole in the core (1h,0p)
// 4: 1 hole in the core, 1 particle in the virtuals (1h,1p)
// 5: 1 hole in the core, 2 particles in the virtuals (1h,2p)
// 6: 2 holes in the core (2h,0p)
// 7: 2 holes in the core, 1 particle in the virtuals (2h,1p)
// 8: 2 holes in the core, 2 holes in the virtuals (2h,2p)
// (-1): None of the above (therefore beyond the FOIS) (> 2h and/or > 2p)
int excitation_class;
// The constructor
SimpleWalker(Determinant &pd) : d(pd), excitation_class(0) {};
SimpleWalker(const Determinant &corr, const Determinant &ref, Determinant &pd) : d(pd), excitation_class(0) {};
SimpleWalker(const SimpleWalker &w): d(w.d), excitedOrbs(w.excitedOrbs),
excitedHoles(w.excitedHoles), excitation_class(w.excitation_class) {};
SimpleWalker() : excitation_class(0) {};
template<typename Wave>
SimpleWalker(Wave& wave, Determinant &pd) : d(pd), excitation_class(0) {};
Determinant getDet() { return d; }
void updateA(int i, int a);
void updateA(int i, int j, int a, int b);
void updateB(int i, int a);
void updateB(int i, int j, int a, int b);
void update(int i, int a, bool sz, const Determinant &ref, const Determinant &corr) { return; };//to be defined for metropolis
void updateEnergyIntermediate(const oneInt& I1, const twoInt& I2, int I, int A);
void updateEnergyIntermediate(const oneInt& I1, const twoInt& I2, int I, int A, int J, int B);
void updateWalker(const Determinant &ref, const Determinant &corr, int ex1, int ex2, bool updateIntermediate = true);
void exciteWalker(const Determinant &ref, const Determinant &corr, int excite1, int excite2, int norbs);
void getExcitationClass();
bool operator<(const SimpleWalker &w) const
{
return d < w.d;
}
bool operator==(const SimpleWalker &w) const
{
return d == w.d;
}
friend ostream& operator<<(ostream& os, const SimpleWalker& w) {
os << w.d << endl;
os << "excitedOrbs ";
copy(w.excitedOrbs.begin(), w.excitedOrbs.end(), ostream_iterator<int>(os, " "));
os << "excitedHoles ";
copy(w.excitedHoles.begin(), w.excitedHoles.end(), ostream_iterator<int>(os, " "));
os << "energyIntermediates\n";
os << "up\n";
os << w.energyIntermediates[0] << endl;
os << "down\n";
os << w.energyIntermediates[1] << endl;
return os;
}
//template <typename Wfn>
//void exciteTo(Wfn& w, Determinant& dcopy) {
// d = dcopy;
//}
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include "Wfn.h"
#include <algorithm>
#include "integral.h"
#include "Determinants.h"
#include "Walker.h"
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include "evaluateE.h"
#include "evaluatePT.h"
#include "Davidson.h"
#include "Hmult.h"
#include "global.h"
#include "input.h"
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace std;
using namespace Eigen;
//<psi|H|psi>/<psi|psi> = <psi|d> <d|H|psi>/<psi|d><d|psi>
double evaluateScaledEDeterministic(CPSSlater& w, double& lambda, double& unscaledE0,
int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE) {
VectorXd localGrad; bool doGradient = false;
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
vector<double> Hij;
int nExcitations;
vector<vector<int> > alphaDets, betaDets;
comb(norbs, nalpha, alphaDets);
comb(norbs, nbeta , betaDets);
std::vector<Determinant> allDets;
for (int a=0; a<alphaDets.size(); a++)
for (int b=0; b<betaDets.size(); b++) {
Determinant d;
for (int i=0; i<alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i], true);
for (int i=0; i<betaDets[b].size(); i++)
d.setoccB(betaDets[b][i], true);
allDets.push_back(d);
}
alphaDets.clear(); betaDets.clear();
double E=0, ovlp=0;
double unscaledE = 0;
for (int d=commrank; d<allDets.size(); d+=commsize) {
double Eloc=0, ovlploc=0;
double scale = 1.0, E0;
Walker walk(allDets[d]);
walk.initUsingWave(w);
w.HamAndOvlpGradient(walk, ovlploc, Eloc, localGrad, I1, I2, I2hb, coreE,
ovlpRatio, excitation1, excitation2, Hij, nExcitations,
doGradient);
E += ((1-lambda)*Eloc + lambda*allDets[d].Energy(I1, I2, coreE))*ovlploc*ovlploc;
unscaledE += Eloc*ovlploc*ovlploc;
ovlp += ovlploc*ovlploc;
}
allDets.clear();
double Ebkp=E, obkp = ovlp, unscaledEbkp = unscaledE;
int size = 1;
#ifndef SERIAL
MPI_Allreduce(&Ebkp, &E, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&unscaledEbkp, &unscaledE, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&obkp, &ovlp, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
unscaledE0 = unscaledE/ovlp;
return E/ovlp;
}
double evaluatePTDeterministic(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb, double& coreE) {
vector<vector<int> > alphaDets, betaDets;
comb(norbs, nalpha, alphaDets);
comb(norbs, nbeta , betaDets);
std::vector<Determinant> allDets;
for (int a=0; a<alphaDets.size(); a++)
for (int b=0; b<betaDets.size(); b++) {
Determinant d;
for (int i=0; i<alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i], true);
for (int i=0; i<betaDets[b].size(); i++)
d.setoccB(betaDets[b][i], true);
allDets.push_back(d);
}
alphaDets.clear(); betaDets.clear();
VectorXd localGrad; bool doGradient = false;
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
vector<double> Hij;
int nExcitations;
double A=0, B=0, C=0, ovlp=0;
for (int d=commrank; d<allDets.size(); d+=commsize) {
double Eloc=0, ovlploc=0;
double scale = 1.0;
Walker walk(allDets[d]);
walk.initUsingWave(w);
double Ei = allDets[d].Energy(I1, I2, coreE);
w.HamAndOvlpGradient(walk, ovlploc, Eloc, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, Hij, nExcitations, doGradient);
//w.HamAndOvlp(walk, ovlploc, Eloc, I1, I2, I2hb, coreE);
double ovlp2 = ovlploc*ovlploc;
A -= pow(Eloc-E0, 2)*ovlp2/(Ei-E0);
B += (Eloc-E0)*ovlp2/(Ei-E0);
C += ovlp2/(Ei-E0);
ovlp += ovlp2;
}
allDets.clear();
double obkp = ovlp;
int size = 1;
#ifndef SERIAL
MPI_Allreduce(&obkp, &ovlp, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
double Abkp=A/ovlp;
double Bbkp=B/ovlp, Cbkp = C/ovlp;
#ifndef SERIAL
MPI_Allreduce(&Abkp, &A, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&Bbkp, &B, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&Cbkp, &C, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
if (commrank == 0) cout <<A<<" "<< B<<" "<<C<<" "<<B*B/C<<endl;
return A + B*B/C;
}
//<psi|H|psi>/<psi|psi> = <psi|d> <d|H|psi>/<psi|d><d|psi>
double evaluatePTDeterministicB(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb, double& coreE) {
vector<vector<int> > alphaDets, betaDets;
comb(norbs, nalpha, alphaDets);
comb(norbs, nbeta , betaDets);
std::vector<Determinant> allDets;
for (int a=0; a<alphaDets.size(); a++)
for (int b=0; b<betaDets.size(); b++) {
Determinant d;
for (int i=0; i<alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i], true);
for (int i=0; i<betaDets[b].size(); i++)
d.setoccB(betaDets[b][i], true);
allDets.push_back(d);
}
alphaDets.clear(); betaDets.clear();
VectorXd localGrad; bool doGradient = false;
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
vector<double> Hij;
int nExcitations;
//if (commrank == 0) cout << allDets.size()<<endl;
double A=0, B=0, C=0, ovlp=0;
for (int d=commrank; d<allDets.size(); d+=commsize) {
double Eloc=0, ovlploc=0;
double scale = 1.0;
Walker walk(allDets[d]);
walk.initUsingWave(w);
double Ei = allDets[d].Energy(I1, I2, coreE);
double Aloc=0, Bloc=0, Cloc=0;
///w.PTcontribution2ndOrder(walk, E0, I1, I2, I2hb, coreE, Aloc, Bloc, Cloc,
//ovlpRatio, excitation1, excitation2, doGradient);
w.HamAndOvlpGradient(walk, ovlploc, Eloc, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, Hij, nExcitations, doGradient);
double ovlp2 = ovlploc*ovlploc;
A += Aloc*ovlp2;
B += Bloc*ovlp2;
C += Cloc*ovlp2;
ovlp += ovlp2;
}
allDets.clear();
double obkp = ovlp;
int size = 1;
#ifndef SERIAL
MPI_Allreduce(&obkp, &ovlp, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
double Abkp=A/ovlp;
double Bbkp=B/ovlp, Cbkp = C/ovlp;
#ifndef SERIAL
MPI_Allreduce(&Abkp, &A, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&Bbkp, &B, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&Cbkp, &C, size, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
if (commrank == 0) cout <<A<<" "<< B<<" "<<C<<" "<<B*B/C<<endl;
return A + B*B/C;
}
double evaluatePTDeterministicC(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb, double& coreE) {
vector<vector<int> > alphaDets, betaDets;
comb(norbs, nalpha, alphaDets);
comb(norbs, nbeta , betaDets);
std::vector<Determinant> allDets;
for (int a=0; a<alphaDets.size(); a++)
for (int b=0; b<betaDets.size(); b++) {
Determinant d;
for (int i=0; i<alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i], true);
for (int i=0; i<betaDets[b].size(); i++)
d.setoccB(betaDets[b][i], true);
allDets.push_back(d);
}
alphaDets.clear(); betaDets.clear();
SparseHam Ham;
vector<vector<int> >& connections = Ham.connections;
vector<vector<double> >& Helements = Ham.Helements;
for (int d=commrank; d<allDets.size(); d+=commsize) {
connections.push_back(vector<int>(1, d));
Helements.push_back(vector<double>(1, allDets[d].Energy(I1, I2, coreE)));
for (int i=d+1; i<allDets.size(); i++) {
if (allDets[d].connected(allDets[i])) {
connections.rbegin()->push_back(i);
Helements.rbegin()->push_back( Hij(allDets[d], allDets[i], I1, I2, coreE));
}
}
}
SparseHam Ham0 = Ham;
Hmult2 hmult(Ham0);
VectorXd localGrad; bool doGradient = false;
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
vector<double> Hij;
int nExcitations;
MatrixXx psi0 = MatrixXx::Zero(allDets.size(),1);
MatrixXx diag = MatrixXx::Zero(allDets.size(),1);
for (int d=commrank; d<allDets.size(); d+=commsize) {
double Eloc=0, ovlploc=0;
Walker walk(allDets[d]);
walk.initUsingWave(w);
double Ei = allDets[d].Energy(I1, I2, coreE);
double scale = 1.0, E0;
w.HamAndOvlpGradient(walk, ovlploc, Eloc, localGrad, I1, I2, I2hb, coreE,
ovlpRatio, excitation1, excitation2, Hij, nExcitations,
doGradient);
//w.HamAndOvlp(walk, ovlploc, Eloc, I1, I2, I2hb, coreE);
psi0(d,0) = ovlploc;
diag(d,0) = Ei;
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &psi0(0,0), psi0.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &diag(0,0), diag.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
psi0 /= psi0.norm();
MatrixXx Hpsi0 = MatrixXx::Zero(allDets.size(),1);
hmult(&psi0(0,0), &Hpsi0(0,0));
#ifndef SERIAL
MPI_Bcast(&Hpsi0(0,0), Hpsi0.rows(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
MatrixXx x0;
if (commrank == 0) cout << psi0.adjoint()*Hpsi0<<endl;
vector<double*> proj(1, &psi0(0,0));
int index = 0;
for (int d=commrank; d<allDets.size(); d+=commsize) {
Ham0.connections[index].resize(1);
Ham0.Helements[index].resize(1);
index++;
}
double PT = 0;
//double PT = LinearSolver(hmult, E0, x0, Hpsi0, proj, 1.e-6, true);
#ifndef SERIAL
MPI_Bcast(&x0(0,0), x0.rows(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0) cout << x0.adjoint()*psi0<<endl;
Hmult2 hmultfull(Ham);
MatrixXx HHpsi0 = MatrixXx::Zero(allDets.size(), 1);
MatrixXx HHpsi1 = MatrixXx::Zero(allDets.size(), 1);
hmultfull(&x0(0,0), &HHpsi0(0,0)); //H x0
hmult (&x0(0,0), &HHpsi1(0,0)); //H0 x0
if (commrank == 0) cout << HHpsi0.adjoint()*x0-HHpsi1.adjoint()*x0<<endl;
return -PT;
}
double evaluateScaledEStochastic(CPSSlater &w, double& lambda, double &unscaledE,
int &nalpha, int &nbeta, int &norbs,
oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb, double &coreE,
double& stddev, double& rk,
int niter, double targetError)
{
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
double scaledE=0., E0=0.;
VectorXd grad;
//initialize the walker
Determinant d;
bool readDeterminant = false;
char file [5000];
sprintf (file, "BestDeterminant.txt");
{
ifstream ofile(file);
if (ofile) readDeterminant = true;
}
//readDeterminant = false;
if ( !readDeterminant )
{
for (int i =0; i<nalpha; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j=0; j<norbs; j++) {
if (abs(HforbsA(i,j)) > maxovlp && !d.getoccA(j)) {
maxovlp = abs(HforbsA(i,j));
bestorb = j;
}
}
d.setoccA(bestorb, true);
}
for (int i =0; i<nbeta; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j=0; j<norbs; j++) {
if (abs(HforbsB(i,j)) > maxovlp && !d.getoccB(j)) {
bestorb = j; maxovlp = abs(HforbsB(i,j));
}
}
d.setoccB(bestorb, true);
}
}
else {
if (commrank == 0) {
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> d;
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
Walker walk(d);
walk.initUsingWave(w);
//int maxTerms = 3*(nalpha) * (nbeta) * (norbs-nalpha) * (norbs-nbeta);
int maxTerms = (nalpha) * (norbs-nalpha); //pick a small number that will be incremented later
vector<double> ovlpRatio(maxTerms);
vector<size_t> excitation1( maxTerms), excitation2( maxTerms);
vector<double> HijElements(maxTerms);
int nExcitations = 0;
stddev = 1.e4;
int iter = 0;
double M1 = 0., S1 = 0., Eavg = 0.;
double Eloc = 0.;
double ham = 0., ovlp = 0.;
VectorXd localGrad = grad;
localGrad.setZero();
double scale = 1.0;
VectorXd diagonalGrad = VectorXd::Zero(grad.rows());
VectorXd localdiagonalGrad = VectorXd::Zero(grad.rows());
double bestOvlp =0.;
Determinant bestDet=d;
nExcitations = 0;
E0 = 0.0;
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, false);
int nstore = 1000000/commsize;
int gradIter = min(nstore, niter);
std::vector<double> gradError(gradIter*commsize, 0);
bool reset = true;
double cumdeltaT = 0., cumdeltaT2 = 0.;
int reset_len = readDeterminant ? 1 : 10*norbs;
while (iter < niter && stddev > targetError)
{
if (iter == reset_len && reset)
{
iter = 0;
reset = false;
M1 = 0.;
S1 = 0.;
Eloc = 0;
grad.setZero();
diagonalGrad.setZero();
walk.initUsingWave(w, true);
cumdeltaT = 0.;
cumdeltaT2 = 0;
scaledE = 0.0;
}
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < nExcitations; i++)
{
cumovlpRatio += abs(ovlpRatio[i]);
//cumovlpRatio += min(1.0, pow(ovlpRatio[i], 2));
ovlpRatio[i] = cumovlpRatio;
}
//double deltaT = -log(random())/(cumovlpRatio);
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random()*cumovlpRatio;
int nextDet = std::lower_bound(ovlpRatio.begin(), (ovlpRatio.begin()+nExcitations),
nextDetRandom) -
ovlpRatio.begin();
cumdeltaT += deltaT;
cumdeltaT2 += deltaT * deltaT;
double Elocold = Eloc;
double ratio = deltaT/cumdeltaT;
double E0 = walk.d.Energy(I1, I2, coreE);
Eloc = Eloc + deltaT * (ham - Eloc) / (cumdeltaT); //running average of energy
ham = (1. - lambda) * ham + lambda * E0;
scaledE = scaledE + deltaT * (ham - scaledE) / (cumdeltaT); //running average of energy
S1 = S1 + (ham - Elocold) * (ham - Eloc);
if (iter < gradIter)
gradError[iter + commrank*gradIter] = ham;
iter++;
walk.updateWalker(w, excitation1[nextDet], excitation2[nextDet]);
nExcitations = 0;
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, false);
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(gradError[0]), gradError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &Eloc, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &scaledE, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
rk = calcTcorr(gradError);
E0 = Eloc / commsize;
unscaledE = E0;
scaledE = scaledE / commsize;
stddev = sqrt(S1 * rk / (niter - 1) / niter / commsize);
#ifndef SERIAL
MPI_Bcast(&stddev, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
return scaledE;
}
double evaluatePTStochasticMethodA(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddev,
int niter, double& A, double& B, double& C) {
//initialize the walker
Determinant d;
for (int i=0; i<nalpha; i++)
d.setoccA(i, true);
for (int j=0; j<nbeta; j++)
d.setoccB(j, true);
Walker walk(d);
walk.initUsingWave(w);
stddev = 1.e4;
int iter = 0;
double M1=0., S1 = 0.;
A=0; B=0; C=0;
double Aloc=0, Bloc=0, Cloc=0;
double scale = 1.0;
double rk = 1.;
vector<double> ovlpRatio; vector<size_t> excitation1, excitation2; bool doGradient=false;
w.PTcontribution2ndOrder(walk, E0, I1, I2, I2hb, coreE, Aloc, Bloc, Cloc,
ovlpRatio, excitation1, excitation2, doGradient);
int gradIter = min(niter, 100000);
std::vector<double> gradError(gradIter, 0);
bool reset = true;
while (iter <niter ) {
if (iter == 100 && reset) {
iter = 0;
reset = false;
M1 = 0.; S1=0.;
A=0; B=0; C=0;
walk.initUsingWave(w, true);
//Detmap.clear();
}
A = A + ( Aloc - A)/(iter+1);
B = B + ( Bloc - B)/(iter+1);
C = C + ( Cloc - C)/(iter+1);
double Mprev = M1;
M1 = Mprev + (Aloc - Mprev)/(iter+1);
if (iter != 0)
S1 = S1 + (Aloc - Mprev)*(Aloc - M1);
if (iter < gradIter)
gradError[iter] = Aloc;
iter++;
if (iter == gradIter-1) {
rk = calcTcorr(gradError);
}
//bool success = walk.makeCleverMove(w);
bool success = walk.makeMove(w);
if (success) {
ovlpRatio.clear(); excitation1.clear(); excitation2.clear();
w.PTcontribution2ndOrder(walk, E0, I1, I2, I2hb, coreE, Aloc, Bloc, Cloc,
ovlpRatio, excitation1, excitation2, doGradient);
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &A, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &B, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &C, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
A = A/commsize;
B = B/commsize;
C = C/commsize;
stddev = sqrt(S1*rk/(niter-1)/niter/commsize) ;
#ifndef SERIAL
MPI_Bcast(&stddev , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
return A + B*B/C;
}
//A = sum_i <D_i|(H-E0)|Psi>/(Ei-E0) pi
//where pi = <D_i|psi>**2/<psi|psi>
//this introduces a bias because there are determinants that have a near zero overlap with
//psi but make a non-zero contribution to A.
double evaluatePTStochasticMethodB(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddev, double& rk,
int niter, double& A, double& B, double& C) {
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
//initialize the walker
Determinant d;
for (int i =0; i<nalpha; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j=0; j<norbs; j++) {
if (abs(HforbsA(i,j)) > maxovlp && !d.getoccA(j)) {
maxovlp = abs(HforbsA(i,j));
bestorb = j;
}
}
d.setoccA(bestorb, true);
}
for (int i =0; i<nbeta; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j=0; j<norbs; j++) {
if (abs(HforbsB(i,j)) > maxovlp && !d.getoccB(j)) {
bestorb = j; maxovlp = abs(HforbsB(i,j));
}
}
d.setoccB(bestorb, true);
}
Walker walk(d);
walk.initUsingWave(w);
VectorXd localGrad; bool doGradient = false;
int maxTerms = (nalpha) * (norbs-nalpha); //pick a small number that will be incremented later
vector<double> ovlpRatio(maxTerms);
vector<size_t> excitation1( maxTerms), excitation2( maxTerms);
vector<double> Hij(maxTerms);
int nExcitations = 0;
stddev = 1.e4;
int iter = 0;
double M1=0., S1 = 0.;
A=0; B=0; C=0;
double Aloc=0, Bloc=0, Cloc=0;
double scale = 1.0, ham, ovlp;
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE,
ovlpRatio, excitation1, excitation2, Hij,
nExcitations, doGradient);
double Ei = walk.d.Energy(I1, I2, coreE);
int nstore = 1000000/commsize;
int gradIter = min(nstore, niter);
std::vector<double> gradError(gradIter*commsize, 0);
bool reset = true;
double cumdeltaT = 0., cumdeltaT2 = 0.;
while (iter <niter ) {
if (iter == 20 && reset) {
iter = 0;
reset = false;
M1 = 0.; S1=0.;
A=0; B=0; C=0;
walk.initUsingWave(w, true);
}
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < nExcitations; i++)
{
cumovlpRatio += abs(ovlpRatio[i]);
ovlpRatio[i] = cumovlpRatio;
}
//double deltaT = -log(random())/(cumovlpRatio);
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random()*cumovlpRatio;
int nextDet = std::lower_bound(ovlpRatio.begin(), (ovlpRatio.begin()+nExcitations),
nextDetRandom) -
ovlpRatio.begin();
cumdeltaT += deltaT;
cumdeltaT2 += deltaT * deltaT;
double Aold = A;
double ratio = deltaT/cumdeltaT;
Aloc = -pow(ham-E0, 2)/(Ei-E0);
Bloc = (ham-E0)/(Ei-E0);
Cloc = 1./(Ei-E0);
A = A + deltaT * ( Aloc - A)/(cumdeltaT);
B = B + deltaT * ( Bloc - B)/(cumdeltaT);
C = C + deltaT * ( Cloc - C)/(cumdeltaT);
S1 = S1 + (Aloc - Aold)*(Aloc - A);
if (iter < gradIter)
gradError[iter + commrank*gradIter] = Aloc;
iter++;
walk.updateWalker(w, excitation1[nextDet], excitation2[nextDet]);
nExcitations = 0;
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, Hij, nExcitations, false);
Ei = walk.d.Energy(I1, I2, coreE);
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(gradError[0]), gradError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &A, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &B, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &C, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
rk = calcTcorr(gradError);
A = A/commsize;
B = B/commsize;
C = C/commsize;
stddev = sqrt(S1*rk/(niter-1)/niter/commsize) ;
#ifndef SERIAL
MPI_Bcast(&stddev , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
return A + B*B/C;
}
/*
//\sum_i <psi|(H0-E0)|D_j><D_j|H0-E0|Di>/(Ei-E0)/<Di|psi> pi
//where pi = <D_i|psi>**2/<psi|psi>
double evaluatePTStochasticMethodC(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddevA,double& stddevB, double& stddevC,
int niter, double& A, double& B, double& C) {
auto random = std::bind(std::uniform_real_distribution<double>(0,1),
std::ref(generator));
//initialize the walker
Determinant d;
for (int i=0; i<nalpha; i++)
d.setoccA(i, true);
for (int j=0; j<nbeta; j++)
d.setoccB(j, true);
Walker walk(d);
walk.initUsingWave(w);
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
int nExcitations;
stddevA = 1.e4; stddevB = 1.e-4; stddevC = 1.e-4;
int iter = 0;
double M1=0., SA1 = 0., SB1=0., SC1=0.;
A=0; B=0; C=0;
double Aloc=0, Bloc=0, Cloc=0;
double scale = 1.0;
double rk = 1.;
w.PTcontribution2ndOrder(walk, E0, I1, I2, I2hb, coreE, Aloc, Bloc, Cloc,
ovlpRatio, excitation1, excitation2, false);
int gradIter = min(niter, 1000);
std::vector<double> gradError(gradIter, 0);
bool reset = true;
double cumdeltaT = 0., cumdeltaT2=0.;
while (iter <niter ) {
if (iter == 100 && reset) {
iter = 0;
reset = false;
SA1=0.; SB1=0.; SC1=0.;
A=0; B=0; C=0;
walk.initUsingWave(w, true);
cumdeltaT = 0; cumdeltaT2 = 0;
}
double cumovlpRatio = 0.;
for (int i=0; i<ovlpRatio.size(); i++) {
cumovlpRatio += abs(ovlpRatio[i]);
ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0/(cumovlpRatio);
double select = random()*cumovlpRatio;
int nextDet = std::distance(ovlpRatio.begin(), std::lower_bound(ovlpRatio.begin(), ovlpRatio.end(),
select));
cumdeltaT += deltaT;
cumdeltaT2 += deltaT*deltaT;
double Aold = A, Bold=B, Cold=C;
//if (commrank == 0) cout <<iter<<" CCC "<< walk.d<<" "<<Aloc<<" "<<Bloc<<" "<<Cloc<<endl;
A = A + deltaT*( Aloc - A)/(cumdeltaT);
B = B + deltaT*( Bloc - B)/(cumdeltaT);
C = C + deltaT*( Cloc - C)/(cumdeltaT);
SA1 = SA1 + (Aloc - Aold)*(Aloc - A);
SB1 = SB1 + (Bloc - Bold)*(Bloc - B);
SC1 = SC1 + (Cloc - Cold)*(Cloc - C);
if (iter < gradIter)
gradError[iter] = Bloc;
iter++;
if (iter == gradIter-1) {
rk = calcTcorr(gradError);
}
//update the walker
if (true) {
int I = excitation1[nextDet]/2/norbs, A = excitation1[nextDet] - 2*norbs*I;
if (I%2 == 0) walk.updateA(I/2, A/2, w);
else walk.updateB(I/2, A/2, w);
if (excitation2[nextDet] != 0) {
int I = excitation2[nextDet]/2/norbs, A = excitation2[nextDet] - 2*norbs*I;
if (I%2 == 0) walk.updateA(I/2, A/2, w);
else walk.updateB(I/2, A/2, w);
}
ovlpRatio.clear(); excitation1.clear(); excitation2.clear();
w.PTcontribution2ndOrder(walk, E0, I1, I2, I2hb, coreE, Aloc, Bloc, Cloc,
ovlpRatio, excitation1, excitation2, false);
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &A, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &B, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &C, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
A = A/commsize;
B = B/commsize;
C = C/commsize;
stddevA = sqrt(SA1*rk/(niter-1)/niter/commsize) ;
stddevB = sqrt(SB1*rk/(niter-1)/niter/commsize) ;
stddevC = sqrt(SC1*rk/(niter-1)/niter/commsize) ;
#ifndef SERIAL
MPI_Bcast(&stddevA , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&stddevB , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&stddevC , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0) cout << rk<<endl;
return A + B*B/C;
}
double evaluatePTStochastic3rdOrder(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddev,
int niter, double& A2, double& B, double& C, double& A3) {
auto random = std::bind(std::uniform_real_distribution<double>(0,1),
std::ref(generator));
//initialize the walker
Determinant d;
for (int i=0; i<nalpha; i++)
d.setoccA(i, true);
for (int j=0; j<nbeta; j++)
d.setoccB(j, true);
Walker walk(d);
walk.initUsingWave(w);
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
stddev = 1.e4;
int iter = 0;
double M1=0., S1 = 0.;
A2=0; B=0; C=0;A3=0;
double A2loc=0, A3loc=0, Bloc=0, Cloc=0;
double scale = 1.0;
double rk = 1.;
w.PTcontribution3rdOrder(walk, E0, I1, I2, I2hb, coreE, A2loc, Bloc, Cloc, A3loc,
ovlpRatio, excitation1, excitation2, false);
int gradIter = min(niter, 1000);
std::vector<double> gradError(gradIter, 0);
bool reset = true;
double cumdeltaT = 0., cumdeltaT2=0.;
while (iter <niter ) {
if (iter == 100 && reset) {
iter = 0;
reset = false;
M1 = 0.; S1=0.;
A2=0; B=0; C=0;A3 = 0;
walk.initUsingWave(w, true);
cumdeltaT = 0; cumdeltaT2 = 0;
}
double cumovlpRatio = 0;
for (int i=0; i<ovlpRatio.size(); i++) {
//cumovlpRatio += min(1.0, ovlpRatio[i]);
cumovlpRatio += abs(ovlpRatio[i]);
ovlpRatio[i] = cumovlpRatio;
}
//double deltaT = -log(random())/(cumovlpRatio);
double deltaT = 1.0/(cumovlpRatio);
double select = random()*cumovlpRatio;
int nextDet = std::distance(ovlpRatio.begin(), std::lower_bound(ovlpRatio.begin(), ovlpRatio.end(),
select));
cumdeltaT += deltaT;
cumdeltaT2 += deltaT*deltaT;
//if (commrank == 0) cout <<iter<<" CCC "<< walk.d<<" "<<Aloc<<" "<<Bloc<<" "<<Cloc<<endl;
double A3old = A3;
A2 = A2 + deltaT*( A2loc - A2)/(cumdeltaT);
A3 = A3 + deltaT*( A3loc - A3)/(cumdeltaT);
B = B + deltaT*( Bloc - B)/(cumdeltaT);
C = C + deltaT*( Cloc - C)/(cumdeltaT);
S1 = S1 + (A3loc - A3old)*(A3loc - A3);
if (iter < gradIter)
gradError[iter] = A3loc;
iter++;
if (iter == gradIter-1) {
rk = calcTcorr(gradError);
}
//update the walker
if (true) {
int I = excitation1[nextDet]/2/norbs, A = excitation1[nextDet] - 2*norbs*I;
if (I%2 == 0) walk.updateA(I/2, A/2, w);
else walk.updateB(I/2, A/2, w);
if (excitation2[nextDet] != 0) {
int I = excitation2[nextDet]/2/norbs, A = excitation2[nextDet] - 2*norbs*I;
if (I%2 == 0) walk.updateA(I/2, A/2, w);
else walk.updateB(I/2, A/2, w);
}
ovlpRatio.clear(); excitation1.clear(); excitation2.clear();
w.PTcontribution3rdOrder(walk, E0, I1, I2, I2hb, coreE, A2loc, Bloc, Cloc, A3loc,
ovlpRatio, excitation1, excitation2, false);
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &A2, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &A3, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &B, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &C, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
A2 = A2/commsize;
A3 = A3/commsize;
B = B/commsize;
C = C/commsize;
stddev = sqrt(S1*rk/(niter-1)/niter/commsize) ;
#ifndef SERIAL
MPI_Bcast(&stddev , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0) cout << A2<<" "<<A3<<endl;
return A2 + B*B/C;
}
*/
<file_sep>#ifndef TrivialWalk_HEADER_H
#define TrivialWalk_HEADER_H
// This is a trial wave function walker for cases in FCIQMC where a
// trial wave function is not used (i.e. the original version of the
// algorithm). In this case, these functions are either not used or
// should return trivial results. This is a basic class to deal with
// this situation, together with the TrialWF class.
class TrivialWalk {
public:
Determinant d;
TrivialWalk() {}
template<typename Wave>
TrivialWalk(Wave& wave, Determinant& det) : d(det) {}
void updateWalker(const Determinant& ref, const Determinant& corr,
int ex1, int ex2, bool updateIntermediate=true) {}
};
#endif
<file_sep>#!/usr/bin/env python
import sys
def check_results(eRef, eTest, tol):
if (abs(eRef - eTest) < tol):
print("test passed")
else:
print("test failed")
print("eRef = ", eRef)
print("eTest = ", eTest)
def check_results_fciqmc_replica(eRef1, eRef2, eRefVar, eRefEN2,
eTest1, eTest2, eTestVar, eTestEN2, tol):
passed_1 = abs(eRef1 - eTest1) < tol
passed_2 = abs(eRef2 - eTest2) < tol
passed_var = abs(eRefVar - eTestVar) < tol
passed_en2 = abs(eRefEN2 - eTestEN2) < tol
if (passed_1 and passed_2 and passed_var and passed_en2):
print("test passed")
else:
print("test failed")
print("eRef1 = ", eRef1)
print("eTest1 = ", eTest1)
print("eRef2 = ", eRef2)
print("eTest2 = ", eTest2)
print("eRefVar = ", eRefVar)
print("eTestVar = ", eTestVar)
print("eRefEN2 = ", eRefEN2)
print("eTestEN2 = ", eTestEN2)
def check_results_sp(determERef, determETest, stochERef, stochETest, tol):
if (abs(determERef - determETest) < tol):
print("determ test passed")
else:
print("determ test failed")
print("determERef = ", determERef)
print("determETest = ", determETest)
if (abs(stochERef - stochETest) < tol):
print("stoch test passed")
else:
print("stoch test failed")
print("stochERef = ", stochERef)
print("stochETest = ", stochETest)
if __name__ == '__main__':
mc = sys.argv[1]
tol = float(sys.argv[2])
if mc == 'vmc' or mc == 'gfmc' or mc == 'ci':
fh = open(mc+'.ref', 'r')
for line in fh:
pass
eRef = float(line.split()[1])
fh = open(mc+'.out', 'r')
for line in fh:
pass
eTest = float(line.split()[1])
check_results(eRef, eTest, tol)
elif mc == 'nevpt' or mc == 'nevpt_print' or mc == 'nevpt_read':
fh = open(mc+'.ref', 'r')
for line in fh:
pass
eRef = float(line.split()[-1])
fh = open(mc+'.out', 'r')
for line in fh:
pass
eTest = float(line.split()[-1])
check_results(eRef, eTest, tol)
elif mc == 'single_perturber':
fh = open('nevpt.ref', 'r')
for line in fh:
pass
determERef = float(line.split()[-1])
fh = open('nevpt.out', 'r')
for line in fh:
pass
determETest = float(line.split()[-1])
fh = open('stoch_samples.ref', 'r')
for line in fh:
pass
stochERef = float(line.split()[1])
fh = open('stoch_samples_0.dat', 'r')
for line in fh:
pass
stochETest = float(line.split()[1])
check_results_sp(determERef, determETest, stochERef, stochETest, tol)
elif mc == 'fciqmc':
last_line = ''
fh = open(mc+'.benchmark', 'r')
for line in fh:
if '#' not in line:
last_line = line
eRef = float(last_line.split()[5]) / float(last_line.split()[6])
fh = open(mc+'.out', 'r')
for line in fh:
if '#' not in line:
last_line = line
eTest = float(last_line.split()[5]) / float(last_line.split()[6])
check_results(eRef, eTest, tol)
elif mc == 'fciqmc_replica':
last_line = ''
fh = open('fciqmc.benchmark', 'r')
# true if EN2 energies are being estimated in this job
doingEN2 = False
for line in fh:
if '#' not in line:
last_line = line
else:
if 'EN2' in line:
doingEN2 = True
eRef1 = float(last_line.split()[5]) / float(last_line.split()[6])
eRef2 = float(last_line.split()[9]) / float(last_line.split()[10])
eRefVar = float(last_line.split()[11]) / float(last_line.split()[12])
eRefEN2 = 0.0
if doingEN2:
eRefEN2 = float(last_line.split()[13]) / float(last_line.split()[12])
fh = open('fciqmc.out', 'r')
for line in fh:
if '#' not in line:
last_line = line
eTest1 = float(last_line.split()[5]) / float(last_line.split()[6])
eTest2 = float(last_line.split()[9]) / float(last_line.split()[10])
eTestVar = float(last_line.split()[11]) / float(last_line.split()[12])
eTestEN2 = 0.0
if doingEN2:
eTestEN2 = float(last_line.split()[13]) / float(last_line.split()[12])
check_results_fciqmc_replica(eRef1, eRef2, eRefVar, eRefEN2,
eTest1, eTest2, eTestVar, eTestEN2, tol)
elif mc == 'fciqmc_trial':
last_line = ''
fh = open('fciqmc.benchmark', 'r')
for line in fh:
if '#' not in line:
last_line = line
eRef = float(last_line.split()[7]) / float(last_line.split()[8])
fh = open('fciqmc.out', 'r')
for line in fh:
if '#' not in line:
last_line = line
eTest = float(last_line.split()[7]) / float(last_line.split()[8])
check_results(eRef, eTest, tol)
<file_sep>/* Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#include <stdint.h>
#include "CxNumpyArray.h"
#include "iostream"
#include "BlockContract.h"
#ifdef _MSC_VER
#define snprintf _snprintf // yes, I know that they are semnatically different, but it does not matter here.
// (snprintf is neither defined in C89 nor in C++98)
#endif
namespace ct {
void WriteNpy(FILE *File, FScalar const *pData, std::size_t const pShape[], std::size_t nDim)
{
// magic string (6), version number (1.0), two bytes giving the header length
// minus 10 Header length as pos [8],[9] will be written later.
#ifdef _SINGLE_PRECISION
char const *BaseTemplate = "{'descr': '<f4', 'fortran_order': True, 'shape': (%s), }";
#else
char const *BaseTemplate = "{'descr': '<f8', 'fortran_order': True, 'shape': (%s), }";
#endif
char Header[256];
char ShapeDesc[256];
switch ( nDim ) {
// why no loop? Because c string processing sucks and I don't want to deal with it.
#define I(n) (int)pShape[n]
case 0: ShapeDesc[0] = 0; break;
case 1: snprintf(&ShapeDesc[0], 256, "%i", I(0)); break;
case 2: snprintf(&ShapeDesc[0], 256, "%i, %i", I(0), I(1)); break;
case 3: snprintf(&ShapeDesc[0], 256, "%i,%i,%i", I(0), I(1), I(2)); break;
case 4: snprintf(&ShapeDesc[0], 256, "%i,%i,%i,%i", I(0), I(1), I(2), I(3)); break;
case 5: snprintf(&ShapeDesc[0], 256, "%i,%i,%i,%i,%i", I(0), I(1), I(2), I(3), I(4)); break;
case 6: snprintf(&ShapeDesc[0], 256, "%i,%i,%i,%i,%i,%i", I(0), I(1), I(2), I(3), I(4), I(5)); break;
default: throw FIoExceptionNpy("input array rank not supported.");
#undef I
}
for ( std::size_t i = 0; i < 10; ++ i )
Header[i] = "\x93NUMPY\x01\x00~~"[i];
int
nw;
nw = snprintf(&Header[10], 256-10, BaseTemplate, &ShapeDesc[0]);
uint16_t
HeaderLenTotal = 10 + nw,
HeaderLen;
// pad with spaces until data address starts at 16-byte boundary
// (for alignment purposes: npy-format.txt forces that). And add a
// newline.
while((HeaderLenTotal + 1) % 16 != 0) {
if (HeaderLenTotal >= 256-1) throw FIoExceptionNpy("programming error in header generation.");
Header[HeaderLenTotal] = 0x20;
HeaderLenTotal += 1;
}
HeaderLenTotal += 1;
Header[HeaderLenTotal-1] = 0x0a;
// calculate and store header lenght; -10: the magic string,
// the version, and the header length itself are not included
// in the count.
HeaderLen = HeaderLenTotal - 10;
Header[8] = HeaderLen & 0xff;
Header[9] = HeaderLen >> 8;
fwrite(&Header[0], 1, HeaderLenTotal, File);
// now write actual data.
std::size_t
DataSize = 1, nWritten;
for ( std::size_t iDim = 0; iDim < nDim; ++ iDim )
DataSize *= pShape[iDim];
nWritten = fwrite(pData, sizeof(pData[0]), DataSize, File);
if ( nWritten != DataSize )
throw FIoExceptionNpy("error in writing array data (disk full?)");
};
// read array from File in .npy format.
void ReadNpy(FArrayNpy &Out, FILE *File)
{
char
Header0[10],
Header1[256];
if ( 10 != fread(&Header0[0], 1, 10, File) )
throw FIoExceptionNpy("Failed to read npy file initial header");
for ( unsigned i = 0; i < 6; ++ i )
if ( Header0[i] != "\x93NUMPY"[i] )
throw FIoExceptionNpy("File does not have a numpy header.");
// printf("Version: %i.%i\n", (int)Header0[6], (int)Header0[7]);
if ( Header0[6] != 0x01 || Header0[7] != 0x00 )
throw FIoExceptionNpy("Cannot read this file version (know only npy version 1.0).");
uint16_t
HeaderSize = (uint16_t)Header0[8] + (((uint16_t)Header0[9]) << 8);
if ( HeaderSize >= 256 )
throw FIoExceptionNpy("File header too large. Expected at most 256 bytes.");
if ( HeaderSize != fread(&Header1[0], 1, HeaderSize, File) )
throw FIoExceptionNpy("Failed to read npy file main header");
// now comes the first complicated part: we need to read
// the python dictionary containing the data declaration.
// Looks like this:
char const *BaseTemplate = "{'descr': '%63[^']', 'fortran_order': %15[^,], 'shape': (%255[^)]), }";
// Note that the order of entries is actually fixed, as are the
// positions of the spaces: npy-format.txt says this is generated
// using the pformat function which enforces that.
char
// well... that's not safe.
DataType[64],
FortranOrder[16],
ShapeDesc[256];
int
nItems;
nItems = sscanf(&Header1[0], BaseTemplate, DataType, FortranOrder, ShapeDesc);
if ( nItems != 3 )
throw FIoExceptionNpy("Failed parse array shape description.");
#ifdef _SINGLE_PRECISION
if ( strcmp(&DataType[0], "<f4") != 0 )
throw FIoExceptionNpy("Can only read single precision arrays. Input has type: " + std::string(DataType) + "'");
#else
if ( strcmp(&DataType[0], "<f8") != 0 )
throw FIoExceptionNpy("Can only read double precision arrays. Input has type: " + std::string(DataType) + "'");
#endif
bool
OrderIsFortran = strcmp(&FortranOrder[0], "True") == 0,
OrderIsC = strcmp(&FortranOrder[0], "False") == 0;
if ( !OrderIsFortran && !OrderIsC )
throw FIoExceptionNpy("fortan_order field misformed in input.");
if (OrderIsC) {
std::cout << "not fortran style while reading "<<std::endl;
exit(0);
}
FShapeNpy
Shape;
Shape.clear();
Shape.reserve(6);
char
*p = &ShapeDesc[0];
for ( ; ; ) {
if ( p[0] == 0 ) // should always be 0-terminated if we reached this place.
break;
int n;
nItems = sscanf(p, "%i", &n);
if ( nItems != 1 )
throw FIoExceptionNpy("failed to process array shape description.");
Shape.push_back(n);
while ( p[0] != 0 && p[0] != ',' )
p += 1;
if ( p[0] == ',' )
p += 1;
}
// now compute strides and read actual data.
Out.Init(Shape, OrderIsFortran ? FArrayNpy::NPY_OrderFortran : FArrayNpy::NPY_OrderC);
std::size_t
nRead, DataSize = Out.Size();
nRead = fread(&Out.Data[0], sizeof(Out.Data[0]), DataSize, File);
if ( nRead != DataSize )
throw FIoExceptionNpy("error in reading array data (file complete?)");
};
// read array from File in .npy format.
void ReadNpyData(FNdArrayView &Out, FILE *File)
{
char
Header0[10],
Header1[256];
if ( 10 != fread(&Header0[0], 1, 10, File) )
throw FIoExceptionNpy("Failed to read npy file initial header");
for ( unsigned i = 0; i < 6; ++ i )
if ( Header0[i] != "\x93NUMPY"[i] )
throw FIoExceptionNpy("File does not have a numpy header.");
// printf("Version: %i.%i\n", (int)Header0[6], (int)Header0[7]);
if ( Header0[6] != 0x01 || Header0[7] != 0x00 )
throw FIoExceptionNpy("Cannot read this file version (know only npy version 1.0).");
uint16_t
HeaderSize = (uint16_t)Header0[8] + (((uint16_t)Header0[9]) << 8);
if ( HeaderSize >= 256 )
throw FIoExceptionNpy("File header too large. Expected at most 256 bytes.");
if ( HeaderSize != fread(&Header1[0], 1, HeaderSize, File) )
throw FIoExceptionNpy("Failed to read npy file main header");
// now comes the first complicated part: we need to read
// the python dictionary containing the data declaration.
// Looks like this:
char const *BaseTemplate = "{'descr': '%63[^']', 'fortran_order': %15[^,], 'shape': (%255[^)]), }";
// Note that the order of entries is actually fixed, as are the
// positions of the spaces: npy-format.txt says this is generated
// using the pformat function which enforces that.
char
// well... that's not safe.
DataType[64],
FortranOrder[16],
ShapeDesc[256];
int
nItems;
nItems = sscanf(&Header1[0], BaseTemplate, DataType, FortranOrder, ShapeDesc);
if ( nItems != 3 )
throw FIoExceptionNpy("Failed parse array shape description.");
#ifdef _SINGLE_PRECISION
if ( strcmp(&DataType[0], "<f4") != 0 )
throw FIoExceptionNpy("Can only read single precision arrays. Input has type: " + std::string(DataType) + "'");
#else
if ( strcmp(&DataType[0], "<f8") != 0 )
throw FIoExceptionNpy("Can only read double precision arrays. Input has type: " + std::string(DataType) + "'");
#endif
bool
OrderIsFortran = strcmp(&FortranOrder[0], "True") == 0,
OrderIsC = strcmp(&FortranOrder[0], "False") == 0;
if ( !OrderIsFortran && !OrderIsC )
throw FIoExceptionNpy("fortan_order field misformed in input.");
Out.Sizes.clear();
//Out.Sizes.reserve(6);
char
*p = &ShapeDesc[0];
for ( ; ; ) {
if ( p[0] == 0 ) // should always be 0-terminated if we reached this place.
break;
int n;
nItems = sscanf(p, "%i", &n);
if ( nItems != 1 )
throw FIoExceptionNpy("failed to process array shape description.");
Out.Sizes.push_back(n);
while ( p[0] != 0 && p[0] != ',' )
p += 1;
if ( p[0] == ',' )
p += 1;
}
Out.Strides.resize(Out.Sizes.size());
std::size_t
pDataSize = 1;
if ( OrderIsFortran) {
// fortran order.
for ( std::size_t iDim = 0; iDim < Out.Sizes.size(); ++ iDim ) {
Out.Strides[iDim] = pDataSize;
pDataSize *= Out.Sizes[iDim];
}
} else {
// that's the default case for npy files, unfortunately.
for ( std::size_t iDim = 0; iDim < Out.Sizes.size(); ++ iDim ) {
std::size_t iDim_ = Out.Sizes.size() - iDim - 1;
Out.Strides[iDim_] = pDataSize;
pDataSize *= Out.Sizes[iDim_];
}
//sometimes when the total dimension is only 1 python writes a c style
//tensor even if you explicitly ask it to write fortran style
if (pDataSize != 1) {
std::cout << "not fortran style while reading "<<std::endl;
exit(0);
}
}
if (pDataSize != Out.nValues())
throw FIoExceptionNpy("numpy array not of correct size");
std::size_t
nRead;
nRead = fread(&Out.pData[0], sizeof(Out.pData[0]), pDataSize, File);
if ( nRead != pDataSize )
throw FIoExceptionNpy("error in reading array data (file complete?)");
};
void WriteNpy(std::string const &FileName, FScalar const *pData, std::size_t const pShape[], std::size_t nDim)
{
FILE *File = fopen(FileName.c_str(), "wb");
if (File == 0)
throw FIoExceptionNpy("Failed to open for writing", FileName);
try {
WriteNpy(File, pData, pShape, nDim);
}
catch ( FIoExceptionNpy &e ) {
std::cout << "Trouble in reading file "<<FileName<<std::endl;
throw FIoExceptionNpy(e.what(), FileName);
}
fclose(File);
}
void WriteNpy(FILE *File, FScalar const *pData, FShapeNpy const &Shape) {
return WriteNpy(File, pData, &Shape[0], Shape.size());
}
void WriteNpy(std::string const &FileName, FScalar const *pData, FShapeNpy const &Shape) {
return WriteNpy(FileName, pData, &Shape[0], Shape.size());
}
void ReadNpy(FArrayNpy &Out, std::string const &FileName)
{
FILE *File = fopen(FileName.c_str(), "rb");
if (File == 0)
throw FIoExceptionNpy("Failed to open for reading", FileName);
try {
ReadNpy(Out, File);
}
catch ( FIoExceptionNpy &e ) {
throw FIoExceptionNpy(e.what(), FileName);
}
fclose(File);
};
void ReadNpyData(FNdArrayView &Out, std::string const &FileName)
{
FILE *File = fopen(FileName.c_str(), "rb");
if (File == 0)
throw FIoExceptionNpy("Failed to open for reading", FileName);
try {
ReadNpyData(Out, File);
}
catch ( FIoExceptionNpy &e ) {
throw FIoExceptionNpy(e.what(), FileName);
}
fclose(File);
};
// convenience functions for making array shape objects.
FShapeNpy MakeShape(std::size_t i0)
{ FShapeNpy r(1); r[0] = i0; return r; }
FShapeNpy MakeShape(std::size_t i0, std::size_t i1)
{ FShapeNpy r(2); r[0] = i0; r[1] = i1; return r; }
FShapeNpy MakeShape(std::size_t i0, std::size_t i1, std::size_t i2)
{ FShapeNpy r(3); r[0] = i0; r[1] = i1; r[2] = i2; return r; }
FShapeNpy MakeShape(std::size_t i0, std::size_t i1, std::size_t i2, std::size_t i3)
{ FShapeNpy r(4); r[0] = i0; r[1] = i1; r[2] = i2; r[3] = i3; return r; }
FIoExceptionNpy::FIoExceptionNpy(std::string const &Msg, std::string const &FileName)
: std::runtime_error(Msg + std::string((FileName != "")? (" while processing '" + FileName + "'").c_str():("")))
{};
std::size_t FArrayNpy::Size() const
{
std::size_t Size = 1;
for ( unsigned i = 0; i < Rank(); ++ i )
Size *= Shape[i];
return Size;
};
void FArrayNpy::swap(FArrayNpy &Other) {
Data.swap(Other.Data);
Shape.swap(Other.Shape);
Strides.swap(Other.Strides);
}
void FArrayNpy::Init(FShapeNpy const &Shape_, uint Flags)
{
Shape = Shape_;
Strides.resize(Rank());
std::size_t
DataSize = 1;
if ( (Flags & NPY_OrderC) == 0) {
// fortran order.
for ( std::size_t iDim = 0; iDim < Rank(); ++ iDim ) {
Strides[iDim] = DataSize;
DataSize *= Shape[iDim];
}
} else {
// that's the default case for npy files, unfortunately.
for ( std::size_t iDim = 0; iDim < Rank(); ++ iDim ) {
std::size_t iDim_ = Rank() - iDim - 1;
Strides[iDim_] = DataSize;
DataSize *= Shape[iDim_];
}
}
Data.resize(DataSize);
if ((Flags & NPY_ClearData) != 0)
Data.clear_data();
}
FArrayNpy::FArrayNpy(FShapeNpy const &Shape_, uint Flags)
{
Init(Shape_, Flags);
}
} // namespace ct
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include "Determinants.h"
#include "input.h"
#include "integral.h"
#include "SHCIshm.h"
#include "runFCIQMC.h"
#include "AGP.h"
#include "CorrelatedWavefunction.h"
#include "Jastrow.h"
#include "Slater.h"
#include "SelectedCI.h"
#include "trivialWF.h"
#include "trivialWalk.h"
#include "runVMC.h"
void printVMCHeader() {
if (commrank == 0) {
cout << endl << " Performing VMC..." << endl << endl;
}
}
void printFCIQMCHeader() {
if (commrank == 0) {
cout << endl << " Performing FCIQMC..." << endl << endl;
}
}
int main(int argc, char *argv[])
{
#ifndef SERIAL
boost::mpi::environment env(argc, argv);
boost::mpi::communicator world;
#endif
startofCalc = getTime();
initSHM();
//license();
if (commrank == 0) {
std::system("echo User:; echo $USER");
std::system("echo Hostname:; echo $HOSTNAME");
std::system("echo CPU info:; lscpu | head -15");
std::system("echo Computation started at:; date");
cout << "git commit: " << GIT_HASH << ", branch: " << GIT_BRANCH << ", compiled at: " << COMPILE_TIME << endl << endl;
cout << "Number of MPI processes used: " << commsize << endl << endl;
}
string inputFile = "input.dat";
if (argc > 1)
inputFile = string(argv[1]);
readInput(inputFile, schd, false);
generator = std::mt19937(schd.seed + commrank);
readIntegralsAndInitializeDeterminantStaticVariables("FCIDUMP");
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
int nel = nalpha + nbeta;
if (!schd.useTrialFCIQMC) {
TrivialWF wave;
TrivialWalk walk;
runFCIQMC(wave, walk, norbs, nel, nalpha, nbeta);
}
else if (schd.wavefunctionType == "jastrowagp") {
CorrelatedWavefunction<Jastrow, AGP> wave;
Walker<Jastrow, AGP> walk;
if (schd.restart || schd.fullRestart) {
wave.readWave();
wave.initWalker(walk);
} else {
printVMCHeader();
runVMC(wave, walk);
}
printFCIQMCHeader();
runFCIQMC(wave, walk, norbs, nel, nalpha, nbeta);
}
else if (schd.wavefunctionType == "jastrowslater") {
CorrelatedWavefunction<Jastrow, Slater> wave;
Walker<Jastrow, Slater> walk;
if (schd.restart || schd.fullRestart) {
wave.readWave();
wave.initWalker(walk);
} else {
printVMCHeader();
runVMC(wave, walk);
}
printFCIQMCHeader();
runFCIQMC(wave, walk, norbs, nel, nalpha, nbeta);
}
else if (schd.wavefunctionType == "selectedci") {
SelectedCI wave;
SimpleWalker walk;
wave.readWave();
wave.initWalker(walk);
runFCIQMC(wave, walk, norbs, nel, nalpha, nbeta);
}
boost::interprocess::shared_memory_object::remove(shciint2.c_str());
boost::interprocess::shared_memory_object::remove(shciint2shm.c_str());
return 0;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "Correlator.h"
#include "Determinants.h"
#include "global.h"
#include <vector>
#include "input.h"
Correlator::Correlator (std::vector<int>& pasites,
std::vector<int>& pbsites,
double iv) : asites(pasites), bsites(pbsites) {
if (asites.size()+bsites.size() > 20) {
std::cout << "Cannot handle correlators of size greater than 20."<<std::endl;
exit(0);
}
std::sort(asites.begin(), asites.end());
std::sort(bsites.begin(), bsites.end());
if(!schd.expCorrelator)
{// exponential correlator coefficients
Variables.resize( pow(2,asites.size()+bsites.size()), iv);
}
else
{
Variables.resize( pow(2,asites.size()+bsites.size()), 0.0);
//Variables.resize( pow(2,asites.size()+bsites.size()), 1.0);
}
}
void Correlator::OverlapWithGradient(const Determinant& d,
Eigen::VectorBlock<Eigen::VectorXd>& grad,
const double& ovlp,
const long& startIndex) const {
int asize = asites.size();
long index=0, one=1, index2=0;
for (int n=0; n<asize; n++)
if (d.getoccA( asites[n])) {
index |= (one<< (n+asize));
}
for (int n=0; n<asize; n++)
if (d.getoccB( bsites[n])) {
index |= (one<< (n));
}
if(!schd.expCorrelator)
{
grad[index+startIndex] += ovlp/Variables[index];
}
else
{
grad[index+startIndex] += ovlp;
//grad[index+startIndex] += 2*ovlp/Variables[index];
}
}
double Correlator::Overlap(const BigDeterminant& d) const {
double Coefficient = 0.0;
int asize = asites.size();
long index=0, one=1;
for (int n=0; n<asize; n++)
if (d [2*asites[n]] == 1)
index |= (one << (n+asize));
for (int n=0; n<asize; n++)
if (d [2*bsites[n]+1] == 1)
index |= (one<<(n));
if(!schd.expCorrelator)
{
return Variables[index];
}
else
{
return exp(Variables[index]);
//return (Variables[index]*Variables[index]);
}
}
double Correlator::Overlap(const Determinant& d) const {
double Coefficient = 0.0;
int asize = asites.size();
long index=0, one=1;
for (int n=0; n<asize; n++)
if (d.getoccA( asites[n]))
index |= (one << (n+asize));
for (int n=0; n<asize; n++)
if (d.getoccB( bsites[n]))
index |= (one<< (n));
if(!schd.expCorrelator)
{
return Variables[index];
}
else
{
return exp(Variables[index]);
//return (Variables[index]*Variables[index]);
}
}
double Correlator::OverlapRatio(const Determinant& d1, const Determinant& d2) const {
double Coefficient = 0.0;
int asize = asites.size();
long index1=0, index2=0, one=1;
for (int n=0; n<asize; n++) {
if (d1.getoccA( asites[n]))
index1 |= (one<< (n+asize));
if (d2.getoccA( asites[n]))
index2 |= (one<< (n+asize));
}
for (int n=0; n<asize; n++) {
if (d1.getoccB( bsites[n]))
index1 |= (one<< (n));
if (d2.getoccB( bsites[n]))
index2 |= (one<< (n));
}
if(!schd.expCorrelator)
{
return Variables[index1]/Variables[index2];
}
else
{
return exp(Variables[index1]-Variables[index2]);
}
}
double Correlator::OverlapRatio(const BigDeterminant& d1, const BigDeterminant& d2) const {
double Coefficient = 0.0;
int asize = asites.size();
long index1=0, index2=0, one=1;
for (int n=0; n<asize; n++) {
if (d1[2*asites[n]] == 1)
index1 |= (one<< (n+asize));
if (d2[2*asites[n]] == 1)
index2 |= (one<< (n+asize));
}
for (int n=0; n<asize; n++) {
if (d1[2*bsites[n]+1] == 1)
index1 |= (one<< (n));
if (d2[2*bsites[n]+1] == 1)
index2 |= (one<< (n));
}
if(!schd.expCorrelator)
{
return Variables[index1]/Variables[index2];
}
else
{
return exp(Variables[index1]-Variables[index2]);
}
}
std::ostream& operator<<(std::ostream& os, const Correlator& c) {
for (int i=0; i<c.asites.size(); i++)
os << c.asites[i]<<"a ";
for (int i=0; i<c.bsites.size(); i++)
os << c.bsites[i]<<"b ";
os<<std::endl;
return os;
}
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace NEVPT2_AAVV {
FTensorDecl TensorDecls[29] = {
/* 0*/{"b", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"B", "eeaa", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"t", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 3*/{"T", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 4*/{"p", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 5*/{"P", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 6*/{"Ap", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 7*/{"AP", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 8*/{"R", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 9*/{"f", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"f", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 13*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 14*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 15*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 16*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 17*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 18*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 19*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 20*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 21*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 22*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 23*/{"S1", "aAaA", "",USAGE_Density, STORAGE_Memory},
/* 24*/{"S2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 25*/{"W", "eeaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 26*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 27*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
};
//Number of terms : 4
FEqInfo EqsRes[3] = {
{"abcd,ef,abeg,cdfg", -4.0 , 4, {6,10,4,21}}, //-4.0 Ap[abcd] f[ef] p[abeg] E2[cdfg]
{"abcd,ae,befg,cdgf", 4.0 , 4, {6,11,4,21}}, //4.0 Ap[abcd] f[ae] p[befg] E2[cdgf]
{"abcd,efgh,abef,cdgh", -2.0 , 4, {6,19,4,21}}, //-2.0 Ap[abcd] W[efgh] p[abef] E2[cdgh]
//{"abcd,efgh,abei,cdfgih", -4.0 , 4, {6,19,4,22}}, //-4.0 Ap[abcd] W[efgh] p[abei] E3[cdfgih]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[2] = {
{"ABRS,ABPQ,RSPQ", 0.5, 3, {0, 25, 21}},
{"BARS,ABPQ,RSQP", 0.5, 3, {0, 25, 21}}
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "NEVPT2_AAVV";
Out.perturberClass = "AAVV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 29;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsRes = FEqSet(&EqsRes[0], 3, "NEVPT2_AAVV/Res");
Out.Overlap = FEqSet(&Overlap[0], 2, "NEVPT2_AAVV/Overlap");
};
};
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include <Eigen/Dense>
#include <algorithm>
#include "integral.h"
#include "Determinants.h"
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include "evaluateE.h"
//#include <math.h>
#include "global.h"
#include "input.h"
#include "statistics.h"
#include "sr.h"
#ifndef SERIAL
#include "mpi.h"
#endif
//using namespace std;
//using namespace Eigen;
/*
void comb(int N, int K, vector<vector<int>> &combinations)
{
std::vector<int> bitmask(K, 1);
bitmask.resize(N, 0); // N-K trailing 0's
// print integers and permute bitmask
int index = 0;
do
{
vector<int> comb;
for (int i = 0; i < N; ++i) // [0..N-1] integers
{
if (bitmask[i] == 1)
comb.push_back(i);
}
combinations.push_back(comb);
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
double calcTcorr(vector<double> &v)
{
//vector<double> w(v.size(), 1);
int n = v.size();
double norm, rk, f, neff;
double aver = 0, var = 0;
for (int i = 0; i < v.size(); i++)
{
aver += v[i] ;
norm += 1.0 ;
}
aver = aver / norm;
neff = 0.0;
for (int i = 0; i < n; i++)
{
neff = neff + 1.0;
};
neff = norm * norm / neff;
for (int i = 0; i < v.size(); i++)
{
var = var + (v[i] - aver) * (v[i] - aver);
};
var = var / norm;
var = var * neff / (neff - 1.0);
//double c[v.size()];
vector<double> c(v.size(),0);
//for (int i=0; i<v.size(); i++) c[i] = 0.0;
int l = v.size() - 1;
int i = commrank+1;
for (; i < l; i+=commsize)
//int i = 1;
//for (; i < l; i++)
{
c[i] = 0.0;
double norm = 0.0;
for (int k = 0; k < n - i; k++)
{
c[i] = c[i] + (v[k] - aver) * (v[k + i] - aver);
norm = norm + 1.0;
};
c[i] = c[i] / norm / var;
};
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &c[0], v.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
rk = 1.0;
f = 1.0;
i = 1;
ofstream out("OldCorrFunc.txt");
for (; i < l; i++)
{
if (commrank == 0)
{
out << c[i] << endl;
}
if (c[i] < 0.0)
f = 0.0;
rk = rk + 2.0 * c[i] * f;
}
out.close();
return rk;
}
void generateAllDeterminants(vector<Determinant>& allDets, int norbs, int nalpha, int nbeta) {
vector<vector<int>> alphaDets, betaDets;
comb(norbs, nalpha, alphaDets);
comb(norbs, nbeta, betaDets);
for (int a = 0; a < alphaDets.size(); a++)
for (int b = 0; b < betaDets.size(); b++)
{
Determinant d;
for (int i = 0; i < alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i], true);
for (int i = 0; i < betaDets[b].size(); i++)
d.setoccB(betaDets[b][i], true);
allDets.push_back(d);
}
alphaDets.clear();
betaDets.clear();
}
*/
<file_sep>#pragma once
#include <vector>
#include "BasisShell.h"
#include "timer.h"
extern BasisSet basis;
extern cumulTimer realSumTime;
extern cumulTimer kSumTime;
extern cumulTimer ksumTime1;
extern cumulTimer ksumTime2, ksumKsum;
extern "C" {
void initPeriodic(int* pshls, int *pao_loc, int *patm, int pnatm,
int *pbas, int pnbas, double *penv,
double* lattice);
};
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <algorithm>
#include "integral.h"
#include <Eigen/Dense>
#include <Eigen/Core>
#include "Determinants.h"
#include "input.h"
#include "workingArray.h"
using namespace std;
using namespace Eigen;
BigDeterminant::BigDeterminant(const Determinant& d) {
int norbs = Determinant::norbs;
occupation.resize(2*norbs, 0);
for (int i=0; i<2*norbs; i++)
if (d.getocc(i)) occupation[i] = 1;
}
const char& BigDeterminant::operator[] (int j) const
{
return occupation[j];
}
char& BigDeterminant::operator[] (int j)
{
return occupation[j];
}
Determinant::Determinant() {
for (int i=0; i<DetLen; i++) {
reprA[i] = 0;
reprB[i] = 0;
}
}
Determinant::Determinant(const Determinant& d) {
for (int i=0; i<DetLen; i++) {
reprA[i] = d.reprA[i];
reprB[i] = d.reprB[i];
}
}
void Determinant::operator=(const Determinant& d) {
for (int i=0; i<DetLen; i++) {
reprA[i] = d.reprA[i];
reprB[i] = d.reprB[i];
}
}
void Determinant::getOpenClosed( std::vector<int>& open, std::vector<int>& closed) const {
for (int i=0; i<norbs; i++) {
if ( getoccA(i)) closed.push_back(2*i);
else open.push_back(2*i);
if ( getoccB(i)) closed.push_back(2*i+1);
else open.push_back(2*i+1);
}
}
void Determinant::getOpenClosed( bool sz, std::vector<int>& open, std::vector<int>& closed) const {
for (int i=0; i<norbs; i++)
{
if (sz==0)
{
if ( getoccA(i)) closed.push_back(i);
else open.push_back(i);
}
else
{
if ( getoccB(i)) closed.push_back(i);
else open.push_back(i);
}
}
}
void Determinant::getOpenClosedAlphaBeta( std::vector<int>& openAlpha,
std::vector<int>& closedAlpha,
std::vector<int>& openBeta,
std::vector<int>& closedBeta
) const {
for (int i=0; i<norbs; i++) {
if ( getoccA(i)) closedAlpha.push_back(i);
else openAlpha.push_back(i);
if ( getoccB(i)) closedBeta.push_back(i);
else openBeta.push_back(i);
}
}
void Determinant::getClosedAlphaBeta( std::vector<int>& closedAlpha,
std::vector<int>& closedBeta ) const
{
for (int i=0; i<norbs; i++) {
if ( getoccA(i)) closedAlpha.push_back(i);
if ( getoccB(i)) closedBeta.push_back(i);
}
}
void Determinant::getAlphaBeta(std::vector<int>& alpha, std::vector<int>& beta) const {
for (int i=0; i<64*EffDetLen; i++) {
if (getoccA(i)) alpha.push_back(i);
if (getoccB(i)) beta .push_back(i);
}
}
void Determinant::getClosed(std::vector<int>& closed) const {
for (int i=0; i<norbs; i++) {
if ( getoccA(i)) {
closed.push_back(2*i);
}
if ( getoccB(i)) {
closed.push_back(2*i+1);
}
}
}
// Version of getClosed for the case where closed has been allocated
// with the correct size already. This is quicker, for cases where
// this is important.
void Determinant::getClosedAllocated(std::vector<int>& closed) const {
int n = 0;
for (int i=0; i<norbs; i++) {
if ( getoccA(i)) {
closed.at(n) = 2*i;
n++;
}
if ( getoccB(i)) {
closed.at(n) = 2*i+1;
n++;
}
}
}
void Determinant::getClosed( bool sz, std::vector<int>& closed) const {
for (int i=0; i<norbs; i++)
{
if (sz==0)
{
if ( getoccA(i)) closed.push_back(i);
}
else
{
if ( getoccB(i)) closed.push_back(i);
}
}
}
int Determinant::getNbetaBefore(int i) const {
int occ = 0;
for (int n = 0; n < i/64; n++) {
occ += CountNonZeroBits(reprB[n]);
}
long one = 1; long mask = ( one << (i%64) ) - one;
long result = (reprB[i/64] & mask ) ;
occ += CountNonZeroBits(result);
return occ;
}
int Determinant::getNalphaBefore(int i) const {
int occ = 0;
for (int n = 0; n < i/64; n++) {
occ += CountNonZeroBits(reprA[n]);
}
long one = 1; long mask = ( one << (i%64) ) - one;
long result = (reprA[i/64] & mask ) ;
occ += CountNonZeroBits(result);
return occ;
}
double Determinant::parityFull(const int ex2, const int i, const int j,
const int a, const int b) const {
double parity = 1.0;
Determinant dcopy = *this;
parity *= dcopy.parity(a/2, i/2, i%2);
dcopy.setocc(i, false);
dcopy.setocc(a, true);
if (ex2 != 0) {
parity *= dcopy.parity(b/2, j/2, j%2);
}
return parity;
}
double Determinant::parityA(const int& a, const int& i) const {
double parity = 1.0;
int occ = getNalphaBefore(i);
occ += getNalphaBefore(a);
parity *= (occ%2==0) ? 1.: -1.;
if (i < a) parity *= -1.;
return parity;
}
double Determinant::parity(const int& a, const int& i, const bool& sz) const {
if (sz == 0) return parityA(a, i);
else return parityB(a, i);
}
double Determinant::parityB(const int& a, const int& i) const {
double parity = 1.0;
int occ = getNbetaBefore(i);
occ += getNbetaBefore(a);
parity *= (occ%2==0) ? 1.: -1.;
if (i < a) parity *= -1.;
return parity;
}
double Determinant::parityA(const vector<int>& aArray, const vector<int>& iArray) const
{
double p = 1.;
Determinant dcopy = *this;
for (int i = 0; i < iArray.size(); i++)
{
p *= dcopy.parityA(aArray[i], iArray[i]);
dcopy.setoccA(iArray[i], false);
dcopy.setoccA(aArray[i], true);
}
return p;
}
double Determinant::parityB(const vector<int>& aArray, const vector<int>& iArray) const
{
double p = 1.;
Determinant dcopy = *this;
for (int i = 0; i < iArray.size(); i++)
{
p *= dcopy.parityB(aArray[i], iArray[i]);
dcopy.setoccB(iArray[i], false);
dcopy.setoccB(aArray[i], true);
}
return p;
}
double Determinant::parity(const vector<int>& aArray, const vector<int>& iArray, bool sz) const
{
if (sz==0) return parityA(aArray, iArray);
else return parityB(aArray, iArray);
}
int Determinant::Noccupied() const {
int nelec = 0;
for (int i=0; i<DetLen; i++) {
nelec += CountNonZeroBits(reprA[i]);
nelec += CountNonZeroBits(reprB[i]);
}
return nelec;
}
int Determinant::Nalpha() const {
int nelec = 0;
for (int i=0; i<DetLen; i++) {
nelec += CountNonZeroBits(reprA[i]);
}
return nelec;
}
int Determinant::Nbeta() const {
int nelec = 0;
for (int i=0; i<DetLen; i++) {
nelec += CountNonZeroBits(reprB[i]);
}
return nelec;
}
void Determinant::flipAlphaBeta() {
for (int i = 0; i < DetLen; i++) {
long temp = reprA[i];
reprA[i] = reprB[i];
reprB[i] = temp;
}
}
//Is the excitation between *this and d less than equal to 2.
bool Determinant::connected(const Determinant& d) const {
int ndiff = 0; long u;
for (int i=0; i<DetLen; i++) {
ndiff += CountNonZeroBits(reprA[i] ^ d.reprA[i]);
ndiff += CountNonZeroBits(reprB[i] ^ d.reprB[i]);
}
return ndiff<=4;
//return true;
}
//Get the number of electrons that need to be excited to get determinant d from *this determinant
//e.g. single excitation will return 1
int Determinant::ExcitationDistance(const Determinant& d) const {
int ndiff = 0;
for (int i=0; i<DetLen; i++) {
ndiff += CountNonZeroBits(reprA[i] ^ d.reprA[i]);
ndiff += CountNonZeroBits(reprB[i] ^ d.reprB[i]);
}
return ndiff/2;
}
//the comparison between determinants is performed
bool Determinant::operator<(const Determinant& d) const {
for (int i=DetLen-1; i>=0 ; i--) {
if (reprA[i] < d.reprA[i]) return true;
else if (reprA[i] > d.reprA[i]) return false;
if (reprB[i] < d.reprB[i]) return true;
else if (reprB[i] > d.reprB[i]) return false;
}
return false;
}
//check if the determinants are equal
bool Determinant::operator==(const Determinant& d) const {
for (int i=DetLen-1; i>=0 ; i--) {
if (reprA[i] != d.reprA[i]) return false;
if (reprB[i] != d.reprB[i]) return false;
}
return true;
}
//set the occupation of the ith orbital
void Determinant::setoccA(int i, bool occ) {
long Integer = i/64, bit = i%64, one=1;
if (occ)
reprA[Integer] |= one << bit;
else
reprA[Integer] &= ~(one<<bit);
}
//set the occupation of the ith orbital
void Determinant::setoccB(int i, bool occ) {
long Integer = i/64, bit = i%64, one=1;
if (occ)
reprB[Integer] |= one << bit;
else
reprB[Integer] &= ~(one<<bit);
}
void Determinant::setocc(int i, bool occ) {
if (i%2 == 0) return setoccA(i/2, occ);
else return setoccB(i/2, occ);
}
void Determinant::setocc(int i, bool sz, bool occ) {
if (sz == 0) return setoccA(i, occ);
else return setoccB(i, occ);
}
bool Determinant::getocc(int i) const {
if (i%2 == 0) return getoccA(i/2);
else return getoccB(i/2);
}
bool Determinant::getocc(int i, bool sz) const {
if (sz == 0) return getoccA(i);
else return getoccB(i);
}
//get the occupation of the ith orbital
bool Determinant::getoccA(int i) const {
//asser(i<norbs);
long Integer = i/64, bit = i%64, reprBit = reprA[Integer];
if(( reprBit>>bit & 1) == 0)
return false;
else
return true;
}
bool Determinant::getoccB(int i) const {
//asser(i<norbs);
long Integer = i/64, bit = i%64, reprBit = reprB[Integer];
if(( reprBit>>bit & 1) == 0)
return false;
else
return true;
}
//Prints the determinant
ostream& operator<<(ostream& os, const Determinant& d) {
for (int i=0; i<Determinant::norbs; i++) {
if (d.getoccA(i)==false && d.getoccB(i) == false)
os<<0<<" ";
else if (d.getoccA(i)==true && d.getoccB(i) == false)
os<<"a"<<" ";
else if (d.getoccA(i)==false && d.getoccB(i) == true)
os<<"b"<<" ";
else if (d.getoccA(i)==true && d.getoccB(i) == true)
os<<2<<" ";
if ( (i+1)%5 == 0)
os <<" ";
}
return os;
}
void Determinant::printActive(ostream& os) {
for (int i = schd.nciCore; i < schd.nciCore + schd.nciAct; i++) {
if (getoccA(i) == false && getoccB(i) == false)
os << 0 << " ";
else if (getoccA(i) == true && getoccB(i) == false)
os << "a" << " ";
else if (getoccA(i) == false && getoccB(i) == true)
os << "b" << " ";
else if (getoccA(i) == true && getoccB(i) == true)
os << 2 << " ";
if ( (i+1)%5 == 0)
os << " ";
}
}
size_t hash_value(Determinant const& d) {
std::size_t seed = 0;
//boost::hash_combine(seed, d.reprA[0]);
//boost::hash_combine(seed, d.reprB[0]);
boost::hash_combine(seed, d.reprA[0] * 2654435761);
boost::hash_combine(seed, d.reprB[0] * 2654435761);
//for (int i = 0; i < DetLen; i++) {
// boost::hash_combine(seed, d.reprA[i]);
// boost::hash_combine(seed, d.reprB[i]);
//}
return seed;
}
//=============================================================================
double Determinant::Energy(const oneInt& I1, const twoInt&I2, const double& coreE) const {
double energy = 0.0;
size_t one = 1;
vector<int> closed;
for(int i=0; i<DetLen; i++) {
long reprBit = reprA[i];
while (reprBit != 0) {
int pos = __builtin_ffsl(reprBit);
closed.push_back( 2*(i*64+pos-1));
reprBit &= ~(one<<(pos-1));
}
reprBit = reprB[i];
while (reprBit != 0) {
int pos = __builtin_ffsl(reprBit);
closed.push_back( 2*(i*64+pos-1)+1);
reprBit &= ~(one<<(pos-1));
}
}
for (int i=0; i<closed.size(); i++) {
int I = closed.at(i);
#ifdef Complex
energy += I1(I,I).real();
#else
energy += I1(I,I);
#endif
for (int j=i+1; j<closed.size(); j++) {
int J = closed.at(j);
energy += I2.Direct(I/2,J/2);
if ( (I%2) == (J%2) ) {
energy -= I2.Exchange(I/2, J/2);
}
}
}
return energy+coreE;
}
//=============================================================================
double Determinant::parityAA(const int& i, const int& j, const int& a, const int& b) const {
double sgn = 1.0;
Determinant dcopy = *this;
sgn *= dcopy.parityA(a, i);
dcopy.setoccA(i, false); dcopy.setoccA(a,true);
sgn *= dcopy.parityA(b, j);
return sgn;
}
double Determinant::parityBB(const int& i, const int& j, const int& a, const int& b) const {
double sgn = 1.0;
Determinant dcopy = *this;
sgn = dcopy.parityB(a, i);
dcopy.setoccB(i, false); dcopy.setoccB(a,true);
sgn *= dcopy.parityB(b, j);
return sgn;
}
//=============================================================================
CItype Determinant::Hij_2ExciteAA(const int& a, const int& i, const int& b,
const int& j, const oneInt&I1, const twoInt& I2) const
{
double sgn = parityAA(i, j, a, b);
return sgn*(I2(2*a,2*i,2*b,2*j) - I2(2*a,2*j,2*b,2*i));
}
CItype Determinant::Hij_2ExciteBB(const int& a, const int& i, const int& b,
const int& j, const oneInt&I1, const twoInt& I2) const
{
double sgn = parityBB(i, j, a, b);
return sgn*(I2(2*a+1, 2*i+1, 2*b+1, 2*j+1) - I2(2*a+1, 2*j+1, 2*b+1, 2*i+1 ));
}
CItype Determinant::Hij_2ExciteAB(const int& a, const int& i, const int& b,
const int& j, const oneInt&I1, const twoInt& I2) const {
double sgn = parityA(a, i);
sgn *= parityB(b,j);
return sgn*I2(2*a,2*i,2*b+1,2*j+1);
}
CItype Determinant::Hij_1ExciteScreened(const int& a, const int& i,
const twoIntHeatBathSHM& I2hb, const double& TINY,
bool doparity) const {
double tia = I1(a, i);
int X = max(i/2, a/2), Y = min(i/2, a/2);
size_t pairIndex = X * (X + 1) / 2 + Y;
size_t start = I2hb.startingIndicesSingleIntegrals[pairIndex];
size_t end = I2hb.startingIndicesSingleIntegrals[pairIndex + 1];
float *integrals = I2hb.singleIntegrals;
short *orbIndices = I2hb.singleIntegralsPairs;
for (size_t index = start; index < end; index++)
{
if (fabs(integrals[index]) < TINY)
break;
int j = orbIndices[2 * index];
if (i % 2 == 1 && j % 2 == 1)
j--;
else if (i % 2 == 1 && j % 2 == 0)
j++;
if (getocc(j) )
tia += integrals[index];
}
double sgn = 1.0;
int A = a/2, I = i/2;
if (doparity && i%2 == 0) sgn *= parityA(A, I);
else if (doparity && i%2 == 1) sgn *= parityB(A, I);
return tia*sgn;
}
//=============================================================================
CItype Determinant::Hij_1Excite(const int& a, const int& i, const oneInt&I1,
const twoInt& I2, bool doparity) const {
int aSpatial = a/2;
int iSpatial = i/2;
if (i%2 == 0 && a%2 == 0) {
return Hij_1ExciteA(aSpatial, iSpatial, I1, I2, doparity);
} else if (i%2 == 1 && a%2 == 1) {
return Hij_1ExciteB(aSpatial, iSpatial, I1, I2, doparity);
} else {
cout << "ERROR: orbitals have different spin in Hij_1Excite" << endl;
}
}
CItype Determinant::Hij_1ExciteA(const int& a, const int& i, const oneInt&I1,
const twoInt& I2, bool doparity) const {
double sgn = 1.0;
if (doparity) sgn *= parityA(a, i);
CItype energy = I1(2*a, 2*i);
if (schd.Hamiltonian == HUBBARD) return energy*sgn;
long one = 1;
for (int I=0; I<DetLen; I++) {
long reprBit = reprA[I];
while (reprBit != 0) {
int pos = __builtin_ffsl(reprBit);
int j = I*64+pos-1;
energy += (I2(2*a, 2*i, 2*j, 2*j) - I2(2*a, 2*j, 2*j, 2*i));
reprBit &= ~(one<<(pos-1));
}
reprBit = reprB[I];
while (reprBit != 0) {
int pos = __builtin_ffsl(reprBit);
int j = I*64+pos-1;
energy += (I2(2*a, 2*i, 2*j+1, 2*j+1));
reprBit &= ~(one<<(pos-1));
}
}
energy *= sgn;
return energy;
}
CItype Determinant::Hij_1ExciteB(const int& a, const int& i, const oneInt&I1,
const twoInt& I2, bool doparity) const {
double sgn = 1.0;
if (doparity) sgn *= parityB(a, i);
CItype energy = I1(2*a+1, 2*i+1);
if (schd.Hamiltonian == HUBBARD) return energy*sgn;
long one = 1;
for (int I=0; I<DetLen; I++) {
long reprBit = reprA[I];
while (reprBit != 0) {
int pos = __builtin_ffsl(reprBit);
int j = I*64+pos-1;
energy += (I2(2*a+1, 2*i+1, 2*j, 2*j));
reprBit &= ~(one<<(pos-1));
}
reprBit = reprB[I];
while (reprBit != 0) {
int pos = __builtin_ffsl(reprBit);
int j = I*64+pos-1;
energy += (I2(2*a+1, 2*i+1, 2*j+1, 2*j+1) - I2(2*a+1, 2*j+1, 2*j+1, 2*i+1));
reprBit &= ~(one<<(pos-1));
}
}
energy *= sgn;
return energy;
}
//=============================================================================
CItype Hij(const Determinant& bra, const Determinant& ket, const oneInt& I1,
const twoInt& I2, const double& coreE) {
int cre[200],des[200],ncrea=0,ncreb=0,ndesa=0,ndesb=0;
long u,b,k,one=1;
cre[0]=-1; cre[1]=-1; des[0]=-1; des[1]=-1;
for (int i=0; i<Determinant::EffDetLen; i++) {
u = bra.reprA[i] ^ ket.reprA[i];
b = u & bra.reprA[i]; //the cre bits
k = u & ket.reprA[i]; //the des bits
while(b != 0) {
int pos = __builtin_ffsl(b);
cre[ncrea+ncreb] = 2*(pos-1+i*64);
ncrea++;
b &= ~(one<<(pos-1));
}
while(k != 0) {
int pos = __builtin_ffsl(k);
des[ndesa+ndesb] = 2*(pos-1+i*64);
ndesa++;
k &= ~(one<<(pos-1));
}
u = bra.reprB[i] ^ ket.reprB[i];
b = u & bra.reprB[i]; //the cre bits
k = u & ket.reprB[i]; //the des bits
while(b != 0) {
int pos = __builtin_ffsl(b);
cre[ncrea+ncreb] = 2*(pos-1+i*64)+1;
ncreb++;
b &= ~(one<<(pos-1));
}
while(k != 0) {
int pos = __builtin_ffsl(k);
des[ndesa+ndesb] = 2*(pos-1+i*64)+1;
ndesb++;
k &= ~(one<<(pos-1));
}
}
if (ncrea+ncreb == 0) {
cout << bra<<endl;
cout << ket<<endl;
cout <<"Use the function for energy"<<endl;
exit(0);
}
else if (ncrea == 1 && ncreb == 0) {
int c0=cre[0]/2, d0 = des[0]/2;
return ket.Hij_1ExciteA(c0, d0, I1, I2);
}
else if (ncrea == 0 && ncreb == 1) {
int c0=cre[0]/2, d0 = des[0]/2;
return ket.Hij_1ExciteB(c0, d0, I1, I2);
}
else if (ncrea == 0 && ncreb == 2) {
int c0=cre[0]/2, d0 = des[0]/2;
int c1=cre[1]/2, d1 = des[1]/2;
return ket.Hij_2ExciteBB(c0, d0, c1, d1, I1, I2);
}
else if (ncrea == 2 && ncreb == 0) {
int c0=cre[0]/2, d0 = des[0]/2;
int c1=cre[1]/2, d1 = des[1]/2;
return ket.Hij_2ExciteAA(c0, d0, c1, d1, I1, I2);
}
else if (ncrea == 1 && ncreb == 1) {
int c0=cre[0]/2, d0 = des[0]/2;
int c1=cre[1]/2, d1 = des[1]/2;
if (cre[0]%2 == 0)
return ket.Hij_2ExciteAB(c0, d0, c1, d1, I1, I2);
else
return ket.Hij_2ExciteAB(c1, d1, c0, d0, I1, I2);
}
else {
return 0.;
}
}
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket,
vector<int>& creA, vector<int>& desA,
vector<int>& creB, vector<int>& desB)
{
std::fill(creA.begin(), creA.end(), -1);
std::fill(desA.begin(), desA.end(), -1);
std::fill(creB.begin(), creB.end(), -1);
std::fill(desB.begin(), desB.end(), -1);
int ncre = 0, ndes = 0;
long u, b, k, one = 1;
for (int i = 0; i < DetLen; i++)
{
u = bra.reprA[i] ^ ket.reprA[i];
b = u & bra.reprA[i]; //the cre bits
k = u & ket.reprA[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
creA[ncre] = pos - 1 + i * 64;
ncre++;
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
desA[ndes] = pos - 1 + i * 64;
ndes++;
k &= ~(one << (pos - 1));
}
}
ncre = 0; ndes = 0;
for (int i = 0; i < DetLen; i++)
{
u = bra.reprB[i] ^ ket.reprB[i];
b = u & bra.reprB[i]; //the cre bits
k = u & ket.reprB[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
creB[ncre] = pos - 1 + i * 64;
ncre++;
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
desB[ndes] = pos - 1 + i * 64;
ndes++;
k &= ~(one << (pos - 1));
}
}
}
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket,
vector<int>& cre, vector<int>& des,
bool sz)
{
std::fill(cre.begin(), cre.end(), -1);
std::fill(des.begin(), des.end(), -1);
int ncre = 0, ndes = 0;
long u, b, k, one = 1;
if (sz == 0)
{
for (int i = 0; i < DetLen; i++)
{
u = bra.reprA[i] ^ ket.reprA[i];
b = u & bra.reprA[i]; //the cre bits
k = u & ket.reprA[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
cre[ncre] = pos - 1 + i * 64;
ncre++;
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
des[ndes] = pos - 1 + i * 64;
ndes++;
k &= ~(one << (pos - 1));
}
}
}
else
{
for (int i = 0; i < DetLen; i++)
{
u = bra.reprB[i] ^ ket.reprB[i];
b = u & bra.reprB[i]; //the cre bits
k = u & ket.reprB[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
cre[ncre] = pos - 1 + i * 64;
ncre++;
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
des[ndes] = pos - 1 + i * 64;
ndes++;
k &= ~(one << (pos - 1));
}
}
}
}
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket, int &I, int &A)
{
I = -1; A = -1;
long u, b, k, one = 1;
for (int i = 0; i < DetLen; i++)
{
u = bra.reprA[i] ^ ket.reprA[i];
b = u & bra.reprA[i]; //the cre bits
k = u & ket.reprA[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
I = 2*(pos - 1 + i * 64);
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
A = 2 * (pos - 1 + i * 64);
k &= ~(one << (pos - 1));
}
}
for (int i = 0; i < DetLen; i++)
{
u = bra.reprB[i] ^ ket.reprB[i];
b = u & bra.reprB[i]; //the cre bits
k = u & ket.reprB[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
I = 2 * (pos - 1 + i * 64) + 1;
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
A = 2 * (pos - 1 + i * 64) + 1;
k &= ~(one << (pos - 1));
}
}
}
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket, int &I, int &J,
int& A, int& B)
{
I = -1; A = -1; J = -1; B = -1;
long u, b, k, one = 1;
for (int i = 0; i < DetLen; i++)
{
u = bra.reprA[i] ^ ket.reprA[i];
b = u & bra.reprA[i]; //the cre bits
k = u & ket.reprA[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
if (I == -1)
I = 2*(pos - 1 + i * 64);
else
J = 2*(pos - 1 + i * 64);
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
if (A == -1)
A = 2*(pos - 1 + i * 64);
else
B = 2*(pos - 1 + i * 64);
//A = 2 * (pos - 1 + i * 64);
k &= ~(one << (pos - 1));
}
}
for (int i = 0; i < DetLen; i++)
{
u = bra.reprB[i] ^ ket.reprB[i];
b = u & bra.reprB[i]; //the cre bits
k = u & ket.reprB[i]; //the des bits
while (b != 0)
{
int pos = __builtin_ffsl(b);
if (I == -1)
I = 2*(pos - 1 + i * 64) + 1;
else
J = 2*(pos - 1 + i * 64) + 1;
b &= ~(one << (pos - 1));
}
while (k != 0)
{
int pos = __builtin_ffsl(k);
if (A == -1)
A = 2*(pos - 1 + i * 64) + 1;
else
B = 2*(pos - 1 + i * 64) + 1;
k &= ~(one << (pos - 1));
}
}
}
double getParityForDiceToAlphaBeta(const Determinant& det)
{
double parity = 1.0;
int nalpha = det.Nalpha();
int norbs = Determinant::norbs;
for (int i=0; i<norbs; i++)
{
if (det.getoccB(norbs-1-i))
{
int nAlphaAfteri = nalpha - det.getNalphaBefore(norbs-1-i);
if (det.getoccA(norbs-1-i)) nAlphaAfteri--;
if (nAlphaAfteri%2 == 1) parity *= -1;
}
}
return parity;
}
void generateAllScreenedSingleExcitation(const Determinant& d,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
//schd.active = number of active spatial orbitals, assumed to be contiguous and at the beginning
//auto ub_1 = upper_bound(open.begin(), open.end(), 2*schd.numActive - 1);
//int indAct = distance(open.begin(), ub_1);
//auto ub_2 = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
//int indCore = distance(closed.begin(), ub_2);
for (int i = 0; i < closed.size(); i++) {
for (int a = 0; a < open.size(); a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > THRESH)
{
int I = closed[i] / 2, A = open[a] / 2;
const double tia = d.Hij_1ExciteScreened(open[a], closed[i], I2hb,
TINY, doparity);
if (abs(tia) > THRESH) {
work.appendValue(0., closed[i]*2*norbs+open[a], 0, tia);
}
}
}
}
}
void generateAllScreenedDoubleExcitation(const Determinant& d,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
int nclosed = closed.size();
for (int i = 0; i<nclosed; i++) {
for (int j = 0; j<i; j++) {
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hb.getIntegralArray(closed[i], closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// if we are going below the criterion, break
//if (fabs(integrals[index]) < THRESH)
// break;
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closed[i] % 2,
b = 2 * orbIndices[2 * index + 1] + closed[j] % 2;
//if ((!(d.getocc(a) || d.getocc(b))) && (a < 2*schd.numActive) && (b < 2*schd.numActive)) {//uncomment for VMC active space calculations
if (!(d.getocc(a) || d.getocc(b))) {
//cout << "a " << a << " b " << b << endl;
work.appendValue(0.0, closed[i] * 2 * norbs + a,
closed[j] * 2 * norbs + b, integrals[index]);
}
}
}
}
}
void generateAllScreenedDoubleExcitationsFOIS(const Determinant& d,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
auto ub = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCore = distance(closed.begin(), ub);
int nclosed = closed.size();
for (int i = indCore; i<nclosed; i++) {
for (int j = indCore; j<i; j++) {
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hb.getIntegralArray(closed[i], closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// if we are going below the criterion, break
//if (fabs(integrals[index]) < THRESH)
// break;
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closed[i] % 2,
b = 2 * orbIndices[2 * index + 1] + closed[j] % 2;
if (a >= 2*first_virtual && b >= 2*first_virtual && closed[i] < 2*first_virtual && closed[j] < 2*first_virtual) continue;
if (!(d.getocc(a) || d.getocc(b))) {
work.appendValue(0.0, closed[i] * 2 * norbs + a,
closed[j] * 2 * norbs + b, integrals[index]);
}
}
}
}
}
void generateAllScreenedSingleExcitationsDyallOld(const Determinant& det,
const Determinant& detAct,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
det.getOpenClosed(open, closed);
for (int i = 0; i < closed.size(); i++) {
for (int a = 0; a < open.size(); a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > THRESH)
{
int I = closed[i] / 2, A = open[a] / 2;
const double tia = det.Hij_1ExciteScreened(open[a], closed[i], I2hb,
TINY, doparity);
double tiaD = 0.;
if (I >= schd.nciCore && I < first_virtual && A >= schd.nciCore && A < first_virtual)
tiaD = detAct.Hij_1ExciteScreened(open[a], closed[i], I2hb,
TINY, doparity);
if (abs(tia) > THRESH) {
work.appendValue(tiaD, closed[i] * 2 * norbs + open[a], 0, tia); // jailbreaking overlapRatio for Dyall ham element (tiaD)
}
}
}
}
}
void generateAllScreenedDoubleExcitationsDyallOld(const Determinant& det,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
det.getOpenClosed(open, closed);
for (int i=0; i<closed.size(); i++) {
for (int j = 0; j<i; j++) {
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hb.getIntegralArray(closed[i], closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// if we are going below the criterion, break
//if (fabs(integrals[index]) < THRESH)
// break;
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closed[i] % 2,
b = 2 * orbIndices[2 * index + 1] + closed[j] % 2;
// Dyall excitation?
double flag = 0.0;
if (closed[i] < 2*first_virtual && a < 2*first_virtual && b < 2*first_virtual) // note j < i, so no j condition
{
if (closed[j] >= 2*schd.nciCore && a >= 2*schd.nciCore && b >= 2*schd.nciCore) // note i > j, so no i condition
{
flag = 1.0;
}
}
//if ((!(d.getocc(a) || d.getocc(b))) && (a < 2*schd.numActive) && (b < 2*schd.numActive)) {//uncomment for VMC active space calculations
if (!(det.getocc(a) || det.getocc(b))) {
//cout << "a " << a << " b " << b << endl;
work.appendValue(flag, closed[i] * 2 * norbs + a,
closed[j] * 2 * norbs + b, integrals[index]);
}
}
}
}
}
void generateAllScreenedSingleExcitationsDyall(const Determinant& det,
const Determinant& detAct,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
det.getOpenClosed(open, closed);
auto ub_1 = upper_bound(open.begin(), open.end(), 2*schd.nciCore - 1);
int indCoreOpen = distance(open.begin(), ub_1);
auto ub_2 = upper_bound(open.begin(), open.end(), 2*first_virtual - 1);
int indActOpen = distance(open.begin(), ub_2);
auto ub_3 = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCoreClosed = distance(closed.begin(), ub_3);
auto ub_4 = upper_bound(closed.begin(), closed.end(), 2*first_virtual - 1);
int indActClosed = distance(closed.begin(), ub_4);
for (int i = indCoreClosed; i < indActClosed; i++) {
for (int a = indCoreOpen; a < indActOpen; a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > THRESH)
{
int I = closed[i] / 2, A = open[a] / 2;
//const double tia = det.Hij_1ExciteScreened(open[a], closed[i], I2hb,
// TINY, doparity);
double tiaD = detAct.Hij_1ExciteScreened(open[a], closed[i], I2hb,
TINY, doparity);
if (abs(tiaD) > THRESH) {
work.appendValue(tiaD, closed[i] * 2 * norbs + open[a], 0, tiaD);
}
}
}
}
}
void generateAllScreenedDoubleExcitationsDyall(const Determinant& det,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
det.getOpenClosed(open, closed);
auto ub_1 = upper_bound(closed.begin(), closed.end(), 2*first_virtual - 1);
int indAct = distance(closed.begin(), ub_1);
auto ub_2 = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCore = distance(closed.begin(), ub_2);
for (int i = indCore; i<indAct; i++) {
for (int j = indCore; j<i; j++) {
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArrayCAS(closed[i], closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closed[i] % 2;
int b = 2 * orbIndices[2 * index + 1] + closed[j] % 2;
double flag = 1.0;
if (!(det.getocc(a) || det.getocc(b))) {
work.appendValue(flag, closed[i] * 2 * norbs + a,
closed[j] * 2 * norbs + b, integrals[index]);
}
}
}
}
}
//---Generate all screened excitations into the CAS-------------------
//---From excitation class 0 (the CAS itself) into the CAS------------
void generateAllScreenedSingleExcitationsCAS_0h0p(const Determinant& d,
const double& THRESH,
const double& TINY,
workingArray& work,
bool doparity) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
auto ub_1 = upper_bound(open.begin(), open.end(), 2*first_virtual - 1);
int indAct = distance(open.begin(), ub_1);
auto ub_2 = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCore = distance(closed.begin(), ub_2);
for (int i = indCore; i < closed.size(); i++) {
for (int a = 0; a < indAct; a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > THRESH)
{
const double tia = d.Hij_1ExciteScreened(open[a], closed[i], I2hb,
TINY, doparity);
if (abs(tia) > THRESH) {
work.appendValue(0., closed[i]*2*norbs+open[a], 0, tia);
}
}
}
}
}
//---From excitation class 0 (the CAS itself) into the CAS------------
void generateAllScreenedDoubleExcitationsCAS_0h0p(const Determinant& d,
const double& THRESH,
workingArray& work) {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
auto ub = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCore = distance(closed.begin(), ub);
int nclosed = closed.size();
for (int i = indCore; i<nclosed; i++) {
for (int j = indCore; j<i; j++) {
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArrayCAS(closed[i], closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closed[i] % 2;
int b = 2 * orbIndices[2 * index + 1] + closed[j] % 2;
if (!(d.getocc(a) || d.getocc(b))) {
work.appendValue(0.0, closed[i] * 2 * norbs + a,
closed[j] * 2 * norbs + b, integrals[index]);
}
}
}
}
}
//---From excitation class 1 (0 holes in core, 1 particle in virtuals) into the CAS------------
void generateAllScreenedSingleExcitationsCAS_0h1p(const Determinant& d,
const double& THRESH,
const double& TINY,
workingArray& work,
const int& i,
bool doparity) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
auto ub = upper_bound(open.begin(), open.end(), 2*first_virtual - 1);
int indAct = distance(open.begin(), ub);
for (int a = 0; a < indAct; a++) {
if (i % 2 == open[a] % 2 &&
abs(I2hb.Singles(i, open[a])) > THRESH)
{
const double tia = d.Hij_1ExciteScreened(open[a], i, I2hb,
TINY, doparity);
if (abs(tia) > THRESH) {
work.appendValue(0., i*2*norbs+open[a], 0, tia);
}
}
}
}
//---From excitation class 1 (0 holes in core, 1 particle in virtuals) into the CAS------------
void generateAllScreenedDoubleExcitationsCAS_0h1p(const Determinant& d,
const double& THRESH,
workingArray& work,
const int& i) {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
auto ub = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCore = distance(closed.begin(), ub);
int nclosed = closed.size();
for (int n=indCore; n < nclosed-1; n++) {
int j = closed[n];
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hb.getIntegralArrayCAS(i, j, integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + i % 2;
int b = 2 * orbIndices[2 * index + 1] + j % 2;
if (!(d.getocc(a) || d.getocc(b))) {
work.appendValue(0.0, i * 2 * norbs + a, j * 2 * norbs + b, integrals[index]);
}
}
}
}
//---From excitation class 2 (0 holes in core, 2 particles in virtuals) into the CAS------------
void generateAllScreenedExcitationsCAS_0h2p(const Determinant& d,
const double& THRESH,
workingArray& work,
const int& iExc, const int& jExc) {
int norbs = Determinant::norbs;
int i = max(iExc, jExc), j = min(iExc, jExc);
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArrayCAS(i, j, integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// if we are going below the criterion, break
//if (fabs(integrals[index]) < THRESH)
// break;
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + i % 2;
int b = 2 * orbIndices[2 * index + 1] + j % 2;
//if ((!(d.getocc(a) || d.getocc(b))) && (a < 2*schd.numActive) && (b < 2*schd.numActive)) {//uncomment for VMC active space calculations
if (!(d.getocc(a) || d.getocc(b))) {
//cout << "a " << a << " b " << b << endl;
work.appendValue(0.0, i * 2 * norbs + a, j * 2 * norbs + b, integrals[index]);
}
}
}
//---From excitation class 3 (1 hole in core, 0 particles in virtuals) into the CAS------------
void generateAllScreenedSingleExcitationsCAS_1h0p(const Determinant& d,
const double& THRESH,
const double& TINY,
workingArray& work,
const int& a,
bool doparity) {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
auto ub = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCore = distance(closed.begin(), ub);
for (int i = indCore; i < closed.size(); i++) {
if (a % 2 == closed[i] % 2 &&
abs(I2hb.Singles(closed[i], a)) > THRESH)
{
const double tia = d.Hij_1ExciteScreened(closed[i], a, I2hb, TINY, doparity);
if (abs(tia) > THRESH) {
work.appendValue(0., closed[i]*2*norbs+a, 0, tia);
}
}
}
}
//---From excitation class 3 (1 hole in core, 0 particles in virtuals) into the CAS------------
void generateAllScreenedDoubleExcitationsCAS_1h0p(const Determinant& d,
const double& THRESH,
workingArray& work,
const int& a) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
auto ub = upper_bound(open.begin(), open.end(), 2*first_virtual - 1);
int indAct = distance(open.begin(), ub);
int nclosed = closed.size();
for (int n = 1; n < indAct; n++) {
int b = open[n];
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hb.getIntegralArrayCAS(b, a, integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// generate the determinant corresponding to the current excitation
int i = 2 * orbIndices[2 * index] + b % 2;
int j = 2 * orbIndices[2 * index + 1] + a % 2;
if (d.getocc(i) && d.getocc(j)) {
//cout << "a " << a << " b " << b << endl;
work.appendValue(0.0, i * 2 * norbs + b, j * 2 * norbs + a, integrals[index]);
}
}
}
}
//---From excitation class 4 (1 hole in core, 1 particle in virtuals) into the CAS------------
void generateAllScreenedSingleExcitationsCAS_1h1p(const Determinant& d,
const double& THRESH,
const double& TINY,
workingArray& work,
const int& i, const int& a,
bool doparity) {
int norbs = Determinant::norbs;
if (i%2 == a%2 && abs(I2hb.Singles(i, a)) > THRESH)
{
const double tia = d.Hij_1ExciteScreened(i, a, I2hb, TINY, doparity);
if (abs(tia) > THRESH) {
work.appendValue(0., i*2*norbs+a, 0, tia);
}
}
}
//---From excitation class 4 (1 hole in core, 1 particle in virtuals) into the CAS------------
// TODO: Remove when all debugging has been done
//void generateAllScreenedDoubleExcitationsCAS_1h1p(const Determinant& d,
// const double& THRESH,
// workingArray& work,
// const int& i, const int& a) {
// int norbs = Determinant::norbs;
// int max_act_ind = 2*(schd.nciCore + schd.nciAct) - 1;
//
// vector<int> closed;
// vector<int> open;
// d.getOpenClosed(open, closed);
//
// auto ub = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
// int indCore = distance(closed.begin(), ub);
//
// int nclosed = closed.size();
// for (int n=indCore; n < nclosed-1; n++) {
// int j = closed[n];
//
// const float *integrals; const short* orbIndices;
// size_t numIntegrals;
// //I2hb.getIntegralArrayCAS(i, j, integrals, orbIndices, numIntegrals);
// I2hb.getIntegralArray(i, j, integrals, orbIndices, numIntegrals);
// size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
//
// // for all HCI integrals
// for (size_t index = 0; index < numLargeIntegrals; index++)
// {
// // otherwise: generate the determinant corresponding to the current excitation
// int a_new = 2 * orbIndices[2 * index] + i % 2;
// int b_new = 2 * orbIndices[2 * index + 1] + j % 2;
//
// if (a_new > max_act_ind || b_new > max_act_ind) continue;
//
// if (a_new == a || b_new == a) {
// if (!(d.getocc(a_new) || d.getocc(b_new))) {
// //cout << i << " " << j << " " << a_new << " " << b_new << " " << integrals[index] << endl;
// work.appendValue(0.0, i * 2 * norbs + a_new, j * 2 * norbs + b_new, integrals[index]);
// }
// }
//
// }
// }
//}
//---From excitation class 4 (1 hole in core, 1 particle in virtuals) into the CAS------------
// An alternative implementation of this function for testing purposes
void generateAllScreenedDoubleExcitationsCAS_1h1p(const Determinant& d,
const double& THRESH,
workingArray& work,
const int& i, const int& aExc) {
//const int& iExc, const int& aExc) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
double integral;
int j, a, b, b_temp;
auto ub_1 = upper_bound(open.begin(), open.end(), 2*first_virtual - 1);
int indActOpen = distance(open.begin(), ub_1);
auto ub_2 = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCoreClosed = distance(closed.begin(), ub_2);
for (int n = indCoreClosed; n < closed.size()-1; n++) {
for (int m = 1; m < indActOpen; m++) {
//i = max(iExc, closed[n]), j = min(iExc, closed[n]);
j = closed[n];
b_temp = open[m];
if (i%2 == aExc%2 && j%2 == b_temp%2) {
a = aExc;
b = b_temp;
}
else if (i%2 == b_temp%2 && j%2 == aExc%2) {
a = b_temp;
b = aExc;
}
else {
continue;
}
if (i%2 == j%2) {
// same spin
integral = I2(i, a, j, b) - I2(i, b, j, a);
}
else {
// opposite spin
integral = I2(i, a, j, b);
}
if (fabs(integral) > THRESH) {
work.appendValue(0.0, i * 2 * norbs + a, j * 2 * norbs + b, integral);
}
}
}
}
//---From excitation class 5 (1 hole in core, 2 particles in virtuals) into the CAS------------
void generateAllScreenedExcitationsCAS_1h2p(const Determinant& d,
const double& THRESH,
workingArray& work,
const int& iExc, const int& jExc,
const int& a) {
int norbs = Determinant::norbs;
int max_act_ind = 2*(schd.nciCore + schd.nciAct) - 1;
int i = max(iExc, jExc), j = min(iExc, jExc);
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArray(i, j, integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// otherwise: generate the determinant corresponding to the current excitation
int a_new = 2 * orbIndices[2 * index] + i % 2;
int b_new = 2 * orbIndices[2 * index + 1] + j % 2;
if (a_new > max_act_ind || b_new > max_act_ind) continue;
if (a_new == a || b_new == a) {
if (!(d.getocc(a_new) || d.getocc(b_new))) {
//cout << "a " << a << " b " << b << endl;
work.appendValue(0.0, i * 2 * norbs + a_new, j * 2 * norbs + b_new, integrals[index]);
}
}
}
}
//---From excitation class 5 (1 hole in core, 2 particles in virtuals) into the CAS------------
// An alternative implementation of this function for testing purposes
// TODO: Remove when all debugging has been done
//void generateAllScreenedExcitationsCAS_1h2p(const Determinant& d,
// const double& THRESH,
// workingArray& work,
// const int& iExc, const int& jExc,
// const int& aExc) {
// int norbs = Determinant::norbs;
// int first_virtual = schd.nciCore + schd.nciAct;
//
// vector<int> closed;
// vector<int> open;
// d.getOpenClosed(open, closed);
//
// double integral;
// int a, b, b_temp;
//
// int i = max(iExc, jExc), j = min(iExc, jExc);
//
// auto ub = upper_bound(open.begin(), open.end(), 2*first_virtual - 1);
// int indAct = distance(open.begin(), ub);
//
// for (int m = 0; m < indAct; m++) {
// b_temp = open[m];
//
// if (i%2 == aExc%2 && j%2 == b_temp%2) {
// a = aExc;
// b = b_temp;
// }
// else if (i%2 == b_temp%2 && j%2 == aExc%2) {
// a = b_temp;
// b = aExc;
// }
// else {
// continue;
// }
//
// if (i%2 == j%2) {
// // same spin
// integral = I2(i, a, j, b) - I2(i, b, j, a);
// }
// else {
// // opposite spin
// integral = I2(i, a, j, b);
// }
//
// if (fabs(integral) > THRESH) {
// //cout << i << " " << j << " " << a << " " << b << " " << integral << endl;
// work.appendValue(0.0, i * 2 * norbs + a, j * 2 * norbs + b, integral);
// }
// }
//}
//---From excitation class 6 (2 holes in core, 0 particles in virtuals) into the CAS------------
void generateAllScreenedExcitationsCAS_2h0p(const Determinant& d,
const double& THRESH,
workingArray& work,
const int& aExc, const int& bExc) {
int norbs = Determinant::norbs;
int a = max(aExc, bExc), b = min(aExc, bExc);
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArrayCAS(a, b, integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// otherwise: generate the determinant corresponding to the current excitation
int i = 2 * orbIndices[2 * index] + a % 2;
int j = 2 * orbIndices[2 * index + 1] + b % 2;
if (d.getocc(i) && d.getocc(j)) {
//cout << "a " << a << " b " << b << endl;
work.appendValue(0.0, i * 2 * norbs + a, j * 2 * norbs + b, integrals[index]);
}
}
}
//---From excitation class 7 (2 holes in core, 1 particle in virtuals) into the CAS------------
void generateAllScreenedExcitationsCAS_2h1p(const Determinant& d,
const double& THRESH,
workingArray& work,
const int& i,
const int& aExc, const int& bExc) {
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
double integral;
int j, a, b;
int nclosed = closed.size();
auto ub = upper_bound(closed.begin(), closed.end(), 2*schd.nciCore - 1);
int indCore = distance(closed.begin(), ub);
for (int n = indCore; n < nclosed-1; n++) {
j = closed[n];
if (i%2 == aExc%2 && j%2 == bExc%2) {
a = aExc;
b = bExc;
}
else if (i%2 == bExc%2 && j%2 == aExc%2) {
a = bExc;
b = aExc;
}
else {
continue;
}
if (i%2 == j%2) {
// same spin
integral = I2(i, a, j, b) - I2(i, b, j, a);
}
else {
// opposite spin
integral = I2(i, a, j, b);
}
if (fabs(integral) > THRESH) {
//cout << i << " " << j << " " << a << " " << b << " " << integral << endl;
work.appendValue(0.0, i * 2 * norbs + a, j * 2 * norbs + b, integral);
}
}
}
//---From excitation class 7 (2 holes in core, 1 particle in virtuals) into the CAS------------
// An alternative implementation of this function for testing purposes
// TODO: Remove when all debugging has been done
//void generateAllScreenedExcitationsCAS_2h1p(const Determinant& d,
// const double& THRESH,
// workingArray& work,
// const int& i,
// const int& aExc, const int& bExc) {
// int norbs = Determinant::norbs;
// int max_core_ind = 2*schd.nciCore - 1;
//
// int a = max(aExc, bExc), b = min(aExc, bExc);
// const float *integrals; const short* orbIndices;
// size_t numIntegrals;
// I2hbCAS.getIntegralArray(a, b, integrals, orbIndices, numIntegrals);
// size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, THRESH, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
//
// int j_temp, b_temp;
//
// // for all HCI integrals
// for (size_t index = 0; index < numLargeIntegrals; index++)
// {
// // otherwise: generate the determinant corresponding to the current excitation
// int i_new = 2 * orbIndices[2 * index] + a % 2;
// int j_new = 2 * orbIndices[2 * index + 1] + b % 2;
//
// if (i_new <= max_core_ind || j_new <= max_core_ind) continue;
//
// if (i_new == i || j_new == i) {
//
// //if (i_new < j_new) {
// // j_temp = j_new;
// // j_new = i_new;
// // i_new = j_temp;
//
// // b_temp = b;
// // b = a;
// // a = b_temp;
// //}
//
// if (d.getocc(i_new) && d.getocc(j_new)) {
// cout << i_new << " " << j_new << " " << a << " " << b << " " << integrals[index] << endl;
// work.appendValue(0.0, i_new * 2 * norbs + a, j_new * 2 * norbs + b, integrals[index]);
// }
// }
// }
//
//}
//---From excitation class 8 (2 holes in core, 2 particles in virtuals) into the CAS------------
void generateAllScreenedExcitationsCAS_2h2p(const double& THRESH,
workingArray& work,
const int& iExc, const int& jExc,
const int& aExc, const int& bExc) {
int norbs = Determinant::norbs;
int i = max(iExc, jExc), j = min(iExc, jExc);
int a, b;
if (i%2 == aExc%2 && j%2 == bExc%2) {
a = aExc;
b = bExc;
}
else if (i%2 == bExc%2 && j%2 == aExc%2) {
a = bExc;
b = aExc;
}
else {
return;
}
double integral;
if (i%2 == j%2) {
// same spin
integral = I2(i, a, j, b) - I2(i, b, j, a);
}
else {
// opposite spin
integral = I2(i, a, j, b);
}
if (fabs(integral) > THRESH) {
work.appendValue(0.0, i * 2 * norbs + a, j * 2 * norbs + b, integral);
}
}
bool applyExcitation(int a, int b, int k, int l, Determinant& dcopy) {
bool valid = true;
if (dcopy.getocc(l) == true)
dcopy.setocc(l, false);
else
return false;
if (dcopy.getocc(b) == false)
dcopy.setocc(b, true);
else
return false;
if (dcopy.getocc(k) == true)
dcopy.setocc(k, false);
else
return false;
if (dcopy.getocc(a) == false)
dcopy.setocc(a, true);
else
return false;
return valid;
}
//generate all the alpha or beta strings
void comb(int N, int K, vector<vector<int>> &combinations)
{
std::vector<int> bitmask(K, 1);
bitmask.resize(N, 0); // N-K trailing 0's
// print integers and permute bitmask
int index = 0;
do
{
vector<int> comb;
for (int i = 0; i < N; ++i) // [0..N-1] integers
{
if (bitmask[i] == 1)
comb.push_back(i);
}
combinations.push_back(comb);
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
void generateAllDeterminants(vector<Determinant>& allDets, int norbs, int nalpha, int nbeta) {
vector<vector<int>> alphaDets, betaDets;
comb(norbs, nalpha, alphaDets);
comb(norbs, nbeta, betaDets);
for (int a = 0; a < alphaDets.size(); a++)
for (int b = 0; b < betaDets.size(); b++)
{
Determinant d;
for (int i = 0; i < alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i], true);
for (int i = 0; i < betaDets[b].size(); i++)
d.setoccB(betaDets[b][i], true);
allDets.push_back(d);
}
alphaDets.clear();
betaDets.clear();
}
void generateAllDeterminantsActive(vector<Determinant>& allDets, const Determinant dExternal,
const int ncore, const int nact, const int nalpha, const int nbeta)
{
vector<vector<int>> alphaDets, betaDets;
comb(nact, nalpha, alphaDets);
comb(nact, nbeta, betaDets);
for (int a = 0; a < alphaDets.size(); a++)
for (int b = 0; b < betaDets.size(); b++)
{
// dExternal holds the core and virtual orbitals
Determinant d(dExternal);
for (int i = 0; i < alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i]+ncore, true);
for (int i = 0; i < betaDets[b].size(); i++)
d.setoccB(betaDets[b][i]+ncore, true);
allDets.push_back(d);
}
alphaDets.clear();
betaDets.clear();
}
// Useful when doing an MRCI/MRPT calculation. This routine only generates
// determinants within the first-order interacting space of the chosen
// CAS, using schd.nciCore and schd.nciAct
void generateAllDeterminantsFOIS(vector<Determinant>& allDets, int norbs, int nalpha, int nbeta) {
vector<vector<int>> alphaDets, betaDets;
vector<int> nBetaHoles, nBetaParts;
vector<int> nAlphaHoles, nAlphaParts;
int nHoles, nParts;
// generate the alpha and beta strings
comb(norbs, nalpha, alphaDets);
comb(norbs, nbeta, betaDets);
// find the number of holes and particles in the core and virtual
// orbitals, respectively
for (int a = 0; a < alphaDets.size(); a++) {
nAlphaHoles.push_back(schd.nciCore);
nAlphaParts.push_back(0);
for (int i = 0; i < alphaDets[a].size(); i++) {
if (alphaDets[a][i] < schd.nciCore) nAlphaHoles[a] -= 1;
if (alphaDets[a][i] >= schd.nciCore + schd.nciAct) nAlphaParts[a] += 1;
}
}
for (int b = 0; b < betaDets.size(); b++) {
nBetaHoles.push_back(schd.nciCore);
nBetaParts.push_back(0);
for (int i = 0; i < betaDets[b].size(); i++) {
if (betaDets[b][i] < schd.nciCore) nBetaHoles[b] -= 1;
if (betaDets[b][i] >= schd.nciCore + schd.nciAct) nBetaParts[b] += 1;
}
}
// construct the determinants
int counter = 0;
for (int a = 0; a < alphaDets.size(); a++)
for (int b = 0; b < betaDets.size(); b++)
{
nHoles = nAlphaHoles[a] + nBetaHoles[b];
nParts = nAlphaParts[a] + nBetaParts[b];
// this is the condition for the determinant to be in the FOIS
if (nHoles <= 2 && nParts <= 2) {
Determinant d;
for (int i = 0; i < alphaDets[a].size(); i++)
d.setoccA(alphaDets[a][i], true);
for (int i = 0; i < betaDets[b].size(); i++)
d.setoccB(betaDets[b][i], true);
allDets.push_back(d);
counter += 1;
}
}
nAlphaHoles.clear();
nAlphaParts.clear();
nBetaHoles.clear();
nBetaParts.clear();
alphaDets.clear();
betaDets.clear();
}
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SelectedCI_HEADER_H
#define SelectedCI_HEADER_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include "SimpleWalker.h"
//#include <google/dense_hash_map>
#include <sparsehash/dense_hash_map>
class SelectedCI
{
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
//ar & DetsMap & bestDeterminant;
ar & bestDeterminant;
}
public:
using CorrType = Determinant;
using ReferenceType = Determinant;
google::dense_hash_map<shortSimpleDet, double, boost::hash<shortSimpleDet> > DetsMap;
//unordered_map<Determinant, double, boost::hash<Determinant> > DetsMap;
Determinant bestDeterminant;
SelectedCI();
void readWave();
void initWalker(SimpleWalker &walk);
void initWalker(SimpleWalker &walk, Determinant& d);
double getOverlapFactor(SimpleWalker& walk, Determinant& dcopy, bool doparity=true) ;
double getOverlapFactor(int I, int A, SimpleWalker& walk, bool doparity);
double Overlap(SimpleWalker& walk);
double Overlap(Determinant& d);
inline double Overlap(shortSimpleDet& d);
double getOverlapFactor(int I, int J, int A, int B,
SimpleWalker& walk, bool doparity);
void OverlapWithGradient(SimpleWalker &walk,
double &factor,
Eigen::VectorXd &grad);
// This version of HamAndOvlp is the standard version, appropriate when
// performing VMC in the usual way, using a SelectedCI wave function.
// This function calculations both ovlp and ham. ovlp is the overlap of
// walk.d with the selected CI wave function. ham is the local energy
// on determinant walk.d, including the 1/ovlp factor.
void HamAndOvlp(SimpleWalker &walk, double &ovlp, double &ham,
workingArray& work, double epsilon);
void HamAndOvlpAndSVTotal(SimpleWalker &walk, double &ovlp,
double &ham, double& SVTotal,
workingArray& work, double epsilon);
// This version of HamAndOvlp is used for MRCI and NEVPT calculations,
// where excitations occur into the first-order interacting space, but
// the selected CI wave function only has non-zero coefficients
// within the complete active space.
// *IMPORTANT* - ham here is <n|H|phi0>, *not* the ratio, to avoid out
// of active space singularitites. Also, ovlp = ham when ham is calculated.
void HamAndOvlp(SimpleWalker &walk, double &ovlp, double &ham,
workingArray& work, bool dontCalcEnergy=true);
void HamAndOvlpLanczos(SimpleWalker &walk,
Eigen::VectorXd &lanczosCoeffsSample,
double &ovlpSample,
workingArray& work,
workingArray& moreWork, double &alpha) ;
// For some situation, such as FCIQMC, we want to know the ratio of
// overlaps with the correct parity. This function will calculate
// this parity, relative to what is returned by getOverlapFactor.
// For a SelectedCI wave function, this is always equal to 1.
double parityFactor(Determinant& d, const int ex2, const int i,
const int j, const int a, const int b) const {
return 1.0;
}
//void getVariables(Eigen::VectorXd &v);
//long getNumVariables();
//void updateVariables(Eigen::VectorXd &v);
//void printVariables();
Determinant& getRef() { return bestDeterminant; } //no ref and corr for selectedCI, defined to work with other wavefunctions
Determinant& getCorr() { return bestDeterminant; }
std::string getfileName() const { return "SelectedCI"; }
};
#endif
<file_sep>import numpy as np
from pyscf import gto, scf, ao2mo, tools, fci
from pyscf.lo import pipek
from scipy.linalg import fractional_matrix_power
nsites = 4
norb = 4
sqrt2 = 2**0.5
mol = gto.M(atom = 'H 0 0 0; H 1 0 0; H 2 0 0; H 3 0 0', basis = 'sto-3g')
mf = scf.RHF(mol)
print mf.kernel()
lmo = fractional_matrix_power(mf.get_ovlp(mol), -0.5).T
#lmo = pipek.PM(mol).kernel(mf.mo_coeff)
h1 = lmo.T.dot(mf.get_hcore()).dot(lmo)
eri = ao2mo.kernel(mol, lmo)
tools.fcidump.from_integrals('FCIDUMP', h1, eri, 4, 4, mf.energy_nuc())
print mf.mo_coeff
print 'local'
print lmo
cisolver = fci.direct_spin1.FCI(mol)
e, ci = cisolver.kernel(h1, eri, h1.shape[1], mol.nelec, ecore=mol.energy_nuc())
print e
print ci.T.flatten()
ovlp = mf.get_ovlp(mol)
gmf = scf.GHF(mol)
gmf.max_cycle = 200
dm = gmf.get_init_guess()
print dm.shape
dm = dm + np.random.rand(2*norb, 2*norb) / 3
print gmf.kernel(dm0 = dm)
uc1 = (gmf.mo_coeff[:norb, :norb].T.dot(ovlp).dot(lmo)).T
uc2 = (gmf.mo_coeff[:norb, norb:].T.dot(ovlp).dot(lmo)).T
uc3 = (gmf.mo_coeff[norb:, :norb].T.dot(ovlp).dot(lmo)).T
uc4 = (gmf.mo_coeff[norb:, norb:].T.dot(ovlp).dot(lmo)).T
fileHF = open("ghf.txt", 'w')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(uc1[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(uc2[i,j]))
fileHF.write('\n')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(uc3[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(uc4[i,j]))
fileHF.write('\n')
fileHF.close()
<file_sep>#ifndef fnn_HEADER_H
#define fnn_HEADER_H
#include <iostream>
#include <fstream>
#include <vector>
#include <functional>
#include <algorithm>
//#define EIGEN_USE_MKL_ALL
#include <Eigen/Dense>
#include <boost/serialization/serialization.hpp>
using namespace std;
using namespace Eigen;
class fnn
{ // feed forward neural network
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & numLayers
& sizes
& weights
& biases;
}
public:
int numLayers;
vector<int> sizes; // number of neurons in each layer
vector<MatrixXd> weights;
vector<VectorXd> biases;
// constructor
fnn() {};
fnn(vector<int> pSizes) {
numLayers = pSizes.size();
sizes = pSizes;
for (int i = 1; i < numLayers; i++) {
weights.push_back(MatrixXd::Random(sizes[i], sizes[i - 1])/pow(sizes[i - 1]*sizes[i], 0.5));
biases.push_back(VectorXd::Random(sizes[i]));
}
}
// constructor
fnn(vector<int> pSizes, vector<MatrixXd>& pWeights, vector<VectorXd>& pBiases) {
numLayers = pSizes.size();
sizes = pSizes;
weights = pWeights;
biases = pBiases;
}
// number of variables : weights and biases
size_t getNumVariables() const {
size_t num = 0;
for (int i = 1; i < numLayers; i++) num += sizes[i - 1] * sizes[i] + sizes[i];
return num;
}
// all weights followed by all biases
void getVariables(VectorXd& vars) const {
vars = VectorXd::Zero(getNumVariables());
size_t counter = 0;
// weights
for (int n = 0; n < numLayers - 1; n++) {
for (int j = 0; j < sizes[n]; j++) {
for (int i = 0; i < sizes[n + 1]; i++) {
vars[counter] = weights[n](i, j);
counter++;
}
}
}
// biases
for (int n = 0; n < numLayers - 1; n++) {
for (int i = 0; i < sizes[n + 1]; i++) {
vars[counter] = biases[n](i);
counter++;
}
}
}
// all weights followed by all biases
void updateVariables(const VectorXd& vars) {
size_t counter = 0;
// weights
for (int n = 0; n < numLayers - 1; n++) {
for (int j = 0; j < sizes[n]; j++) {
for (int i = 0; i < sizes[n + 1]; i++) {
weights[n](i, j) = vars[counter];
counter++;
}
}
}
// biases
for (int n = 0; n < numLayers - 1; n++) {
for (int i = 0; i < sizes[n + 1]; i++) {
biases[n](i) = vars[counter];
counter++;
}
}
}
// activation function
static double activation(double input) {
// ramp
return (input > 0) ? input : 0.;
}
// derivative of activation function
static double dactivation(double input) {
// ramp
return (input > 0) ? 1. : 0.;
}
// forward propagation
void feedForward(const VectorXd& input, VectorXd& output) const {
output = input;
for (int i = 0; i < numLayers - 1; i++)
output = (weights[i] * output + biases[i]).unaryExpr(std::ref(activation));
}
// evaluate the nn for given input and cost function
double evaluate(const VectorXd& input, std::function<double(VectorXd&)> cost) const {
VectorXd output;
feedForward(input, output);
return cost(output);
}
// gradient evaluation
void backPropagate(const VectorXd& input, std::function<void(VectorXd&, VectorXd&)> costGradient, VectorXd& grad) const {
// forward
vector<VectorXd> zVecs, aVecs; // intermediates created during feedforward
zVecs.push_back(input);
aVecs.push_back(input);
for (int i = 0; i < numLayers - 1; i++) {
VectorXd zVec = weights[i] * aVecs[i] + biases[i];
zVecs.push_back(zVec);
VectorXd aVec = (zVec).unaryExpr(std::ref(activation));
aVecs.push_back(aVec);
}
// backward
vector<MatrixXd> weightDerivatives;
vector<VectorXd> biasDerivatives;
VectorXd costGradVec;
costGradient(aVecs[numLayers - 1], costGradVec);
VectorXd delta = costGradVec.cwiseProduct((zVecs[numLayers - 1]).unaryExpr(std::ref(dactivation)));
// these are built in reverse order
biasDerivatives.push_back(delta);
weightDerivatives.push_back(delta * aVecs[numLayers - 2].transpose());
for (int i = 2; i < numLayers; i++) { // l = numLayers - i - 1
delta = (weights[numLayers - i].transpose() * delta).cwiseProduct((zVecs[numLayers - i]).unaryExpr(std::ref(dactivation)));
biasDerivatives.push_back(delta);
weightDerivatives.push_back(delta * aVecs[numLayers - i - 1].transpose());
}
// reversing to correct order
reverse(biasDerivatives.begin(), biasDerivatives.end());
reverse(weightDerivatives.begin(), weightDerivatives.end());
// flattening into grad vector
grad = VectorXd::Zero(getNumVariables());
size_t counter = 0;
// weights
for (int n = 0; n < numLayers - 1; n++) {
for (int j = 0; j < sizes[n]; j++) {
for (int i = 0; i < sizes[n + 1]; i++) {
grad[counter] = weightDerivatives[n](i, j);
counter++;
}
}
}
// biases
for (int n = 0; n < numLayers - 1; n++) {
for (int i = 0; i < sizes[n + 1]; i++) {
grad[counter] = biasDerivatives[n](i);
counter++;
}
}
}
// print for debugging
friend ostream& operator<<(ostream& os, const fnn& nn) {
os << "numLayers " << nn.numLayers << endl;
os << "sizes ";
for (int i : nn.sizes) os << i << " ";
os << endl << endl;
os << "weights\n\n";
for (MatrixXd i : nn.weights) os << i << endl << endl;
os << "biases\n\n";
for (MatrixXd i : nn.biases) os << i << endl << endl;
return os;
}
};
#endif
<file_sep>#include "CalculateSphHarmonics.h"
#include <Eigen/Dense>
#include <boost/math/special_functions/spherical_harmonic.hpp>
#include "pythonInterface.h"
#include <boost/math/interpolators/cubic_b_spline.hpp>
#include <stdio.h>
#include <pvfmm.hpp>
#include <ctime>
#include <boost/math/quadrature/gauss.hpp>
#include "mkl.h"
//#### LIBCINT VARIABLES ######
int *shls, *ao_loc, *atm, *bas;
int natm, nbas, ncalls;
double *env, *dm, *centroid, coordScale;
std::vector<char> non0tab;
int BLKSIZE;
std::vector<double> aovals, intermediate, grid_fformat;
//#FMM TREE
pvfmm::ChebFMM_Tree<double>* tree;
vector<double> LegCoord, LegWts;
vector<double> AoValsAtLegCoord;
vector<double> ChebCoord;
vector<double> AoValsAtChebCoord;
vector<double> density;
//#### BECKE GRID VARIABLES ######
vector<RawDataOnGrid> densityYlm;
vector<RawDataOnGrid> potentialYlm;
vector<SplineFit> splinePotential;
MatrixXdR RawDataOnGrid::lebdevgrid;
MatrixXd RawDataOnGrid::SphericalCoords;
MatrixXd RawDataOnGrid::sphVals;
MatrixXd RawDataOnGrid::WeightedSphVals;
VectorXd RawDataOnGrid::densityStore;
int RawDataOnGrid::lmax;
vector<int> RawDataOnGrid::lebdevGridSize{ 1, 6, 14, 26, 38, 50, 74, 86, 110, 146, 170,
194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030,
2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810 };
void init(int* pshls, int *pao_loc, int *patm, int pnatm,
int *pbas, int pnbas, double *penv) {
BLKSIZE = 128;
shls = pshls;
ao_loc = pao_loc;
atm = patm;
natm = pnatm;
bas = pbas;
nbas = pnbas;
env = penv;
}
void getBeckePartition(double* coords, int ngrids, double* pbecke) {
vector<double> fcoord(ngrids*3);
vector<double> atmCoord(natm*3);
for (int i=0; i<ngrids; i++) {
fcoord[0*ngrids+i] = coords[i*3+0];
fcoord[1*ngrids+i] = coords[i*3+1];
fcoord[2*ngrids+i] = coords[i*3+2];
}
for (int i=0; i<natm; i++) {
atmCoord[3*i+0] = env[atm[6*i+1] + 0];
atmCoord[3*i+1] = env[atm[6*i+1] + 1];
atmCoord[3*i+2] = env[atm[6*i+1] + 2];
}
VXCgen_grid(pbecke, &fcoord[0], &atmCoord[0], NULL, natm, ngrids);
}
void initAtomGrids() {
int natom = natm;
densityYlm.resize(natom);
potentialYlm.resize(natom);
splinePotential.resize(natom);
for (int i=0; i<natom; i++) {
densityYlm[i].coord(0) = env[atm[6*i+1] + 0];
densityYlm[i].coord(1) = env[atm[6*i+1] + 1];
densityYlm[i].coord(2) = env[atm[6*i+1] + 2];
potentialYlm[i].coord = densityYlm[i].coord;
splinePotential[i].coord = densityYlm[i].coord;
}
}
void initAngularData(int lmax, int lebdevOrder){
RawDataOnGrid::InitStaticVariables(lmax, lebdevOrder);
}
void initDensityRadialGrid(int ia, int rmax, double rm) {
densityYlm[ia].InitRadialGrids(rmax, rm);
}
void fitDensity(int ia, int rindex) {
int GridSize = RawDataOnGrid::lebdevgrid.rows();
MatrixXdR grid(GridSize, 3);
grid = RawDataOnGrid::lebdevgrid.block(0,0,GridSize, 3) * densityYlm[ia].radialGrid(rindex);
for (int i=0; i<grid.rows(); i++) {
grid(i,0) += densityYlm[ia].coord(0);
grid(i,1) += densityYlm[ia].coord(1);
grid(i,2) += densityYlm[ia].coord(2);
}
vector<double> density(GridSize, 0.0), becke(natm*GridSize, 0.0), beckenorm(GridSize,0.0);
getValuesAtGrid(&grid(0,0), GridSize, &density[0]);
getBeckePartition(&grid(0,0), GridSize, &becke[0]);
for (int i = 0; i<GridSize; i++) {
for (int a =0; a<natm; a++)
beckenorm[i] += becke[a * GridSize + i];
}
for (int i = 0; i<GridSize; i++) {
density[i] *= becke[ia*GridSize + i]/beckenorm[i];
}
densityYlm[ia].fit(rindex, &density[0]);
}
//void getDensityOnLebdevGridAtGivenR(int rindex, double* densityOut) {
//densityYlm.getValue(rindex, densityOut);
//}
void solvePoissonsEquation(int ia) {
double totalQ = densityYlm[ia].wts.dot(densityYlm[ia].GridValues * densityYlm[ia].lebdevgrid.col(3));
potentialYlm[ia] = densityYlm[ia];
int nr = densityYlm[ia].radialGrid.size();
double h = 1./(1.*nr+1.), rm = densityYlm[ia].rm;
VectorXd drdz(nr), d2rdz2(nr), b(nr);
VectorXd& z = densityYlm[ia].zgrid, &r = densityYlm[ia].radialGrid;
for (int i=0; i<nr; i++) {
drdz(i) = (-2.*M_PI * rm * sin(M_PI * z(i))) / pow(1. - cos(M_PI * z(i)), 2);
d2rdz2(i) = ( 2.* M_PI * M_PI * rm) *
(2 * pow(sin(M_PI * z(i)), 2.) + pow(cos(M_PI * z(i)), 2) - cos(M_PI * z(i)))
/ pow(1. - cos(M_PI * z(i)), 3);
}
MatrixXd A1Der(nr, nr), A2Der(nr, nr), A(nr, nr);
A1Der.setZero(); A2Der.setZero(); A.setZero();
A2Der.block(0,0,1,6) << -147., -255., 470., -285., 93., -13.;
A1Der.block(0,0,1,6) << -77., 150., -100., 50., -15., 2.;
A2Der.block(1,0,1,6) << 228., -420., 200., 15., -12., 2.;
A1Der.block(1,0,1,6) << -24., -35., 80., -30., 8., -1.;
A2Der.block(2,0,1,6) << -27., 270., -490., 270., -27., 2.;
A1Der.block(2,0,1,6) << 9., -45., 0., 45., -9., 1.;
for (int i=3; i<nr-3; i++) {
A2Der.block(i,i-3,1,7) << 2., -27., 270., -490., 270., -27., 2.;
A1Der.block(i,i-3,1,7) << -1., 9., -45., 0., 45., -9., 1.;
}
A2Der.block(nr-1, nr-6, 1, 6) << -13., 93., -285., 470.,-255.,-147.;
A1Der.block(nr-1, nr-6, 1, 6) << -2., 15., -50., 100.,-150., 77.;
A2Der.block(nr-2, nr-6, 1, 6) << 2., -12., 15., 200.,-420., 228.;
A1Der.block(nr-2, nr-6, 1, 6) << 1., -8., 30., -80., 35., 24.;
A2Der.block(nr-3, nr-6, 1, 6) << 2., -27., 270., -490., 270., -27.;
A1Der.block(nr-3, nr-6, 1, 6) << -1., 9., -45., 0., 45., -9.;
int lmax = densityYlm[ia].lmax;
for (int l = 0; l < lmax; l++) {
for (int m = -l; m < l+1; m++) {
int lm = l * l + (l + m);
b = -4 * M_PI * r.cwiseProduct(densityYlm[ia].CoeffsYlm.col(lm));
if (l == 0) {
b(0) += sqrt(4 * M_PI) * (-137. / (180. * h * h)/(drdz(0) * drdz(0))) * totalQ;
b(1) += sqrt(4 * M_PI) * ( 13. / (180. * h * h)/(drdz(1) * drdz(1))) * totalQ;
b(2) += sqrt(4 * M_PI) * ( -2. / (180. * h * h)/(drdz(2) * drdz(2))) * totalQ;
b(0) += sqrt(4 * M_PI) * ( 10. / (60. * h)*(-d2rdz2(0) / pow(drdz(0),3))) * totalQ;
b(1) += sqrt(4 * M_PI) * ( -2. / (60. * h)*(-d2rdz2(1) / pow(drdz(1),3))) * totalQ;
b(2) += sqrt(4 * M_PI) * ( 1. / (60. * h)*(-d2rdz2(2) / pow(drdz(2),3))) * totalQ;
}
for (int i=0; i<nr; i++) {
A.row(i) = A2Der.row(i) / (180. * h * h)/(drdz(i) * drdz(i))
+ A1Der.row(i) / (60 * h) * (-d2rdz2(i) / pow(drdz(i), 3));
A(i, i) += (-l * (l + 1) / r(i) / r(i));
}
potentialYlm[ia].CoeffsYlm.col(lm) = A.colPivHouseholderQr().solve(b);
}
}
}
void fitSplinePotential(int ia) {
splinePotential[ia].Init(potentialYlm[ia]);
}
void getPotentialBeckeOfAtom(int ia, int ngrid, double* grid, double* potential) {
splinePotential[ia].getPotential(ngrid, grid, potential);
}
void getPotentialBecke(int ngrid, double* grid, double* potential, int lmax,
int* nrad, double* rm, double* pdm) {
coordScale = 1.0;
centroid = new double[3];
centroid[0] = 0.5; centroid[1] = 0.5; centroid[2] = 0.5;
dm = pdm;
int lebedevOrder = 2*lmax + 1;
initAngularData(lmax, lebedevOrder);
initAtomGrids();
for (int ia=0; ia<natm; ia++) {
initDensityRadialGrid(ia, nrad[ia], rm[ia]);
for (int rindex = 0; rindex < nrad[ia] ; rindex++)
fitDensity(ia, rindex);
solvePoissonsEquation(ia);
fitSplinePotential(ia);
getPotentialBeckeOfAtom(ia, ngrid, grid, potential);
}
delete [] centroid;
}
void getAoValuesAtGrid(const double* grid_cformat, int ngrid, double* aovals) {
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
if (grid_fformat.size() < 3*ngrid)
grid_fformat.resize(ngrid*3);
std::fill(&grid_fformat[0], &grid_fformat[0]+3*ngrid, 0.);
for (int i=0; i<ngrid; i++)
for (int j=0; j<3; j++)
grid_fformat[i + j*ngrid] = grid_cformat[j + i*3];
//now you have to scale the basis such that centroid is 0.5
for (int i=0; i<ngrid; i++)
grid_fformat[i] = (grid_fformat[i]-0.5)*coordScale + centroid[0];
for (int i=0; i<ngrid; i++)
grid_fformat[ngrid+i] = (grid_fformat[ngrid+i]-0.5)*coordScale + centroid[1];
for (int i=0; i<ngrid; i++)
grid_fformat[2*ngrid+i] = (grid_fformat[2*ngrid+i]-0.5)*coordScale + centroid[2];
int tabSize = (((ngrid + BLKSIZE-1)/BLKSIZE) * nbas)*10;
if (non0tab.size() < tabSize)
non0tab.resize(tabSize, 1);
GTOval_cart(ngrid, shls, ao_loc, &aovals[0], &grid_fformat[0],
&non0tab[0], atm, natm, bas, nbas, env);
}
//the coords are nx3 matrix in "c" order but libcint requires it to be in
//"f" order
void getValuesAtGrid(const double* grid_cformat, int ngrid, double* out) {
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
if (aovals.size() < nao*ngrid) {
aovals.resize(nao*ngrid, 0.0);
intermediate.resize(nao*ngrid, 0.0);
}
if (grid_fformat.size() < 3*ngrid)
grid_fformat.resize(ngrid*3);
std::fill(&aovals[0], &aovals[0]+nao*ngrid, 0.);
std::fill(out, out+ngrid, 0.);
for (int i=0; i<ngrid; i++)
for (int j=0; j<3; j++)
grid_fformat[i + j*ngrid] = grid_cformat[j + i*3];
//now you have to scale the basis such that centroid is 0.5
for (int i=0; i<ngrid; i++)
grid_fformat[i] = (grid_fformat[i]-0.5)*coordScale + centroid[0];
for (int i=0; i<ngrid; i++)
grid_fformat[ngrid+i] = (grid_fformat[ngrid+i]-0.5)*coordScale + centroid[1];
for (int i=0; i<ngrid; i++)
grid_fformat[2*ngrid+i] = (grid_fformat[2*ngrid+i]-0.5)*coordScale + centroid[2];
int tabSize = (((ngrid + BLKSIZE-1)/BLKSIZE) * nbas)*10;
if (non0tab.size() < tabSize)
non0tab.resize(tabSize, 1);
GTOval_cart(ngrid, shls, ao_loc, &aovals[0], &grid_fformat[0],
&non0tab[0], atm, natm, bas, nbas, env);
char N = 'N', T = 'T'; double alpha = 1.0, beta = 0.0; int LDA = 1, LDB = 1, LDC=1;
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
ngrid, nao, nao, alpha, &aovals[0], ngrid, &dm[0], nao, beta,
&intermediate[0], ngrid);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
out[g] += intermediate[p*ngrid + g] * aovals[p*ngrid + g];
ncalls += ngrid;
}
void getLegCoords(int dim, vector<double>& Coord,
vector<double>& Weights) {
boost::math::quadrature::gauss<double, 7> gaussLegendre;
auto abscissa = boost::math::quadrature::gauss<double, 7>::abscissa();
auto weights = boost::math::quadrature::gauss<double, 7>::weights();
vector<double> coords1D(7,0), weights1D(7, 0.0);
coords1D[0] = -abscissa[3]; coords1D[1] = -abscissa[2]; coords1D[2] = -abscissa[1];
coords1D[3] = abscissa[0];
coords1D[4] = abscissa[1]; coords1D[5] = abscissa[2]; coords1D[6] = abscissa[3];
weights1D[0] = weights[3]; weights1D[1] = weights[2]; weights1D[2] = weights[1];
weights1D[3] = weights[0];
weights1D[4] = weights[1]; weights1D[5] = weights[2]; weights1D[6] = weights[3];
Coord.resize(7*7*7*3, 0.0); Weights.resize(7*7*7, 0.0);
for (int x =0; x<7; x++)
for (int y =0; y<7; y++)
for (int z =0; z<7; z++)
{
Coord[3 * ( x * 49 + y * 7 + z) + 0] = 0.5*coords1D[x]+0.5;
Coord[3 * ( x * 49 + y * 7 + z) + 1] = 0.5*coords1D[y]+0.5;
Coord[3 * ( x * 49 + y * 7 + z) + 2] = 0.5*coords1D[z]+0.5;
Weights[( x * 49 + y * 7 + z)] = weights1D[x] * weights1D[y] * weights1D[z];
}
}
void initFMMGridAndTree(double* pdm, double* pcentroid, double pscale, double tol) {
cout.precision(12);
dm = pdm;
centroid = pcentroid;
coordScale = pscale;
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
MPI_Comm comm = MPI_COMM_WORLD;
int cheb_deg = 10, max_pts = 10000, mult_order = 10;
const pvfmm::Kernel<double>& kernel_fn=pvfmm::LaplaceKernel<double>::potential();
int leafNodes = 0;
//generate the gauss-legendre and gaiss-chebyshev coords for each leaf node
//which will be used for integration
vector<double> dummy(3,0.0);
tree=ChebFMM_CreateTree(cheb_deg, kernel_fn.ker_dim[0],
getValuesAtGrid,
dummy, comm, tol, max_pts, pvfmm::FreeSpace);
auto nodes = tree->GetNodeList();
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf())
leafNodes++;
size_t nLeg = 7*7*7;
size_t nCheb = (cheb_deg+1)*(cheb_deg+1)*(cheb_deg+1);
size_t numCoords = leafNodes * nLeg;
size_t index = 0;
double volume = 0.0;
int legdeg = 7;
vector<double> Legcoord, Legwts;
getLegCoords(nodes[0]->Dim(), Legcoord, Legwts);
LegCoord.resize(numCoords*3, 0.0); LegWts.resize(numCoords, 0.0);
vector<double> nodeTrgCoords(nLeg*3, 0.0);
//legendre coord for each leaf node and make them also the target coords
//so that the potential is calculated at those points
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf()) {
double s=pvfmm::pow<double>(0.5,nodes[i]->Depth());
double wt = s*s*s/8;
volume += wt;
for (int j=0; j<nLeg; j++) {
LegCoord[index*3+0] = Legcoord[j*3+0]*s+nodes[i]->Coord()[0];
LegCoord[index*3+1] = Legcoord[j*3+1]*s+nodes[i]->Coord()[1];
LegCoord[index*3+2] = Legcoord[j*3+2]*s+nodes[i]->Coord()[2];
LegWts[index] = Legwts[j] * wt;//j == 0 ? wt: 0.0;//wt;//s*s*s * scal;
nodeTrgCoords[j*3+0] = LegCoord[index*3+0];
nodeTrgCoords[j*3+1] = LegCoord[index*3+1];
nodeTrgCoords[j*3+2] = LegCoord[index*3+2];
nodes[i]->trg_coord = nodeTrgCoords;
index++;
}
}
//chebyshev coord
ChebCoord.resize(leafNodes*nCheb*3, 0.0);
index = 0;
std::vector<double> Chebcoord=pvfmm::cheb_nodes<double>(cheb_deg,nodes[0]->Dim());
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf()) {
double s=pvfmm::pow<double>(0.5,nodes[i]->Depth());
for (int j=0; j<nCheb; j++) {
ChebCoord[index*3+0] = Chebcoord[j*3+0]*s+nodes[i]->Coord()[0];
ChebCoord[index*3+1] = Chebcoord[j*3+1]*s+nodes[i]->Coord()[1];
ChebCoord[index*3+2] = Chebcoord[j*3+2]*s+nodes[i]->Coord()[2];
index++;
}
}
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
//calculate the ao values at the legendre coordinates
AoValsAtLegCoord.resize(LegCoord.size() * nao/3, 0.0);
getAoValuesAtGrid(&LegCoord[0], LegCoord.size()/3, &AoValsAtLegCoord[0]);
//calculate the ao values at the chebyshev coordinates
AoValsAtChebCoord.resize(ChebCoord.size() * nao/3, 0.0);
getAoValuesAtGrid(&ChebCoord[0], ChebCoord.size()/3, &AoValsAtChebCoord[0]);
}
void writeNorm(double* mat, size_t size) {
double norm = 0.0;
for (int i=0; i<size; i++)
norm += mat[i];
cout << norm<<endl;
}
void getFockFMM(double* pdm, double* fock, double tol) {
int rank;MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm comm = MPI_COMM_WORLD;
const pvfmm::Kernel<double>& kernel_fn=pvfmm::LaplaceKernel<double>::potential();
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
//construct the density from density matrix and ao values stored on chebyshev grid
int cheb_deg = 10, mult_order = 10;
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
{
int ngrid = ChebCoord.size()/3;
if (intermediate.size() < nao*ngrid) {
intermediate.resize(nao*ngrid, 0.0);
}
double alpha = 1.0, beta = 0.0;
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
ngrid, nao, nao, alpha, &AoValsAtChebCoord[0], ngrid, &pdm[0], nao, beta,
&intermediate[0], ngrid);
if (density.size() < ngrid) density.resize(ngrid, 0.0);
std::fill(&density[0], &density[0]+ngrid, 0.0);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
density[g] += intermediate[p*ngrid + g] * AoValsAtChebCoord[p*ngrid + g];
}
//use the density on the chebyshev grid points to fit the
//chebyshev polynomials of the leaf nodes
int index = 0, nCheb = (cheb_deg+1)*(cheb_deg+1)*(cheb_deg+1);;
auto nodes = tree->GetNodeList();
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf()) {
nodes[i]->ChebData().SetZero();
pvfmm::cheb_approx<double,double>(&density[nCheb*index], cheb_deg, nodes[i]->DataDOF(), &(nodes[i]->ChebData()[0]));
index++;
}
pvfmm::ChebFMM<double> matrices;
matrices.Initialize(mult_order, cheb_deg, comm, &kernel_fn);
tree->SetupFMM(&matrices);
std::vector<double> trg_value;
size_t n_trg=LegCoord.size()/PVFMM_COORD_DIM;
pvfmm::ChebFMM_Evaluate(tree, trg_value, n_trg);
//construct the fock matrix using potential and AOvals on the legendre grid
{
int ngrid = LegCoord.size()/3;
if (intermediate.size() < nao*ngrid)
intermediate.resize(nao*ngrid, 0.0);
vector<double>& aovals = AoValsAtLegCoord;
double scale = pow(coordScale, 5);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
intermediate[p*ngrid + g] = aovals[p*ngrid + g] * trg_value[g] * LegWts[g] * scale * 4 * M_PI;
double alpha = 1.0, beta = 0.0;
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,
nao, nao, ngrid, alpha, &intermediate[0], ngrid, &aovals[0], ngrid, beta,
&fock[0], nao);
}
return;
/*
cout.precision(12);
ncalls = 0;
dm = pdm;
centroid = pcentroid;
coordScale = pscale;
int rank;MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int ngrid = LegWts.size();
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
MPI_Comm comm = MPI_COMM_WORLD;
int cheb_deg = 10, max_pts = 10000, mult_order = 10;
const pvfmm::Kernel<double>& kernel_fn=pvfmm::LaplaceKernel<double>::potential();
vector<double>& trg_coord = LegCoord;
auto* tree=ChebFMM_CreateTree(cheb_deg, kernel_fn.ker_dim[0],
getValuesAtGrid,
trg_coord, comm, tol, max_pts, pvfmm::FreeSpace);
current_time = time(NULL);
if (rank == 0) cout << "make tree "<<(current_time - Initcurrent_time)<<endl;
// Load matrices.
pvfmm::ChebFMM<double> matrices;
matrices.Initialize(mult_order, cheb_deg, comm, &kernel_fn);
// FMM Setup
tree->SetupFMM(&matrices);
current_time = time(NULL);
if (rank == 0) cout << "fmm setup "<<(current_time - Initcurrent_time)<<endl;
// Run FMM
std::vector<double> trg_value;
size_t n_trg=trg_coord.size()/PVFMM_COORD_DIM;
pvfmm::ChebFMM_Evaluate(tree, trg_value, n_trg);
current_time = time(NULL);
if (rank == 0) cout << "evalstep setup "<<(current_time - Initcurrent_time)<<endl;
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
if (intermediate.size() < nao*ngrid)
intermediate.resize(nao*ngrid, 0.0);
tblis_tensor Fock;
std::fill(fock, fock+nao*nao, 0.);
vector<double>& aovals = AoValsAtLegCoord;
long lena[2] = {ngrid, nao}, stridea[2] = {1, ngrid}; //aovals, intermediate
long lendm[2] = {nao, nao} , stridedm[2] = {1, nao}; //density matrix
tblis_init_tensor_d(&AOVALS, 2, lena, &aovals[0], stridea);
tblis_init_tensor_d(&INTERMEDIATE, 2, lena, &intermediate[0], stridea);
tblis_init_tensor_d(&Fock, 2, lendm, fock, stridedm);
double scale = pow(coordScale, 5);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
intermediate[p*ngrid + g] = aovals[p*ngrid + g] * trg_value[g] * LegWts[g] * scale * 4 * M_PI;
//intermediate[p*ngrid + g] = aovals[p*ngrid + g] * LegWts[g] * scale;
tblis_tensor_mult(NULL, NULL, &INTERMEDIATE, "gp", &AOVALS, "gq", &Fock, "pq");
delete tree;
*/
}
void getPotentialFMM(int nTarget, double* coordsTarget, double* potential, double* pdm,
double* pcentroid, double pscale, double tol) {
cout.precision(12);
ncalls = 0;
dm = pdm;
centroid = pcentroid;
coordScale = pscale;
int rank;MPI_Comm_rank(MPI_COMM_WORLD, &rank);
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
MPI_Comm comm = MPI_COMM_WORLD;
int cheb_deg = 10, max_pts = 10000, mult_order = 10;
vector<double> trg_coord(3*nTarget), input_coord(3*nTarget);
for (int i=0; i<nTarget; i++) {
trg_coord[3*i+0] = (coordsTarget[3*i+0] - centroid[0])/coordScale + 0.5;
trg_coord[3*i+1] = (coordsTarget[3*i+1] - centroid[1])/coordScale + 0.5;
trg_coord[3*i+2] = (coordsTarget[3*i+2] - centroid[2])/coordScale + 0.5;
}
const pvfmm::Kernel<double>& kernel_fn=pvfmm::LaplaceKernel<double>::potential();
auto* tree=ChebFMM_CreateTree(cheb_deg, kernel_fn.ker_dim[0],
getValuesAtGrid,
trg_coord, comm, tol, max_pts, pvfmm::FreeSpace);
current_time = time(NULL);
//if (rank == 0) cout << "make tree "<<(current_time - Initcurrent_time)<<endl;
// Load matrices.
pvfmm::ChebFMM<double> matrices;
matrices.Initialize(mult_order, cheb_deg, comm, &kernel_fn);
// FMM Setup
tree->SetupFMM(&matrices);
current_time = time(NULL);
//if (rank == 0) cout << "fmm setup "<<(current_time - Initcurrent_time)<<endl;
// Run FMM
std::vector<double> trg_value;
size_t n_trg=trg_coord.size()/PVFMM_COORD_DIM;
pvfmm::ChebFMM_Evaluate(tree, trg_value, n_trg);
current_time = time(NULL);
//if (rank == 0) cout << "evalstep setup "<<(current_time - Initcurrent_time)<<endl;
for (int i=0; i<nTarget; i++)
potential[i] = trg_value[i]*4*M_PI;
delete tree;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef EvalPT_HEADER_H
#define EvalPT_HEADER_H
#include <Eigen/Dense>
#include <vector>
#ifndef SERIAL
#include "mpi.h"
#endif
class CPSSlater;
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
class MoDeterminant;
//evaluate PT correction
double evaluateScaledEDeterministic(CPSSlater& w, double& lambda, double& unscaledE,
int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE);
double evaluatePTDeterministic(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE);
double evaluatePTDeterministicB(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb, double& coreE);
double evaluatePTDeterministicC(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb, double& coreE);
double evaluateScaledEStochastic(CPSSlater& w, double& lambda, double& unscaledE,
int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddev, double& rk,
int niter=10000, double targetError = 1e-3);
double evaluatePTStochasticMethodA(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddev, int niter, double& A, double& B, double& C);
double evaluatePTStochasticMethodB(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddev, double& rk, int niter, double& A, double& B,
double& C);
double evaluatePTStochasticMethodC(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddevA, double& stddevB, double& stddevC,
int niter, double& A, double& B,
double& C);
double evaluatePTStochastic3rdOrder(CPSSlater& w, double& E0, int& nalpha, int& nbeta, int& norbs,
oneInt& I1, twoInt& I2, twoIntHeatBathSHM& I2hb,
double& coreE, double& stddev, int niter, double& A2, double& B,
double& C, double& A3);
#endif
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace MRLCC_CCAV {
FTensorDecl TensorDecls[30] = {
/* 0*/{"t", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "ccae", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"k", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"k", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"k", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"W", "caca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 6*/{"W", "caac", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 7*/{"W", "cece", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 8*/{"W", "ceec", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 9*/{"W", "aeae", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"W", "aeea", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"W", "cccc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 13*/{"W", "e", "",USAGE_Intermediate, STORAGE_Memory},
/* 14*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"S1", "AA", "",USAGE_Density, STORAGE_Memory},
/* 18*/{"S2", "aa", "",USAGE_Density, STORAGE_Memory},
/* 19*/{"T", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"b", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"p", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"Ap", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"P", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"AP", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"B", "ccae", "",USAGE_Amplitude, STORAGE_Memory},
/* 26*/{"W", "ccae", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 27*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 29*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
};
//Number of terms : 134
FEqInfo EqsRes[134] = {
{"KLQB,PAQB,KLPA", 4.0 , 3, {22,9,21}}, //Ap[KLQB] += 4.0 W[PAQB] p[KLPA]
{"KLQB,PAQB,LKPA", -2.0 , 3, {22,9,21}}, //Ap[KLQB] += -2.0 W[PAQB] p[LKPA]
{"KLQB,QBAP,KLPA", -2.0 , 3, {22,10,21}}, //Ap[KLQB] += -2.0 W[QBAP] p[KLPA]
{"KLQB,QBAP,LKPA", 4.0 , 3, {22,10,21}}, //Ap[KLQB] += 4.0 W[QBAP] p[LKPA]
{"KLQB,IJKL,IJQB", 4.0 , 3, {22,11,21}}, //Ap[KLQB] += 4.0 W[IJKL] p[IJQB]
{"KLQB,IJLK,IJQB", -2.0 , 3, {22,11,21}}, //Ap[KLQB] += -2.0 W[IJLK] p[IJQB]
{"KLQB,IPKQ,ILPB", -4.0 , 3, {22,5,21}}, //Ap[KLQB] += -4.0 W[IPKQ] p[ILPB]
{"KLQB,IPLQ,IKPB", 2.0 , 3, {22,5,21}}, //Ap[KLQB] += 2.0 W[IPLQ] p[IKPB]
{"KLQB,JPKQ,LJPB", 2.0 , 3, {22,5,21}}, //Ap[KLQB] += 2.0 W[JPKQ] p[LJPB]
{"KLQB,JPLQ,KJPB", -4.0 , 3, {22,5,21}}, //Ap[KLQB] += -4.0 W[JPLQ] p[KJPB]
{"KLQB,IQPK,ILPB", 8.0 , 3, {22,6,21}}, //Ap[KLQB] += 8.0 W[IQPK] p[ILPB]
{"KLQB,IQPL,IKPB", -4.0 , 3, {22,6,21}}, //Ap[KLQB] += -4.0 W[IQPL] p[IKPB]
{"KLQB,JQPK,LJPB", -4.0 , 3, {22,6,21}}, //Ap[KLQB] += -4.0 W[JQPK] p[LJPB]
{"KLQB,JQPL,KJPB", 2.0 , 3, {22,6,21}}, //Ap[KLQB] += 2.0 W[JQPL] p[KJPB]
{"KLQB,IAKB,ILQA", -4.0 , 3, {22,7,21}}, //Ap[KLQB] += -4.0 W[IAKB] p[ILQA]
{"KLQB,IALB,IKQA", 2.0 , 3, {22,7,21}}, //Ap[KLQB] += 2.0 W[IALB] p[IKQA]
{"KLQB,JAKB,LJQA", 2.0 , 3, {22,7,21}}, //Ap[KLQB] += 2.0 W[JAKB] p[LJQA]
{"KLQB,JALB,KJQA", -4.0 , 3, {22,7,21}}, //Ap[KLQB] += -4.0 W[JALB] p[KJQA]
{"KLQB,IBAK,ILQA", 2.0 , 3, {22,8,21}}, //Ap[KLQB] += 2.0 W[IBAK] p[ILQA]
{"KLQB,IBAL,IKQA", -4.0 , 3, {22,8,21}}, //Ap[KLQB] += -4.0 W[IBAL] p[IKQA]
{"KLQB,JBAK,LJQA", -4.0 , 3, {22,8,21}}, //Ap[KLQB] += -4.0 W[JBAK] p[LJQA]
{"KLQB,JBAL,KJQA", 8.0 , 3, {22,8,21}}, //Ap[KLQB] += 8.0 W[JBAL] p[KJQA]
{"KLQB,PQ,KLPB", 4.0 , 3, {22,3,21}}, //Ap[KLQB] += 4.0 k[PQ] p[KLPB]
{"KLQB,PQ,LKPB", -2.0 , 3, {22,3,21}}, //Ap[KLQB] += -2.0 k[PQ] p[LKPB]
{"KLQB,IK,ILQB", -4.0 , 3, {22,2,21}}, //Ap[KLQB] += -4.0 k[IK] p[ILQB]
{"KLQB,IL,IKQB", 2.0 , 3, {22,2,21}}, //Ap[KLQB] += 2.0 k[IL] p[IKQB]
{"KLQB,JK,LJQB", 2.0 , 3, {22,2,21}}, //Ap[KLQB] += 2.0 k[JK] p[LJQB]
{"KLQB,JL,KJQB", -4.0 , 3, {22,2,21}}, //Ap[KLQB] += -4.0 k[JL] p[KJQB]
{"KLQB,AB,KLQA", 4.0 , 3, {22,4,21}}, //Ap[KLQB] += 4.0 k[AB] p[KLQA]
{"KLQB,AB,LKQA", -2.0 , 3, {22,4,21}}, //Ap[KLQB] += -2.0 k[AB] p[LKQA]
{"KLQB,IKab,ba,ILQB", 4.0 , 4, {22,11,27,21}}, //Ap[KLQB] += 4.0 W[IKab] delta[ba] p[ILQB]
{"KLQB,ILab,ba,IKQB", -2.0 , 4, {22,11,27,21}}, //Ap[KLQB] += -2.0 W[ILab] delta[ba] p[IKQB]
{"KLQB,IaKb,ba,ILQB", -8.0 , 4, {22,11,27,21}}, //Ap[KLQB] += -8.0 W[IaKb] delta[ba] p[ILQB]
{"KLQB,IaLb,ba,IKQB", 4.0 , 4, {22,11,27,21}}, //Ap[KLQB] += 4.0 W[IaLb] delta[ba] p[IKQB]
{"KLQB,JKab,ba,LJQB", -2.0 , 4, {22,11,27,21}}, //Ap[KLQB] += -2.0 W[JKab] delta[ba] p[LJQB]
{"KLQB,JLab,ba,KJQB", 4.0 , 4, {22,11,27,21}}, //Ap[KLQB] += 4.0 W[JLab] delta[ba] p[KJQB]
{"KLQB,JaKb,ba,LJQB", 4.0 , 4, {22,11,27,21}}, //Ap[KLQB] += 4.0 W[JaKb] delta[ba] p[LJQB]
{"KLQB,JaLb,ba,KJQB", -8.0 , 4, {22,11,27,21}}, //Ap[KLQB] += -8.0 W[JaLb] delta[ba] p[KJQB]
{"KLQB,aPbQ,ba,KLPB", 8.0 , 4, {22,5,27,21}}, //Ap[KLQB] += 8.0 W[aPbQ] delta[ba] p[KLPB]
{"KLQB,aPbQ,ba,LKPB", -4.0 , 4, {22,5,27,21}}, //Ap[KLQB] += -4.0 W[aPbQ] delta[ba] p[LKPB]
{"KLQB,aQPb,ba,KLPB", -4.0 , 4, {22,6,27,21}}, //Ap[KLQB] += -4.0 W[aQPb] delta[ba] p[KLPB]
{"KLQB,aQPb,ba,LKPB", 2.0 , 4, {22,6,27,21}}, //Ap[KLQB] += 2.0 W[aQPb] delta[ba] p[LKPB]
{"KLQB,aAbB,ba,KLQA", 8.0 , 4, {22,7,27,21}}, //Ap[KLQB] += 8.0 W[aAbB] delta[ba] p[KLQA]
{"KLQB,aAbB,ba,LKQA", -4.0 , 4, {22,7,27,21}}, //Ap[KLQB] += -4.0 W[aAbB] delta[ba] p[LKQA]
{"KLQB,aBAb,ba,KLQA", -4.0 , 4, {22,8,27,21}}, //Ap[KLQB] += -4.0 W[aBAb] delta[ba] p[KLQA]
{"KLQB,aBAb,ba,LKQA", 2.0 , 4, {22,8,27,21}}, //Ap[KLQB] += 2.0 W[aBAb] delta[ba] p[LKQA]
{"KLQB,IJKL,PQ,IJPB", -2.0 , 4, {22,11,14,21}}, //Ap[KLQB] += -2.0 W[IJKL] E1[PQ] p[IJPB]
{"KLQB,IJLK,PQ,IJPB", 1.0 , 4, {22,11,14,21}}, //Ap[KLQB] += 1.0 W[IJLK] E1[PQ] p[IJPB]
{"KLQB,IAKB,PQ,ILPA", 2.0 , 4, {22,7,14,21}}, //Ap[KLQB] += 2.0 W[IAKB] E1[PQ] p[ILPA]
{"KLQB,IALB,PQ,IKPA", -1.0 , 4, {22,7,14,21}}, //Ap[KLQB] += -1.0 W[IALB] E1[PQ] p[IKPA]
{"KLQB,JAKB,PQ,LJPA", -1.0 , 4, {22,7,14,21}}, //Ap[KLQB] += -1.0 W[JAKB] E1[PQ] p[LJPA]
{"KLQB,JALB,PQ,KJPA", 2.0 , 4, {22,7,14,21}}, //Ap[KLQB] += 2.0 W[JALB] E1[PQ] p[KJPA]
{"KLQB,IBAK,PQ,ILPA", -1.0 , 4, {22,8,14,21}}, //Ap[KLQB] += -1.0 W[IBAK] E1[PQ] p[ILPA]
{"KLQB,IBAL,PQ,IKPA", 2.0 , 4, {22,8,14,21}}, //Ap[KLQB] += 2.0 W[IBAL] E1[PQ] p[IKPA]
{"KLQB,JBAK,PQ,LJPA", 2.0 , 4, {22,8,14,21}}, //Ap[KLQB] += 2.0 W[JBAK] E1[PQ] p[LJPA]
{"KLQB,JBAL,PQ,KJPA", -4.0 , 4, {22,8,14,21}}, //Ap[KLQB] += -4.0 W[JBAL] E1[PQ] p[KJPA]
{"KLQB,IK,PQ,ILPB", 2.0 , 4, {22,2,14,21}}, //Ap[KLQB] += 2.0 k[IK] E1[PQ] p[ILPB]
{"KLQB,IL,PQ,IKPB", -1.0 , 4, {22,2,14,21}}, //Ap[KLQB] += -1.0 k[IL] E1[PQ] p[IKPB]
{"KLQB,JK,PQ,LJPB", -1.0 , 4, {22,2,14,21}}, //Ap[KLQB] += -1.0 k[JK] E1[PQ] p[LJPB]
{"KLQB,JL,PQ,KJPB", 2.0 , 4, {22,2,14,21}}, //Ap[KLQB] += 2.0 k[JL] E1[PQ] p[KJPB]
{"KLQB,AB,PQ,KLPA", -2.0 , 4, {22,4,14,21}}, //Ap[KLQB] += -2.0 k[AB] E1[PQ] p[KLPA]
{"KLQB,AB,PQ,LKPA", 1.0 , 4, {22,4,14,21}}, //Ap[KLQB] += 1.0 k[AB] E1[PQ] p[LKPA]
{"KLQB,PAaB,aQ,KLPA", -2.0 , 4, {22,9,14,21}}, //Ap[KLQB] += -2.0 W[PAaB] E1[aQ] p[KLPA]
{"KLQB,PAaB,aQ,LKPA", 1.0 , 4, {22,9,14,21}}, //Ap[KLQB] += 1.0 W[PAaB] E1[aQ] p[LKPA]
{"KLQB,QAaB,Pa,KLPA", -2.0 , 4, {22,9,14,21}}, //Ap[KLQB] += -2.0 W[QAaB] E1[Pa] p[KLPA]
{"KLQB,QAaB,Pa,LKPA", 1.0 , 4, {22,9,14,21}}, //Ap[KLQB] += 1.0 W[QAaB] E1[Pa] p[LKPA]
{"KLQB,QBAa,Pa,KLPA", 1.0 , 4, {22,10,14,21}}, //Ap[KLQB] += 1.0 W[QBAa] E1[Pa] p[KLPA]
{"KLQB,QBAa,Pa,LKPA", -2.0 , 4, {22,10,14,21}}, //Ap[KLQB] += -2.0 W[QBAa] E1[Pa] p[LKPA]
{"KLQB,aBAP,aQ,KLPA", 1.0 , 4, {22,10,14,21}}, //Ap[KLQB] += 1.0 W[aBAP] E1[aQ] p[KLPA]
{"KLQB,aBAP,aQ,LKPA", -2.0 , 4, {22,10,14,21}}, //Ap[KLQB] += -2.0 W[aBAP] E1[aQ] p[LKPA]
{"KLQB,IKab,PQ,ba,ILPB", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += -2.0 W[IKab] E1[PQ] delta[ba] p[ILPB]
{"KLQB,ILab,PQ,ba,IKPB", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += 1.0 W[ILab] E1[PQ] delta[ba] p[IKPB]
{"KLQB,IaKb,PQ,ba,ILPB", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += 4.0 W[IaKb] E1[PQ] delta[ba] p[ILPB]
{"KLQB,IaLb,PQ,ba,IKPB", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += -2.0 W[IaLb] E1[PQ] delta[ba] p[IKPB]
{"KLQB,JKab,PQ,ba,LJPB", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += 1.0 W[JKab] E1[PQ] delta[ba] p[LJPB]
{"KLQB,JLab,PQ,ba,KJPB", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += -2.0 W[JLab] E1[PQ] delta[ba] p[KJPB]
{"KLQB,JaKb,PQ,ba,LJPB", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += -2.0 W[JaKb] E1[PQ] delta[ba] p[LJPB]
{"KLQB,JaLb,PQ,ba,KJPB", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLQB] += 4.0 W[JaLb] E1[PQ] delta[ba] p[KJPB]
{"KLQB,IPKa,aQ,ILPB", 2.0 , 4, {22,5,14,21}}, //Ap[KLQB] += 2.0 W[IPKa] E1[aQ] p[ILPB]
{"KLQB,IPLa,aQ,IKPB", -1.0 , 4, {22,5,14,21}}, //Ap[KLQB] += -1.0 W[IPLa] E1[aQ] p[IKPB]
{"KLQB,IQKa,Pa,ILPB", 2.0 , 4, {22,5,14,21}}, //Ap[KLQB] += 2.0 W[IQKa] E1[Pa] p[ILPB]
{"KLQB,IQLa,Pa,IKPB", -1.0 , 4, {22,5,14,21}}, //Ap[KLQB] += -1.0 W[IQLa] E1[Pa] p[IKPB]
{"KLQB,JPKa,aQ,LJPB", -1.0 , 4, {22,5,14,21}}, //Ap[KLQB] += -1.0 W[JPKa] E1[aQ] p[LJPB]
{"KLQB,JPLa,aQ,KJPB", 2.0 , 4, {22,5,14,21}}, //Ap[KLQB] += 2.0 W[JPLa] E1[aQ] p[KJPB]
{"KLQB,JQKa,Pa,LJPB", -1.0 , 4, {22,5,14,21}}, //Ap[KLQB] += -1.0 W[JQKa] E1[Pa] p[LJPB]
{"KLQB,JQLa,Pa,KJPB", 2.0 , 4, {22,5,14,21}}, //Ap[KLQB] += 2.0 W[JQLa] E1[Pa] p[KJPB]
{"KLQB,IQaK,Pa,ILPB", -4.0 , 4, {22,6,14,21}}, //Ap[KLQB] += -4.0 W[IQaK] E1[Pa] p[ILPB]
{"KLQB,IQaL,Pa,IKPB", 2.0 , 4, {22,6,14,21}}, //Ap[KLQB] += 2.0 W[IQaL] E1[Pa] p[IKPB]
{"KLQB,IaPK,aQ,ILPB", -4.0 , 4, {22,6,14,21}}, //Ap[KLQB] += -4.0 W[IaPK] E1[aQ] p[ILPB]
{"KLQB,IaPL,aQ,IKPB", 2.0 , 4, {22,6,14,21}}, //Ap[KLQB] += 2.0 W[IaPL] E1[aQ] p[IKPB]
{"KLQB,JQaK,Pa,LJPB", 2.0 , 4, {22,6,14,21}}, //Ap[KLQB] += 2.0 W[JQaK] E1[Pa] p[LJPB]
{"KLQB,JQaL,Pa,KJPB", -1.0 , 4, {22,6,14,21}}, //Ap[KLQB] += -1.0 W[JQaL] E1[Pa] p[KJPB]
{"KLQB,JaPK,aQ,LJPB", 2.0 , 4, {22,6,14,21}}, //Ap[KLQB] += 2.0 W[JaPK] E1[aQ] p[LJPB]
{"KLQB,JaPL,aQ,KJPB", -1.0 , 4, {22,6,14,21}}, //Ap[KLQB] += -1.0 W[JaPL] E1[aQ] p[KJPB]
{"KLQB,aAbB,PQ,ba,KLPA", -4.0 , 5, {22,7,14,27,21}}, //Ap[KLQB] += -4.0 W[aAbB] E1[PQ] delta[ba] p[KLPA]
{"KLQB,aAbB,PQ,ba,LKPA", 2.0 , 5, {22,7,14,27,21}}, //Ap[KLQB] += 2.0 W[aAbB] E1[PQ] delta[ba] p[LKPA]
{"KLQB,aBAb,PQ,ba,KLPA", 2.0 , 5, {22,8,14,27,21}}, //Ap[KLQB] += 2.0 W[aBAb] E1[PQ] delta[ba] p[KLPA]
{"KLQB,aBAb,PQ,ba,LKPA", -1.0 , 5, {22,8,14,27,21}}, //Ap[KLQB] += -1.0 W[aBAb] E1[PQ] delta[ba] p[LKPA]
{"KLQB,Pa,aQ,KLPB", -2.0 , 4, {22,3,14,21}}, //Ap[KLQB] += -2.0 k[Pa] E1[aQ] p[KLPB]
{"KLQB,Pa,aQ,LKPB", 1.0 , 4, {22,3,14,21}}, //Ap[KLQB] += 1.0 k[Pa] E1[aQ] p[LKPB]
{"KLQB,PQab,ab,KLPB", -2.0 , 4, {22,12,14,21}}, //Ap[KLQB] += -2.0 W[PQab] E1[ab] p[KLPB]
{"KLQB,PQab,ab,LKPB", 1.0 , 4, {22,12,14,21}}, //Ap[KLQB] += 1.0 W[PQab] E1[ab] p[LKPB]
{"KLQB,PaQb,ab,KLPB", 4.0 , 4, {22,12,14,21}}, //Ap[KLQB] += 4.0 W[PaQb] E1[ab] p[KLPB]
{"KLQB,PaQb,ab,LKPB", -2.0 , 4, {22,12,14,21}}, //Ap[KLQB] += -2.0 W[PaQb] E1[ab] p[LKPB]
{"KLQB,aAbB,ab,KLQA", 4.0 , 4, {22,9,14,21}}, //Ap[KLQB] += 4.0 W[aAbB] E1[ab] p[KLQA]
{"KLQB,aAbB,ab,LKQA", -2.0 , 4, {22,9,14,21}}, //Ap[KLQB] += -2.0 W[aAbB] E1[ab] p[LKQA]
{"KLQB,aBAb,ab,KLQA", -2.0 , 4, {22,10,14,21}}, //Ap[KLQB] += -2.0 W[aBAb] E1[ab] p[KLQA]
{"KLQB,aBAb,ab,LKQA", 1.0 , 4, {22,10,14,21}}, //Ap[KLQB] += 1.0 W[aBAb] E1[ab] p[LKQA]
{"KLQB,IaKb,ab,ILQB", -4.0 , 4, {22,5,14,21}}, //Ap[KLQB] += -4.0 W[IaKb] E1[ab] p[ILQB]
{"KLQB,IaLb,ab,IKQB", 2.0 , 4, {22,5,14,21}}, //Ap[KLQB] += 2.0 W[IaLb] E1[ab] p[IKQB]
{"KLQB,JaKb,ab,LJQB", 2.0 , 4, {22,5,14,21}}, //Ap[KLQB] += 2.0 W[JaKb] E1[ab] p[LJQB]
{"KLQB,JaLb,ab,KJQB", -4.0 , 4, {22,5,14,21}}, //Ap[KLQB] += -4.0 W[JaLb] E1[ab] p[KJQB]
{"KLQB,aPcb,bQ,ca,KLPB", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLQB] += -4.0 W[aPcb] E1[bQ] delta[ca] p[KLPB]
{"KLQB,aPcb,bQ,ca,LKPB", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLQB] += 2.0 W[aPcb] E1[bQ] delta[ca] p[LKPB]
{"KLQB,IabK,ab,ILQB", 2.0 , 4, {22,6,14,21}}, //Ap[KLQB] += 2.0 W[IabK] E1[ab] p[ILQB]
{"KLQB,IabL,ab,IKQB", -1.0 , 4, {22,6,14,21}}, //Ap[KLQB] += -1.0 W[IabL] E1[ab] p[IKQB]
{"KLQB,JabK,ab,LJQB", -1.0 , 4, {22,6,14,21}}, //Ap[KLQB] += -1.0 W[JabK] E1[ab] p[LJQB]
{"KLQB,JabL,ab,KJQB", 2.0 , 4, {22,6,14,21}}, //Ap[KLQB] += 2.0 W[JabL] E1[ab] p[KJQB]
{"KLQB,abPc,bQ,ca,KLPB", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLQB] += 2.0 W[abPc] E1[bQ] delta[ca] p[KLPB]
{"KLQB,abPc,bQ,ca,LKPB", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLQB] += -1.0 W[abPc] E1[bQ] delta[ca] p[LKPB]
{"KLQB,aAbB,PaQb,KLPA", -2.0 , 4, {22,9,15,21}}, //Ap[KLQB] += -2.0 W[aAbB] E2[PaQb] p[KLPA]
{"KLQB,aAbB,PaQb,LKPA", 1.0 , 4, {22,9,15,21}}, //Ap[KLQB] += 1.0 W[aAbB] E2[PaQb] p[LKPA]
{"KLQB,aBAb,PaQb,KLPA", 1.0 , 4, {22,10,15,21}}, //Ap[KLQB] += 1.0 W[aBAb] E2[PaQb] p[KLPA]
{"KLQB,aBAb,PabQ,LKPA", 1.0 , 4, {22,10,15,21}}, //Ap[KLQB] += 1.0 W[aBAb] E2[PabQ] p[LKPA]
{"KLQB,IaKb,PaQb,ILPB", 2.0 , 4, {22,5,15,21}}, //Ap[KLQB] += 2.0 W[IaKb] E2[PaQb] p[ILPB]
{"KLQB,IaLb,PaQb,IKPB", -1.0 , 4, {22,5,15,21}}, //Ap[KLQB] += -1.0 W[IaLb] E2[PaQb] p[IKPB]
{"KLQB,JaKb,PaQb,LJPB", -1.0 , 4, {22,5,15,21}}, //Ap[KLQB] += -1.0 W[JaKb] E2[PaQb] p[LJPB]
{"KLQB,JaLb,PaQb,KJPB", 2.0 , 4, {22,5,15,21}}, //Ap[KLQB] += 2.0 W[JaLb] E2[PaQb] p[KJPB]
{"KLQB,IabK,PabQ,ILPB", 2.0 , 4, {22,6,15,21}}, //Ap[KLQB] += 2.0 W[IabK] E2[PabQ] p[ILPB]
{"KLQB,IabL,PabQ,IKPB", -1.0 , 4, {22,6,15,21}}, //Ap[KLQB] += -1.0 W[IabL] E2[PabQ] p[IKPB]
{"KLQB,JabK,PabQ,LJPB", -1.0 , 4, {22,6,15,21}}, //Ap[KLQB] += -1.0 W[JabK] E2[PabQ] p[LJPB]
{"KLQB,JabL,PaQb,KJPB", -1.0 , 4, {22,6,15,21}}, //Ap[KLQB] += -1.0 W[JabL] E2[PaQb] p[KJPB]
{"KLQB,Pabc,abcQ,KLPB", -2.0 , 4, {22,12,15,21}}, //Ap[KLQB] += -2.0 W[Pabc] E2[abcQ] p[KLPB]
{"KLQB,Pabc,abcQ,LKPB", 1.0 , 4, {22,12,15,21}}, //Ap[KLQB] += 1.0 W[Pabc] E2[abcQ] p[LKPB]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[4] = {
{"IJPA,RP,IJRA", 4.0, 3, {20, 28, 26}},
{"IJPA,RP,JIRA",-2.0, 3, {20, 28, 26}},
{"IJPA,RP,IJRA",-2.0, 3, {20, 14, 26}},
{"IJPA,RP,JIRA", 1.0, 3, {20, 14, 26}},
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "MRLCC_CCAV";
Out.perturberClass = "CCAV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 30;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsRes = FEqSet(&EqsRes[0], 134, "MRLCC_CCAV/Res");
Out.Overlap = FEqSet(&Overlap[0], 4, "MRLCC_CCAV/Overlap");
};
};
<file_sep>#include <algorithm>
#include <numeric>
#include "LatticeSum.h"
#include "BasisShell.h"
#include "Kernel.h"
#include "GeneratePolynomials.h"
double dotProduct(double* vA, double* vB) {
return vA[0] * vB[0] + vA[1] * vB[1] + vA[2] * vB[2];
};
void crossProduct(double* v_A, double* v_B, double* c_P, double factor=1.) {
c_P[0] = factor * (v_A[1] * v_B[2] - v_A[2] * v_B[1]);
c_P[1] = -factor * (v_A[0] * v_B[2] - v_A[2] * v_B[0]);
c_P[2] = factor * (v_A[0] * v_B[1] - v_A[1] * v_B[0]);
};
double getKLattice(double* KLattice, double* Lattice) {
vector<double> cross(3);
crossProduct(&Lattice[3], &Lattice[6], &cross[0]);
double Volume = dotProduct(&Lattice[0], &cross[0]);
crossProduct(&Lattice[3], &Lattice[6], &KLattice[0], 2*M_PI/Volume);
crossProduct(&Lattice[6], &Lattice[0], &KLattice[3], 2*M_PI/Volume);
crossProduct(&Lattice[0], &Lattice[3], &KLattice[6], 2*M_PI/Volume);
return Volume;
};
double dist(double a, double b, double c) {
return a*a + b*b + c*c;
}
void LatticeSum::getRelativeCoords(BasisShell *pA, BasisShell *pC,
double& Tx, double& Ty, double& Tz) {
double Txmin = pA->Xcoord - pC->Xcoord,
Tymin = pA->Ycoord - pC->Ycoord,
Tzmin = pA->Zcoord - pC->Zcoord;
Tx = Txmin; Ty = Tymin; Tz = Tzmin;
if (Txmin == 0 && Tymin == 0 && Tzmin == 0) {
return;
}
for (int nx=-1; nx<=1; nx++)
for (int ny=-1; ny<=1; ny++)
for (int nz=-1; nz<=1; nz++)
{
if (dist(Tx + nx * RLattice[0] + ny * RLattice[3] + nz * RLattice[6],
Ty + nx * RLattice[1] + ny * RLattice[4] + nz * RLattice[7],
Tz + nx * RLattice[2] + ny * RLattice[5] + nz * RLattice[8])
< dist(Txmin, Tymin, Tzmin)) {
Txmin = Tx + nx * RLattice[0] + ny * RLattice[3] + nz * RLattice[6];
Tymin = Ty + nx * RLattice[1] + ny * RLattice[4] + nz * RLattice[7];
Tzmin = Tz + nx * RLattice[2] + ny * RLattice[5] + nz * RLattice[8];
}
}
Tx = Txmin; Ty = Tymin; Tz = Tzmin;
}
LatticeSum::LatticeSum(double* Lattice, int nr, int nk, double _Eta2Rho,
double _Eta2RhoCoul, double pscreen) {
//int nr = 1, nk = 10;
int ir = 0; int Nr = 4*nr+1;
vector<double> Rcoordcopy(3*Nr*Nr*Nr), Rdistcopy(Nr*Nr*Nr);
int Nrkeep = pow(2*nr+1, 3);
Rcoord.resize(3*Nrkeep);
Rdist.resize(Nrkeep);
//rvals
for (int i = -2*nr; i<=2*nr ; i++)
for (int j = -2*nr; j<=2*nr ; j++)
for (int k = -2*nr; k<=2*nr ; k++) {
Rcoordcopy[3*ir+0] = i * Lattice[0] + j * Lattice[3] + k * Lattice[6];
Rcoordcopy[3*ir+1] = i * Lattice[1] + j * Lattice[4] + k * Lattice[7];
Rcoordcopy[3*ir+2] = i * Lattice[2] + j * Lattice[5] + k * Lattice[8];
Rdistcopy[ir] = Rcoordcopy[3*ir+0] * Rcoordcopy[3*ir+0]
+ Rcoordcopy[3*ir+1] * Rcoordcopy[3*ir+1]
+ Rcoordcopy[3*ir+2] * Rcoordcopy[3*ir+2];
ir++;
}
//sort rcoord and rdist in ascending order
std::vector<int> idx(Nr*Nr*Nr);
std::iota(idx.begin(), idx.end(), 0);
std::stable_sort(idx.begin(), idx.end(),
[&Rdistcopy](size_t i1, size_t i2) {return Rdistcopy[i1] < Rdistcopy[i2];});
for (int i=0; i<Nrkeep; i++) {
Rdist[i] = Rdistcopy[idx[i]];
Rcoord[3*i+0] = Rcoordcopy[3*idx[i]+0];
Rcoord[3*i+1] = Rcoordcopy[3*idx[i]+1];
Rcoord[3*i+2] = Rcoordcopy[3*idx[i]+2];
}
//make klattice
KLattice.resize(9), RLattice.resize(9);
for (int i=0; i<9; i++) RLattice[i] = Lattice[i];
RVolume = getKLattice(&KLattice[0], Lattice);
int Nk = 2*nk +1;
vector<double> Kcoordcopy(3*(Nk*Nk*Nk-1)), Kdistcopy(Nk*Nk*Nk-1);
Kcoord.resize(3 * (Nk*Nk*Nk-1));
Kdist.resize(Nk*Nk*Nk-1);
ir = 0;
//kvals
for (int i = -nk; i<=nk ; i++)
for (int j = -nk; j<=nk ; j++)
for (int k = -nk; k<=nk ; k++) {
if (i == 0 && j == 0 && k == 0) continue;
Kcoordcopy[3*ir+0] = i * KLattice[0] + j * KLattice[3] + k * KLattice[6];
Kcoordcopy[3*ir+1] = i * KLattice[1] + j * KLattice[4] + k * KLattice[7];
Kcoordcopy[3*ir+2] = i * KLattice[2] + j * KLattice[5] + k * KLattice[8];
Kdistcopy[ir] = Kcoordcopy[3*ir+0] * Kcoordcopy[3*ir+0]
+ Kcoordcopy[3*ir+1] * Kcoordcopy[3*ir+1]
+ Kcoordcopy[3*ir+2] * Kcoordcopy[3*ir+2];
ir++;
}
idx.resize(Nk*Nk*Nk-1);
std::iota(idx.begin(), idx.end(), 0);
std::stable_sort(idx.begin(), idx.end(),
[&Kdistcopy](size_t i1, size_t i2) {return Kdistcopy[i1] < Kdistcopy[i2];});
for (int i=0; i<idx.size(); i++) {
Kdist[i] = Kdistcopy[idx[i]];
Kcoord[3*i+0] = Kcoordcopy[3*idx[i]+0];
Kcoord[3*i+1] = Kcoordcopy[3*idx[i]+1];
Kcoord[3*i+2] = Kcoordcopy[3*idx[i]+2];
}
Eta2RhoOvlp = _Eta2Rho/(Rdist[Nrkeep-1]);
Eta2RhoCoul = _Eta2RhoCoul/(Rdist[1]);
screen = pscreen;
cout << Eta2RhoOvlp<<" "<<Eta2RhoCoul<<endl;
}
void LatticeSum::printLattice() {
cout <<"Rlattice: "<<endl;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++)
printf("%8.4f ", RLattice[j*3+i]);
cout << endl;
}
cout <<"Klattice: "<<endl;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++)
printf("%8.4f ", KLattice[j*3+i]);
cout << endl;
}
}
void LatticeSum::getIncreasingIndex(size_t *&idx, double Tx, double Ty, double Tz, ct::FMemoryStack& Mem) {
double* Tdist;
Mem.Alloc(idx, Rdist.size());
Mem.Alloc(Tdist, Rdist.size());
for (int i=0; i<Rdist.size(); i++) {
idx[i] = i;
Tdist[i] = dist(Tx + Rcoord[3*i + 0],
Ty + Rcoord[3*i + 1],
Tz + Rcoord[3*i + 2]);
}
std::stable_sort(idx, (idx+Rdist.size()),
[&Tdist](size_t i1, size_t i2) {return Tdist[i1] < Tdist[i2];});
Mem.Free(Tdist);
}
bool isRhoLarge(BasisSet& basis, int sh1, int sh2, double eta2rho) {
BasisShell& pA = basis.BasisShells[sh1], &pC = basis.BasisShells[sh2];
for (uint iExpC = 0; iExpC < pC.nFn; ++ iExpC)
for (uint iExpA = 0; iExpA < pA.nFn; ++ iExpA) {
double
Alpha = pA.exponents[iExpA],
Gamma = pC.exponents[iExpC],
InvEta = 1./(Alpha + Gamma),
Rho = (Alpha * Gamma)*InvEta; // = (Alpha * Gamma)*/(Alpha + Gamma)
if (Rho > eta2rho) return true;
}
return false;
}
int LatticeSum::indexCenter(BasisShell& bas) {
double X=bas.Xcoord, Y=bas.Ycoord, Z=bas.Zcoord;
int idx = -1;
for (int i=0; i<atomCenters.size()/3; i++) {
if (abs(X-atomCenters[3*i+0]) < 1.e-12 &&
abs(Y-atomCenters[3*i+1]) < 1.e-12 &&
abs(Z-atomCenters[3*i+2]) < 1.e-12 )
return i;
}
atomCenters.push_back(X);
atomCenters.push_back(Y);
atomCenters.push_back(Z);
return -1;
}
//if rho > eta2rho, part of the summation is done in reciprocal space
//but it does not depend on rho, only on the T (distance between basis)
//and the L (anuglar moment)
void LatticeSum::makeKsum(BasisSet& basis) {
//idensify unique atom positions
atomCenters.reserve(basis.BasisShells.size());
for (int i = 0; i<basis.BasisShells.size(); i++)
int idx = indexCenter(basis.BasisShells[i]);
int pnatm = atomCenters.size()/3;
int nT = pnatm * (pnatm + 1)/2 ; //all pairs of atoms + one for each atom T=0
int nL = 13; //for each pair there are maximum 12 Ls
KSumIdx.resize(nT, vector<long>(nL,-1)); //make all elements -1
vector<double> DistanceT(3*nT);
//for each atom pair and L identify the position of the
//precacualted reciprocal lattice sum
size_t startIndex = 0;
for (int sh1 = 0 ; sh1 < basis.BasisShells.size(); sh1++) {
for (int sh2 = 0 ; sh2 <= sh1; sh2++) {
int T1 = indexCenter(basis.BasisShells[sh1]);
int T2 = indexCenter(basis.BasisShells[sh2]);
int T = T1 == T2 ? 0 : max(T1, T2)*(max(T1, T2)+1)/2 + min(T1, T2);
DistanceT[3*T+0] = atomCenters[3*T1+0] - atomCenters[3*T2+0];
DistanceT[3*T+1] = atomCenters[3*T1+1] - atomCenters[3*T2+1];
DistanceT[3*T+2] = atomCenters[3*T1+2] - atomCenters[3*T2+2];
int l1 = basis.BasisShells[sh1].l, l2 = basis.BasisShells[sh2].l;
int L = l1+l2;
if (isRhoLarge(basis, sh1, sh2, Eta2RhoCoul)) {
if (KSumIdx[T][L] == -1) {
KSumIdx[T][L] = startIndex;
startIndex += (L+1)*(L+2)/2;
}
}
}
}
KSumVal.resize(startIndex, 0.0);
CoulombKernel kernel;
//cout << screen <<" "<<Eta2RhoCoul<<endl;
for (int i=0; i<nT; i++) {
for (int j=0; j<nL; j++) {
if (KSumIdx[i][j] != -1) {
int idx = KSumIdx[i][j];
//now calculate the Ksum
double Tx = DistanceT[3*i], Ty = DistanceT[3*i+1], Tz = DistanceT[3*i+2];
int L = j;
double scale = 1.0;
for (int k=0; k<Kdist.size(); k++) {
double expVal = kernel.getValueKSpace(Kdist[k], 1.0, Eta2RhoCoul);
double maxG = getHermiteReciprocal(L, &KSumVal[idx],
Kcoord[3*k+0],
Kcoord[3*k+1],
Kcoord[3*k+2],
Tx, Ty, Tz,
expVal, scale);
if (abs(maxG * scale * expVal) < screen) {
break;
}
}
}
}
}
//now populate the various
cout <<"start index "<< startIndex <<endl;
//now precalculate the
//exit(0);
}
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace NEVPT2_CCAA {
FTensorDecl TensorDecls[32] = {
/* 0*/{"t", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "ccaa", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"f", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"f", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 6*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 7*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 8*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 9*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 13*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 14*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S1", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"S2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 18*/{"T", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 19*/{"b", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"p", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"Ap", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"P", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"AP", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"B", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"W", "ccaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 26*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 27*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 29*/{"Ap12a", "cc", "", USAGE_PlaceHolder, STORAGE_Memory},
/* 30*/{"Ap12b", "cc", "", USAGE_PlaceHolder, STORAGE_Memory},
/* 31*/{"E312", "aaaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //SR
};
//Number of terms : 122
FEqInfo EqsRes[122] = {
{"KLRS,PQRS,KLPQ", 4.0 , 3, {21,12,20}}, //Ap[KLRS] += 4.0 W[PQRS] p[KLPQ]
{"KLRS,PQRS,LKPQ", -2.0 , 3, {21,12,20}}, //Ap[KLRS] += -2.0 W[PQRS] p[LKPQ]
{"KLRS,PQSR,KLPQ", -2.0 , 3, {21,12,20}}, //Ap[KLRS] += -2.0 W[PQSR] p[KLPQ]
{"KLRS,PQSR,LKPQ", 4.0 , 3, {21,12,20}}, //Ap[KLRS] += 4.0 W[PQSR] p[LKPQ]
{"KLRS,PR,KLPS", 4.0 , 3, {21,3,20}}, //Ap[KLRS] += 4.0 f[PR] p[KLPS]
{"KLRS,PR,LKPS", -2.0 , 3, {21,3,20}}, //Ap[KLRS] += -2.0 f[PR] p[LKPS]
{"KLRS,PS,KLPR", -2.0 , 3, {21,3,20}}, //Ap[KLRS] += -2.0 f[PS] p[KLPR]
{"KLRS,PS,LKPR", 4.0 , 3, {21,3,20}}, //Ap[KLRS] += 4.0 f[PS] p[LKPR]
{"KLRS,QR,KLSQ", -2.0 , 3, {21,3,20}}, //Ap[KLRS] += -2.0 f[QR] p[KLSQ]
{"KLRS,QR,LKSQ", 4.0 , 3, {21,3,20}}, //Ap[KLRS] += 4.0 f[QR] p[LKSQ]
{"KLRS,QS,KLRQ", 4.0 , 3, {21,3,20}}, //Ap[KLRS] += 4.0 f[QS] p[KLRQ]
{"KLRS,QS,LKRQ", -2.0 , 3, {21,3,20}}, //Ap[KLRS] += -2.0 f[QS] p[LKRQ]
{"KLRS,IK,ILRS", -4.0 , 3, {21,2,20}}, //Ap[KLRS] += -4.0 f[IK] p[ILRS]
{"KLRS,IK,ILSR", 2.0 , 3, {21,2,20}}, //Ap[KLRS] += 2.0 f[IK] p[ILSR]
{"KLRS,IL,IKRS", 2.0 , 3, {21,2,20}}, //Ap[KLRS] += 2.0 f[IL] p[IKRS]
{"KLRS,IL,IKSR", -4.0 , 3, {21,2,20}}, //Ap[KLRS] += -4.0 f[IL] p[IKSR]
{"KLRS,JK,LJRS", 2.0 , 3, {21,2,20}}, //Ap[KLRS] += 2.0 f[JK] p[LJRS]
{"KLRS,JK,LJSR", -4.0 , 3, {21,2,20}}, //Ap[KLRS] += -4.0 f[JK] p[LJSR]
{"KLRS,JL,KJRS", -4.0 , 3, {21,2,20}}, //Ap[KLRS] += -4.0 f[JL] p[KJRS]
{"KLRS,JL,KJSR", 2.0 , 3, {21,2,20}}, //Ap[KLRS] += 2.0 f[JL] p[KJSR]
{"KLRS,PR,QS,KLPQ", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[PR] E1[QS] p[KLPQ]
{"KLRS,PR,QS,LKPQ", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[PR] E1[QS] p[LKPQ]
{"KLRS,PS,QR,KLPQ", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[PS] E1[QR] p[KLPQ]
{"KLRS,PS,QR,LKPQ", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[PS] E1[QR] p[LKPQ]
{"KLRS,QR,PS,KLPQ", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[QR] E1[PS] p[KLPQ]
{"KLRS,QR,PS,LKPQ", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[QR] E1[PS] p[LKPQ]
{"KLRS,QS,PR,KLPQ", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[QS] E1[PR] p[KLPQ]
{"KLRS,QS,PR,LKPQ", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[QS] E1[PR] p[LKPQ]
{"KLRS,IK,QS,ILRQ", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[IK] E1[QS] p[ILRQ]
{"KLRS,IK,QR,ILSQ", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[IK] E1[QR] p[ILSQ]
{"KLRS,IK,PS,ILPR", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[IK] E1[PS] p[ILPR]
{"KLRS,IK,PR,ILPS", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[IK] E1[PR] p[ILPS]
{"KLRS,IL,QS,IKRQ", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[IL] E1[QS] p[IKRQ]
{"KLRS,IL,QR,IKSQ", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[IL] E1[QR] p[IKSQ]
{"KLRS,IL,PS,IKPR", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[IL] E1[PS] p[IKPR]
{"KLRS,IL,PR,IKPS", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[IL] E1[PR] p[IKPS]
{"KLRS,JK,QS,LJRQ", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[JK] E1[QS] p[LJRQ]
{"KLRS,JK,QR,LJSQ", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[JK] E1[QR] p[LJSQ]
{"KLRS,JK,PS,LJPR", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[JK] E1[PS] p[LJPR]
{"KLRS,JK,PR,LJPS", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[JK] E1[PR] p[LJPS]
{"KLRS,JL,QS,KJRQ", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[JL] E1[QS] p[KJRQ]
{"KLRS,JL,QR,KJSQ", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[JL] E1[QR] p[KJSQ]
{"KLRS,JL,PS,KJPR", -1.0 , 4, {21,2,13,20}}, //Ap[KLRS] += -1.0 f[JL] E1[PS] p[KJPR]
{"KLRS,JL,PR,KJPS", 2.0 , 4, {21,2,13,20}}, //Ap[KLRS] += 2.0 f[JL] E1[PR] p[KJPS]
{"KLRS,PQRa,aS,KLPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PQRa] E1[aS] p[KLPQ]
{"KLRS,PQRa,aS,LKPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PQRa] E1[aS] p[LKPQ]
{"KLRS,PQSa,aR,KLPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PQSa] E1[aR] p[KLPQ]
{"KLRS,PQSa,aR,LKPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PQSa] E1[aR] p[LKPQ]
{"KLRS,PQaR,aS,KLPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PQaR] E1[aS] p[KLPQ]
{"KLRS,PQaR,aS,LKPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PQaR] E1[aS] p[LKPQ]
{"KLRS,PQaS,aR,KLPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PQaS] E1[aR] p[KLPQ]
{"KLRS,PQaS,aR,LKPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PQaS] E1[aR] p[LKPQ]
{"KLRS,PRSa,Qa,KLPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PRSa] E1[Qa] p[KLPQ]
{"KLRS,PRSa,Qa,LKPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PRSa] E1[Qa] p[LKPQ]
{"KLRS,PSRa,Qa,KLPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PSRa] E1[Qa] p[KLPQ]
{"KLRS,PSRa,Qa,LKPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PSRa] E1[Qa] p[LKPQ]
{"KLRS,QRSa,Pa,KLPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[QRSa] E1[Pa] p[KLPQ]
{"KLRS,QRSa,Pa,LKPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[QRSa] E1[Pa] p[LKPQ]
{"KLRS,QSRa,Pa,KLPQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[QSRa] E1[Pa] p[KLPQ]
{"KLRS,QSRa,Pa,LKPQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[QSRa] E1[Pa] p[LKPQ]
{"KLRS,Pa,aS,KLPR", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[Pa] E1[aS] p[KLPR]
{"KLRS,Pa,aS,LKPR", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[Pa] E1[aS] p[LKPR]
{"KLRS,Pa,aR,KLPS", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[Pa] E1[aR] p[KLPS]
{"KLRS,Pa,aR,LKPS", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[Pa] E1[aR] p[LKPS]
{"KLRS,Qa,aS,KLRQ", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[Qa] E1[aS] p[KLRQ]
{"KLRS,Qa,aS,LKRQ", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[Qa] E1[aS] p[LKRQ]
{"KLRS,Qa,aR,KLSQ", 1.0 , 4, {21,3,13,20}}, //Ap[KLRS] += 1.0 f[Qa] E1[aR] p[KLSQ]
{"KLRS,Qa,aR,LKSQ", -2.0 , 4, {21,3,13,20}}, //Ap[KLRS] += -2.0 f[Qa] E1[aR] p[LKSQ]
{"KLRS,PRab,ab,KLPS", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PRab] E1[ab] p[KLPS]
{"KLRS,PRab,ab,LKPS", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PRab] E1[ab] p[LKPS]
{"KLRS,PSab,ab,KLPR", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[PSab] E1[ab] p[KLPR]
{"KLRS,PSab,ab,LKPR", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PSab] E1[ab] p[LKPR]
{"KLRS,PaRb,ab,KLPS", 4.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 4.0 W[PaRb] E1[ab] p[KLPS]
{"KLRS,PaRb,ab,LKPS", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PaRb] E1[ab] p[LKPS]
{"KLRS,PaSb,ab,KLPR", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[PaSb] E1[ab] p[KLPR]
{"KLRS,PaSb,ab,LKPR", 4.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 4.0 W[PaSb] E1[ab] p[LKPR]
{"KLRS,QRab,ab,KLSQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[QRab] E1[ab] p[KLSQ]
{"KLRS,QRab,ab,LKSQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[QRab] E1[ab] p[LKSQ]
{"KLRS,QSab,ab,KLRQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[QSab] E1[ab] p[KLRQ]
{"KLRS,QSab,ab,LKRQ", 1.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 1.0 W[QSab] E1[ab] p[LKRQ]
{"KLRS,QaRb,ab,KLSQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[QaRb] E1[ab] p[KLSQ]
{"KLRS,QaRb,ab,LKSQ", 4.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 4.0 W[QaRb] E1[ab] p[LKSQ]
{"KLRS,QaSb,ab,KLRQ", 4.0 , 4, {21,12,13,20}}, //Ap[KLRS] += 4.0 W[QaSb] E1[ab] p[KLRQ]
{"KLRS,QaSb,ab,LKRQ", -2.0 , 4, {21,12,13,20}}, //Ap[KLRS] += -2.0 W[QaSb] E1[ab] p[LKRQ]
{"KLRS,IK,PQRS,ILPQ", -1.0 , 4, {21,2,14,20}}, //Ap[KLRS] += -1.0 f[IK] E2[PQRS] p[ILPQ]
{"KLRS,IL,PQSR,IKPQ", -1.0 , 4, {21,2,14,20}}, //Ap[KLRS] += -1.0 f[IL] E2[PQSR] p[IKPQ]
{"KLRS,JK,PQSR,LJPQ", -1.0 , 4, {21,2,14,20}}, //Ap[KLRS] += -1.0 f[JK] E2[PQSR] p[LJPQ]
{"KLRS,JL,PQRS,KJPQ", -1.0 , 4, {21,2,14,20}}, //Ap[KLRS] += -1.0 f[JL] E2[PQRS] p[KJPQ]
{"KLRS,Pa,QaSR,KLPQ", 1.0 , 4, {21,3,14,20}}, //Ap[KLRS] += 1.0 f[Pa] E2[QaSR] p[KLPQ]
{"KLRS,Pa,QaRS,LKPQ", 1.0 , 4, {21,3,14,20}}, //Ap[KLRS] += 1.0 f[Pa] E2[QaRS] p[LKPQ]
{"KLRS,Qa,PaRS,KLPQ", 1.0 , 4, {21,3,14,20}}, //Ap[KLRS] += 1.0 f[Qa] E2[PaRS] p[KLPQ]
{"KLRS,Qa,PaSR,LKPQ", 1.0 , 4, {21,3,14,20}}, //Ap[KLRS] += 1.0 f[Qa] E2[PaSR] p[LKPQ]
{"KLRS,PQab,abRS,KLPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PQab] E2[abRS] p[KLPQ]
{"KLRS,PQab,abSR,LKPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PQab] E2[abSR] p[LKPQ]
{"KLRS,PRab,QaSb,KLPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PRab] E2[QaSb] p[KLPQ]
{"KLRS,PRab,QabS,LKPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PRab] E2[QabS] p[LKPQ]
{"KLRS,PSab,QabR,KLPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PSab] E2[QabR] p[KLPQ]
{"KLRS,PSab,QaRb,LKPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PSab] E2[QaRb] p[LKPQ]
{"KLRS,PaRb,QaSb,KLPQ", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[PaRb] E2[QaSb] p[KLPQ]
{"KLRS,PaRb,QaSb,LKPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PaRb] E2[QaSb] p[LKPQ]
{"KLRS,PaSb,QaRb,KLPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[PaSb] E2[QaRb] p[KLPQ]
{"KLRS,PaSb,QaRb,LKPQ", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[PaSb] E2[QaRb] p[LKPQ]
{"KLRS,QRab,PabS,KLPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[QRab] E2[PabS] p[KLPQ]
{"KLRS,QRab,PaSb,LKPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[QRab] E2[PaSb] p[LKPQ]
{"KLRS,QSab,PaRb,KLPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[QSab] E2[PaRb] p[KLPQ]
{"KLRS,QSab,PabR,LKPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[QSab] E2[PabR] p[LKPQ]
{"KLRS,QaRb,PaSb,KLPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[QaRb] E2[PaSb] p[KLPQ]
{"KLRS,QaRb,PaSb,LKPQ", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[QaRb] E2[PaSb] p[LKPQ]
{"KLRS,QaSb,PaRb,KLPQ", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[QaSb] E2[PaRb] p[KLPQ]
{"KLRS,QaSb,PaRb,LKPQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[QaSb] E2[PaRb] p[LKPQ]
{"KLRS,Pabc,abcS,KLPR", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[Pabc] E2[abcS] p[KLPR]
{"KLRS,Pabc,abcS,LKPR", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[Pabc] E2[abcS] p[LKPR]
{"KLRS,Pabc,abcR,KLPS", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[Pabc] E2[abcR] p[KLPS]
{"KLRS,Pabc,abcR,LKPS", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[Pabc] E2[abcR] p[LKPS]
{"KLRS,Qabc,abcS,KLRQ", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[Qabc] E2[abcS] p[KLRQ]
{"KLRS,Qabc,abcS,LKRQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[Qabc] E2[abcS] p[LKRQ]
{"KLRS,Qabc,abcR,KLSQ", 1.0 , 4, {21,12,14,20}}, //Ap[KLRS] += 1.0 W[Qabc] E2[abcR] p[KLSQ]
{"KLRS,Qabc,abcR,LKSQ", -2.0 , 4, {21,12,14,20}}, //Ap[KLRS] += -2.0 W[Qabc] E2[abcR] p[LKSQ]
//{"KLRS,Pabc,aQbcSR,KLPQ", 1.0 , 4, {21,12,15,20}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabScR] p[KLPQ]
//{"KLSR,Pabc,aQbcSR,LKPQ", 1.0 , 4, {21,12,15,20}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabRcS] p[LKPQ]
//{"KLSR,Qabc,aPbcSR,KLPQ", 1.0 , 4, {21,12,15,20}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabRcS] p[KLPQ]
//{"KLRS,Qabc,aPbcSR,LKPQ", 1.0 , 4, {21,12,15,20}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabScR] p[LKPQ]
};
//Number of terms : 12
FEqInfo EqsHandCode[4] = {
{"KL,Pabc,aQbc,KLPQ", 1.0 , 4, {29,12,31,20}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabScR] p[KLPQ]
{"KL,Pabc,aQbc,LKPQ", 1.0 , 4, {30,12,31,20}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabRcS] p[LKPQ]
{"KL,Qabc,aPbc,KLPQ", 1.0 , 4, {30,12,31,20}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabRcS] p[KLPQ]
{"KL,Qabc,aPbc,LKPQ", 1.0 , 4, {29,12,31,20}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabScR] p[LKPQ]
};
FEqInfo Overlap[14] = {
{"KLRS,PR,KLPS", 2.0 , 3, {19,27,25}}, //b[KLRS] += 2.0 delta[PR] V[KLPS]
{"KLRS,PR,LKPS", -1.0 , 3, {19,27,25}}, //b[KLRS] += -1.0 delta[PR] V[LKPS]
{"KLRS,PS,KLPR", -1.0 , 3, {19,27,25}}, //b[KLRS] += -1.0 delta[PS] V[KLPR]
{"KLRS,PS,LKPR", 2.0 , 3, {19,27,25}}, //b[KLRS] += 2.0 delta[PS] V[LKPR]
{"KLRS,QS,KLRQ", -1.0 , 3, {19,13,25}}, //b[KLRS] += -1.0 E1[QS] V[KLRQ]
{"KLRS,QS,LKRQ", 0.5 , 3, {19,13,25}}, //b[KLRS] += 0.5 E1[QS] V[LKRQ]
{"KLRS,QR,KLSQ", 0.5 , 3, {19,13,25}}, //b[KLRS] += 0.5 E1[QR] V[KLSQ]
{"KLRS,QR,LKSQ", -1.0 , 3, {19,13,25}}, //b[KLRS] += -1.0 E1[QR] V[LKSQ]
{"KLRS,PS,KLPR", 0.5 , 3, {19,13,25}}, //b[KLRS] += 0.5 E1[PS] V[KLPR]
{"KLRS,PS,LKPR", -1.0 , 3, {19,13,25}}, //b[KLRS] += -1.0 E1[PS] V[LKPR]
{"KLRS,PR,KLPS", -1.0 , 3, {19,13,25}}, //b[KLRS] += -1.0 E1[PR] V[KLPS]
{"KLRS,PR,LKPS", 0.5 , 3, {19,13,25}}, //b[KLRS] += 0.5 E1[PR] V[LKPS]
{"KLRS,PQRS,KLPQ", 0.5 , 3, {19,14,25}}, //b[KLRS] += 0.5 E2[PQRS] V[KLPQ]
{"KLRS,PQSR,LKPQ", 0.5 , 3, {19,14,25}}, //b[KLRS] += 0.5 E2[PQSR] V[LKPQ]
};
FEqInfo MakeS1[7] = {
{"PQRS,PR,QS", 4.0 , 3, {16,27,27}}, //S1[PQRS] += 4.0 delta[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PS,QR", -2.0 , 3, {16,27,27}}, //S1[PQRS] += -2.0 delta[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,QS,PR", -2.0 , 3, {16,13,27}}, //S1[PQRS] += -2.0 E1[QS] delta[PR] delta[IK] delta[JL] []
{"PQRS,QR,PS", 1.0 , 3, {16,13,27}}, //S1[PQRS] += 1.0 E1[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,PS,QR", 1.0 , 3, {16,13,27}}, //S1[PQRS] += 1.0 E1[QS] delta[PR] delta[IL] delta[JK] []
{"PQRS,PR,QS", -2.0 , 3, {16,13,27}}, //S1[PQRS] += -2.0 E1[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PQRT,TS", 1.0 , 3, {16,14,27}}, //S1[PQRS] += 1.0 E2[PQRS] delta[IK] delta[JL] []
};
FEqInfo MakeS2[14] = {
{"PQRS,PR,QS", 4.0 , 5, {17,27,27}}, //S1[PQRS] += 4.0 delta[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PR,QS", -2.0 , 5, {17,27,27}}, //S1[PQRS] += -2.0 delta[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,PS,QR", -2.0 , 5, {17,27,27}}, //S1[PQRS] += -2.0 delta[PS] delta[QR] delta[IK] delta[JL] []
{"PQRS,PS,QR", 4.0 , 5, {17,27,27}}, //S1[PQRS] += 4.0 delta[PS] delta[QR] delta[IL] delta[JK] []
{"PQRS,QS,PR", -2.0 , 5, {17,13,27}}, //S1[PQRS] += -2.0 E1[QS] delta[PR] delta[IK] delta[JL] []
{"PQRS,QS,PR", 1.0 , 5, {17,13,27}}, //S1[PQRS] += 1.0 E1[QS] delta[PR] delta[IL] delta[JK] []
{"PQRS,QR,PS", 1.0 , 5, {17,13,27}}, //S1[PQRS] += 1.0 E1[QR] delta[PS] delta[IK] delta[JL] []
{"PQRS,QR,PS", -2.0 , 5, {17,13,27}}, //S1[PQRS] += -2.0 E1[QR] delta[PS] delta[IL] delta[JK] []
{"PQRS,PS,QR", 1.0 , 5, {17,13,27}}, //S1[PQRS] += 1.0 E1[PS] delta[QR] delta[IK] delta[JL] []
{"PQRS,PS,QR", -2.0 , 5, {17,13,27}}, //S1[PQRS] += -2.0 E1[PS] delta[QR] delta[IL] delta[JK] []
{"PQRS,PR,QS", -2.0 , 5, {17,13,27}}, //S1[PQRS] += -2.0 E1[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PR,QS", 1.0 , 5, {17,13,27}}, //S1[PQRS] += 1.0 E1[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,PQRT,TS", 1.0 , 4, {17,14,27}}, //S1[PQRS] += 1.0 E2[PQRS] delta[IK] delta[JL] []
{"PQRS,PQTR,TS", 1.0 , 4, {17,14,27}}, //S1[PQRS] += 1.0 E2[PQSR] delta[IL] delta[JK] []
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "NEVPT2_CCAA";
Out.perturberClass = "CCAA";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 32;
Out.nDomainDecls = 0;
Out.EqsHandCode = FEqSet(&EqsHandCode[0], 4, "NEVPT2_CCAA/Res");
Out.EqsRes = FEqSet(&EqsRes[0], 118, "NEVPT2_CCAA/Res");
Out.Overlap = FEqSet(&Overlap[0], 14, "NEVPT2_CCAA/Overlap");
Out.MakeS1 = FEqSet(&MakeS1[0], 7, "NEVPT2_CCAA/Overlap");
Out.MakeS2 = FEqSet(&MakeS2[0], 14, "NEVPT2_CCAA/Overlap");
};
};
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <numeric>
#include <Eigen/Eigenvalues>
#include "ShermanMorrisonWoodbury.h"
/**
* This takes an inverse and determinant of a matrix formed by a subset of
* columns and rows of Hforbs
* and generates the new inverse and determinant
* by replacing cols with incides des with those with indices cre
* RowVec is the set of row indices that are common to both in the
* incoming and outgoing matrices. ColIn are the column indices
* of the incoming matrix.
*/
void calculateInverseDeterminantWithColumnChange(const Eigen::MatrixXcd &inverseIn, const std::complex<double> &detValueIn, const Eigen::MatrixXcd &tableIn,
Eigen::MatrixXcd &inverseOut, std::complex<double> &detValueOut, Eigen::MatrixXcd &tableOut,
std::vector<int>& cre, std::vector<int>& des,
const Eigen::Map<Eigen::VectorXi> &RowVec,
std::vector<int> &ColIn, const Eigen::MatrixXcd &Hforbs)
{
int ncre = 0, ndes = 0;
for (int i = 0; i < cre.size(); i++)
if (cre[i] != -1)
ncre++;
for (int i = 0; i < des.size(); i++)
if (des[i] != -1)
ndes++;
if (ncre == 0)
{
inverseOut = inverseIn;
detValueOut = detValueIn;
return;
}
Eigen::Map<Eigen::VectorXi> ColCre(&cre[0], ncre);
Eigen::Map<Eigen::VectorXi> ColDes(&des[0], ndes);
Eigen::MatrixXcd newCol, oldCol;
igl::slice(Hforbs, RowVec, ColCre, newCol);
igl::slice(Hforbs, RowVec, ColDes, oldCol);
newCol = newCol - oldCol;
Eigen::MatrixXcd vT = Eigen::MatrixXcd::Zero(ncre, ColIn.size());
std::vector<int> ColOutWrong = ColIn;
for (int i = 0; i < ndes; i++)
{
int index = std::lower_bound(ColIn.begin(), ColIn.end(), des[i]) - ColIn.begin();
vT(i, index) = 1.0;
ColOutWrong[index] = cre[i];
}
//igl::slice(inverseIn, ColCre, 1, vTinverseIn);
Eigen::MatrixXcd vTinverseIn = vT * inverseIn;
Eigen::MatrixXcd Id = Eigen::MatrixXcd::Identity(ncre, ncre);
Eigen::MatrixXcd detFactor = Id + vTinverseIn * newCol;
Eigen::MatrixXcd detFactorInv, inverseOutWrong;
Eigen::FullPivLU<Eigen::MatrixXcd> lub(detFactor);
if (lub.isInvertible())
{
detFactorInv = lub.inverse();
inverseOutWrong = inverseIn - ((inverseIn * newCol) * detFactorInv) * (vTinverseIn);
detValueOut = detValueIn * detFactor.determinant();
}
else
{
Eigen::MatrixXcd originalOrbs;
Eigen::Map<Eigen::VectorXi> Col(&ColIn[0], ColIn.size());
igl::slice(Hforbs, RowVec, Col, originalOrbs);
Eigen::MatrixXcd newOrbs = originalOrbs + newCol * vT;
inverseOutWrong = newOrbs.inverse();
detValueOut = newOrbs.determinant();
}
//now we need to reorder the inverse to correct the order of rows
std::vector<int> order(ColOutWrong.size()), ccopy = ColOutWrong;
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&ccopy](size_t i1, size_t i2) { return ccopy[i1] < ccopy[i2]; });
Eigen::Map<Eigen::VectorXi> orderVec(&order[0], order.size());
igl::slice(inverseOutWrong, orderVec, 1, inverseOut);
}
/**
* This takes an inverse and determinant of a matrix formed by a subset of
* columns and rows of Hforbs
* and generates the new inverse and determinant
* by replacing rows with incides des with those with indices des
* ColVec is the set of col indices that are common to both in the
* incoming and outgoing matrices. RowIn are the column indices
* of the incoming matrix.
*/
void calculateInverseDeterminantWithRowChange(const Eigen::MatrixXcd &inverseIn, const std::complex<double> &detValueIn, const Eigen::MatrixXcd &tableIn,
Eigen::MatrixXcd &inverseOut, std::complex<double> &detValueOut, Eigen::MatrixXcd &tableOut,
std::vector<int>& cre, std::vector<int>& des,
const Eigen::Map<Eigen::VectorXi> &ColVec,
std::vector<int> &RowIn, const Eigen::MatrixXcd &Hforbs, const bool updateTable)
{
int ncre = 0, ndes = 0;
for (int i = 0; i < cre.size(); i++)
if (cre[i] != -1)
ncre++;
for (int i = 0; i < des.size(); i++)
if (des[i] != -1)
ndes++;
if (ncre == 0)
{
inverseOut = inverseIn;
detValueOut = detValueIn;
return;
}
Eigen::Map<Eigen::VectorXi> RowCre(&cre[0], ncre);
Eigen::Map<Eigen::VectorXi> RowDes(&des[0], ndes);
Eigen::MatrixXcd newRow, oldRow;
igl::slice(Hforbs, RowCre, ColVec, newRow);
igl::slice(Hforbs, RowDes, ColVec, oldRow);
newRow = newRow - oldRow;
Eigen::MatrixXcd U = Eigen::MatrixXd::Zero(ColVec.rows(), ncre);
std::vector<int> RowOutWrong = RowIn;
for (int i = 0; i < ndes; i++)
{
int index = std::lower_bound(RowIn.begin(), RowIn.end(), des[i]) - RowIn.begin();
U(index, i) = 1.0;
RowOutWrong[index] = cre[i];
}
//igl::slice(inverseIn, VectorXi::LinSpaced(RowIn.size(), 0, RowIn.size() + 1), RowDes, inverseInU);
Eigen::MatrixXcd inverseInU = inverseIn * U;
Eigen::MatrixXcd Id = Eigen::MatrixXd::Identity(ncre, ncre);
Eigen::MatrixXcd detFactor = Id + newRow * inverseInU;
Eigen::MatrixXcd detFactorInv, inverseOutWrong, tableChangeWrong;
Eigen::FullPivLU<Eigen::MatrixXcd> lub(detFactor);
if (lub.isInvertible())
{
detFactorInv = lub.inverse();
if (updateTable) tableChangeWrong = ((Hforbs.block(0, 0, Hforbs.rows(), ColVec.rows()) * inverseInU) * detFactorInv) * (newRow * inverseIn);
inverseOutWrong = inverseIn - ((inverseInU)*detFactorInv) * (newRow * inverseIn);
detValueOut = detValueIn * detFactor.determinant();
}
else
{
Eigen::MatrixXcd originalOrbs;
Eigen::Map<Eigen::VectorXi> Row(&RowIn[0], RowIn.size());
igl::slice(Hforbs, Row, ColVec, originalOrbs);
Eigen::MatrixXcd newOrbs = originalOrbs + U * newRow;
inverseOutWrong = newOrbs.inverse();
detValueOut = newOrbs.determinant();
}
//now we need to reorder the inverse to correct the order of rows
std::vector<int> order(RowOutWrong.size()), rcopy = RowOutWrong;
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&rcopy](size_t i1, size_t i2) { return rcopy[i1] < rcopy[i2]; });
Eigen::Map<Eigen::VectorXi> orderVec(&order[0], order.size());
Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> perm(orderVec);
inverseOut = inverseOutWrong * perm;
if (updateTable && lub.isInvertible()) tableOut = (tableIn - tableChangeWrong) * perm;
else if (updateTable) tableOut = Hforbs.block(0, 0, Hforbs.rows(), ColVec.rows()) * inverseOut;
//igl::slice(inverseOutWrong, Eigen::VectorXi::LinSpaced(ColVec.rows(), 0, ColVec.rows() - 1), orderVec, inverseOut);
}
double calcPfaffianH(const Eigen::MatrixXd &mat)
{
//if (mat.rows() % 2 == 1) return 0.;
Eigen::HessenbergDecomposition<Eigen::MatrixXd> hd(mat);
Eigen::MatrixXd triDiag = hd.matrixH();
double pfaffian = 1.;
int i = 0;
while (i < mat.rows() - 1) {
pfaffian *= triDiag(i, i+1);
i++; i++;
}
return pfaffian;
}
std::complex<double> calcPfaffian(const Eigen::MatrixXcd &mat)
{
Eigen::MatrixXcd matCopy = mat;
int size = mat.rows();
std::complex<double> pfaffian = 1.;
int i = 0;
while (i < size-1) {
int currentSize = size-i;
Eigen::VectorXd colNorm = matCopy.col(i).tail(currentSize-1).cwiseAbs();
Eigen::VectorXd::Index maxIndex;
colNorm.maxCoeff(&maxIndex);
int ip = i+1+maxIndex;
//pivot if necessary
if (ip != i+1) {
matCopy.block(i,i,currentSize,currentSize).row(1).swap(matCopy.block(i,i,currentSize, currentSize).row(ip-i));
matCopy.block(i,i,currentSize,currentSize).col(1).swap(matCopy.block(i,i,currentSize, currentSize).col(ip-i));
pfaffian *= -1;
}
//gauss elimination
if (matCopy(i,i+1) != 0.) {
pfaffian *= matCopy(i,i+1);
Eigen::VectorXcd tau = matCopy.row(i).tail(currentSize-2);
tau /= matCopy(i,i+1);
if (i+2 < size) {
matCopy.block(i+2,i+2,currentSize-2,currentSize-2) += tau * matCopy.col(i+1).tail(currentSize-2).transpose();
matCopy.block(i+2,i+2,currentSize-2,currentSize-2) -= matCopy.col(i+1).tail(currentSize-2) * tau.transpose();
}
}
else return 0.;
i++; i++;
}
return pfaffian;
}
<file_sep>#include <iostream>
#include <ctime>
#include "math.h"
#include <chrono>
#include "Integral2c.h"
#include "Integral3c.h"
#include "workArray.h"
#include "primitives.h"
using namespace std;
using namespace std::chrono;
int main(int argc, char** argv) {
initWorkArray(); //initializes some arrays
cout.precision(14);
double Lx = 1.0, Ly = 1.0, Lz = 1.0;
double Ax=0.11*Lx, Ay=0.12*Ly, Az=0.13*Lz, expA = 0.17; //gaussian center and exponent
double Bx=0.60*Lx, By=0.61*Ly, Bz=0.62*Lz, expB = 0.7; //gaussian center and exponent
double Cx=0.5*Lx, Cy=0.5*Ly, Cz=0.5*Lz, expC = 60; //gaussian center and exponent
//the order of polynomial on bra and ket N = i+j+k (i,j,k are polynomial order)
int NA, NB, NC;
S_2d.setZero(); NA=0; NB = 1; NC = 0;
double zEta = 1.e11, Z = -4.0;
auto start = high_resolution_clock::now();
/*
vector<double> work(100,0);
JacobiThetaDerivative(0.0, 9.6313216766119, &work[0], 6, true);
cout << work[0]<<" "<<work[1]<<" "<<work[2]<<" "<<work[3]<<endl;
work[0] = 0.0;
JacobiThetaDerivative(-1.0e-12, 9.6313216766119, &work[0], 6, true);
cout << work[0]<<" "<<work[1]<<" "<<work[2]<<" "<<work[3]<<endl;
work[0] = 0.0;
JacobiThetaDerivative(2.*M_PI-1.0e-12, 9.6313216766119, &work[0], 6, true);
cout << work[0]<<" "<<work[1]<<" "<<work[2]<<" "<<work[3]<<endl;
exit(0);
*/
S_3d.setZero();
/*
calcCoulombIntegralPeriodic_BTranslations
(NA, Ax, Ay, Az, expA, 1.0,
NA, Ax, Ay, Az, expA, 1.0,
NC, Ax, Ay, Az, expA, 1.0, //it uses sqrt(norm)
Lx, Ly, Lz, S_3d, coulomb_14_14_8, true);
*/
calcCoulombIntegralPeriodic_BTranslations
(NA, Ax, Ay, Az, expA, 1.0,
NB, Ax, Ay, Az, expB, 1.0,
NC, Bx, By, Bz, zEta, Z*pow(zEta/M_PI/2., 0.75), //it uses sqrt(norm)
Lx, Ly, Lz, S_3d, coulomb_14_14_8, true);
cout <<"--> "<< S_3d(0,0,0)<<endl;
for (int a = 0; a< (NA+1)*(NA+2)/2; a++) {
for (int b = 0; b< (NB+1)*(NB+2)/2; b++)
for (int c = 0; c< (NC+1)*(NC+2)/2; c++)
cout <<"-> "<< S_3d(a,b,c)<<" ";
cout << endl;
}
NA = 1; NB = 1;
S_2d.setZero(); Lx = 3.5668/0.529177208;
calcCoulombIntegralPeriodic(1, 1.68506879, 1.68506879, 1.68506879, 0.3376720, 1.0,
1, 0, 0, 0, 13.5472892, 1.0,
Lx, Lx, Lx, S_2d, false);
/*
calcCoulombIntegralPeriodic(1, 0, 0, 0, 13.5472892, 1.0,
1, 1.68506879, 1.68506879, 1.68506879, 0.3376720, 1.0,
Lx, Lx, Lx, S_2d, false);
*/
for (int a = 0; a< (NA+1)*(NA+2)/2; a++) {
for (int b = 0; b< (NB+1)*(NB+2)/2; b++)
cout << S_2d(a,b)<<" ";
cout << endl;
}
/*
calcCoulombIntegralPeriodic(NA, Ax, Ay, Az, expA, 1.0,
NB, Ax, Ay, Az, expA, 1.0,
Lx, Ly, Lz, S_2d);
*/
cout << S_2d(1,1)<<endl;
exit(0);
/*
for (int i=0; i<1000*100; i++) {
calcCoulombIntegralPeriodic
(NA, Ax, Ay, Az, expA, 1.0,
NB, Bx, By, Bz, expB, 1.0,
Lx, Ly, Lz, S_2d);
}
for (int a = 0; a< (NA+1)*(NA+2)/2; a++) {
for (int b = 0; b< (NB+1)*(NB+2)/2; b++)
cout << S_2d(a,b)<<" ";
cout << endl;
}
*/
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout <<"Executation time: "<< duration.count()/1e6 << endl;
S_3d.setZero();
for (int i=0; i<10000; i++) {
calcCoulombIntegralPeriodic_BTranslations
(NA, Ax, Ay, Az, expA, 1.0,
NB, Bx, By, Bz, expB, 1.0,
NC, Ax, Ay, Az, zEta, Z*pow(zEta/M_PI/2., 0.75), //it uses sqrt(norm)
Lx, Ly, Lz, S_3d, coulomb_14_14_8, true);
}
stop = high_resolution_clock::now();
duration = duration_cast<microseconds>(stop - start);
cout <<"Executation time: "<< duration.count()/1e6 << endl;
}
/*
calcCoulombIntegralPeriodic(NA, Ax, Ay, Az, 2*expA, 1.0,
NB, Bx, By, Bz, expB, 1.0,
Lx, Ly, Lz, S, false);
cout << S(0,0)<<endl;
calcKineticIntegralPeriodic(NA, Ax, Ay, Az, expA, 1.0,
NB, Bx, By, Bz, expB, 1.0,
Lx, Ly, Lz, S);
*/
/*
double zEta = 5.e5, Z = 2.0;
S.setZero();
calcCoulombIntegralPeriodic(0, Ax, Ay, Az, expA, 1.0,
0, Ax, Ay, Az, expA, 1.0,
0, Ax, Ay, Az, zEta, Z*pow(zEta/M_PI/2., 0.75), //it uses sqrt(norm)
Lx, Ly, Lz, S, true);
cout << S(0,0)<<endl;
*/
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "input.h"
#include "CPS.h"
#include "global.h"
#include "Determinants.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
using namespace Eigen;
using namespace boost;
using namespace std;
void readInput(string inputFile, schedule& schd, bool print) {
if (commrank == 0) {
if (print) {
cout << "**************************************************************" << endl;
cout << "Input file :" << endl;
cout << "**************************************************************" << endl;
}
property_tree::iptree input;
property_tree::read_json(inputFile, input);
//print input file
stringstream ss;
property_tree::json_parser::write_json(ss, input);
cout << ss.str() << endl;
//minimal checking for correctness
//wavefunction
schd.wavefunctionType = algorithm::to_lower_copy(input.get("wavefunction.name", "jastrowslater"));
//correlatedwavefunction options
schd.hf = algorithm::to_lower_copy(input.get("wavefunction.hfType", "rhf"));
schd.ifComplex = input.get("wavefunction.complex", false);
schd.uagp = input.get("wavefunction.uagp", false);
optional< property_tree::iptree& > child = input.get_child_optional("wavefunction.correlators");
if (child) {
for (property_tree::iptree::value_type &correlator : input.get_child("wavefunction.correlators")) {
int siteSize = stoi(correlator.first);
string file = correlator.second.data();
schd.correlatorFiles[siteSize] = file;
}
}
//jastrow multislater
schd.ghfDets = input.get("wavefunction.ghfDets", false);
//resonating wave function
schd.numResonants = input.get("wavefunction.numResonants", 1);
schd.singleJastrow = input.get("wavefunction.singleJastrow", true);
schd.readTransOrbs = input.get("wavefunction.readTransOrbs", true);
// permuted wave function
schd.numPermutations = input.get("wavefunction.numPermutations", 1);
//ci and lanczos
schd.nciCore = input.get("wavefunction.numCore", 0);
schd.nciAct = input.get("wavefunction.numAct", -1);
schd.usingFOIS = false;
schd.overlapCutoff = input.get("wavefunction.overlapCutoff", 1.e-5);
if (schd.wavefunctionType == "sci") schd.ciCeption = true;
else schd.ciCeption = false;
schd.determinantFile = input.get("wavefunction.determinants", ""); //used for both sci and starting det
schd.detsInCAS = input.get("wavefunction.detsInCAS", true);
schd.alpha = input.get("wavefunction.alpha", 0.01); //lanczos
schd.lanczosEpsilon = input.get("wavefunction.lanczosEpsilon", 1.e-8); //lanczos
// nnb and rbm
schd.numHidden = input.get("wavefunction.numHidden", 1);
// multi-Slater
schd.excitationLevel = input.get("wavefunction.excitationLevel", 10);
//hamiltonian
string hamString = algorithm::to_lower_copy(input.get("hamiltonian", "abinitio"));
if (hamString == "abinitio") schd.Hamiltonian = ABINITIO;
else if (hamString == "hubbard") schd.Hamiltonian = HUBBARD;
//sampling
schd.epsilon = input.get("sampling.epsilon", 1.e-7);
schd.screen = input.get("sampling.screentol", 1.e-8);
schd.ctmc = input.get("sampling.ctmc", true); //if this is false, metropolis is used!
schd.deterministic = input.get("sampling.deterministic", false);
schd.stochasticIter = input.get("sampling.stochasticIter", 1e4);
schd.burnIter = input.get("sampling.burnIter", 0);
schd.integralSampleSize = input.get("sampling.integralSampleSize", 10);
schd.useLastDet = input.get("sampling.useLastDet", false);
schd.useLogTime = input.get("sampling.useLogTime", false);
schd.numSCSamples = input.get("sampling.numSCSamples", 1e3);
schd.normSampleThreshold = input.get("sampling.normSampleThreshold", 5.);
schd.seed = input.get("sampling.seed", getTime());
// SC-NEVPT2(s) sampling options:
schd.determCCVV = input.get("sampling.determCCVV", false);
schd.efficientNEVPT = input.get("sampling.efficientNEVPT", false);
schd.efficientNEVPT_2 = input.get("sampling.efficientNEVPT_2", false);
schd.exactE_NEVPT = input.get("sampling.exactE_NEVPT", false);
schd.NEVPT_readE = input.get("sampling.NEVPT_readE", false);
schd.NEVPT_writeE = input.get("sampling.NEVPT_writeE", false);
schd.continueMarkovSCPT = input.get("sampling.continueMarkovSCPT", true);
schd.stochasticIterNorms = input.get("sampling.stochasticIterNorms", 1e4);
schd.stochasticIterEachSC = input.get("sampling.stochasticIterEachSC", 1e2);
schd.nIterFindInitDets = input.get("sampling.nIterFindInitDets", 1e2);
schd.SCEnergiesBurnIn = input.get("sampling.SCEnergiesBurnIn", 50);
schd.SCNormsBurnIn = input.get("sampling.SCNormsBurnIn", 50);
schd.exactPerturber = input.get("sampling.exactPerturber", false);
schd.perturberOrb1 = input.get("sampling.perturberOrb1", -1);
schd.perturberOrb2 = input.get("sampling.perturberOrb2", -1);
schd.fixedResTimeNEVPT_Ene = input.get("sampling.fixedResTimeNEVPT_Ene", true);
schd.fixedResTimeNEVPT_Norm = input.get("sampling.fixedResTimeNEVPT_Norm", false);
schd.resTimeNEVPT_Ene = input.get("sampling.resTimeNEVPT_Ene", 5.0);
schd.resTimeNEVPT_Norm = input.get("sampling.resTimeNEVPT_Norm", 5.0);
schd.CASEnergy = input.get("sampling.CASEnergy", 0.0);
// GFMC
schd.maxIter = input.get("sampling.maxIter", 50); //note: parameter repeated in optimizer for vmc
schd.nwalk = input.get("sampling.nwalk", 100);
schd.tau = input.get("sampling.tau", 0.001);
schd.fn_factor = input.get("sampling.fn_factor", 1.0);
schd.nGeneration = input.get("sampling.nGeneration", 30.0);
// FCIQMC options
schd.maxIterFCIQMC = input.get("FCIQMC.maxIter", 50);
schd.nreplicas = input.get("FCIQMC.nReplicas", 1);
schd.nAttemptsEach = input.get("FCIQMC.nAttemptsEach", 1);
schd.mainMemoryFac = input.get("FCIQMC.mainMemoryFac", 5.0);
schd.spawnMemoryFac = input.get("FCIQMC.spawnMemoryFac", 5.0);
schd.shiftDamping = input.get("FCIQMC.shiftDamping", 0.01);
schd.initialShift = input.get("FCIQMC.initialShift", 0.0);
schd.minSpawn = input.get("FCIQMC.minSpawn", 0.01);
schd.minPop = input.get("FCIQMC.minPop", 1.0);
schd.initialPop = input.get("FCIQMC.initialPop", 100.0);
schd.initialNDets = input.get("FCIQMC.initialNDets", 1);
schd.trialInitFCIQMC = input.get("FCIQMC.trialInit", false);
schd.targetPop = input.get("FCIQMC.targetPop", 1000.0);
schd.initiator = input.get("FCIQMC.initiator", false);
schd.initiatorThresh = input.get("FCIQMC.initiatorThresh", 2.0);
schd.semiStoch = input.get("FCIQMC.semiStoch", false);
schd.semiStochInit = input.get("FCIQMC.semiStochInit", false);
schd.semiStochFile = input.get("wavefunction.semiStochDets", "dets");
schd.uniformExGen = input.get("FCIQMC.uniform", true);
schd.heatBathExGen = input.get("FCIQMC.heatBath", false);
schd.heatBathUniformSingExGen = input.get("FCIQMC.heatBathUniformSingles", false);
schd.calcEN2 = input.get("FCIQMC.EN2", false);
schd.useTrialFCIQMC = input.get("FCIQMC.useTrial", false);
schd.trialWFEstimator = input.get("FCIQMC.trialWFEstimator", false);
schd.importanceSampling = input.get("FCIQMC.importanceSampling", false);
schd.applyNodeFCIQMC = input.get("FCIQMC.applyNode", false);
schd.releaseNodeFCIQMC = input.get("FCIQMC.releaseNode", false);
schd.releaseNodeIter = input.get("FCIQMC.releaseNodeIter", 2000);
schd.diagonalDumping = input.get("FCIQMC.diagonalDumping", false);
schd.partialNodeFactor = input.get("FCIQMC.partialNodeFactor", 1.0);
schd.expApprox = input.get("FCIQMC.expApprox", false);
schd.printAnnihilStats = input.get("FCIQMC.printAnnihilStats", true);
//optimization
string method = algorithm::to_lower_copy(input.get("optimizer.method", "amsgrad"));
//need a better way of doing this
if (method == "amsgrad") schd.method = amsgrad;
else if (method == "amsgrad_sgd") schd.method = amsgrad_sgd;
else if (method == "sgd") schd.method = sgd;
else if (method == "sr") schd.method = sr;
else if (method == "lm") schd.method = linearmethod;
schd.restart = input.get("optimizer.restart", false);
schd.fullRestart = input.get("optimizer.fullRestart", false);
child = input.get_child_optional("sampling.maxIter"); //to ensure maxiter is not reassigned
if (!child) schd.maxIter = input.get("optimizer.maxIter", 50);
schd.avgIter = input.get("optimizer.avgIter", 0);
schd._sgdIter = input.get("optimizer.sgdIter", 1);
schd.decay2 = input.get("optimizer.decay2", 0.001);
schd.decay1 = input.get("optimizer.decay1", 0.1);
schd.momentum = input.get("optimizer.momentum", 0.);
schd.stepsize = input.get("optimizer.stepsize", 0.001);
schd.optimizeOrbs = input.get("optimizer.optimizeOrbs", true);
schd.optimizeCiCoeffs = input.get("optimizer.optimizeCiCoeffs", true);
schd.optimizeCps = input.get("optimizer.optimizeCps", true); // this is used for all correlators in correlatedwavefunction, not just cps
schd.optimizeJastrow = input.get("optimizer.optimizeJastrow", true); // this is misleading, becuase this is only relevant to jrbm
schd.optimizeRBM = input.get("optimizer.optimizeRBM", true);
schd.cgIter = input.get("optimizer.cgIter", 15);
schd.sDiagShift = input.get("optimizer.sDiagShift", 0.01);
schd.doHessian = input.get("optimizer.doHessian", false);
schd.diagMethod = input.get("optimizer.diagMethod", "power");
schd.powerShift = input.get("optimizer.powerShift", 10);
//debug and print options
schd.printLevel = input.get("print.level", 0);
schd.printVars = input.get("print.vars", false);
schd.printGrad = input.get("print.grad", false);
schd.printJastrow = input.get("print.jastrow", false);
schd.debug = input.get("print.debug", false);
// SC-NEVPT(2) print options:
schd.printSCNorms = input.get("print.SCNorms", true);
schd.printSCNormFreq = input.get("print.SCNormFreq", 1);
schd.readSCNorms = input.get("print.readSCNorms", false);
schd.continueSCNorms = input.get("print.continueSCNorms", false);
schd.sampleNEVPT2Energy = input.get("print.sampleNEVPT2Energy", true);
schd.printSCEnergies = input.get("print.SCEnergies", false);
schd.nWalkSCEnergies = input.get("print.nWalkSCEnergies", 1);
//deprecated, or I don't know what they do
schd.actWidth = input.get("wavefunction.actWidth", 100);
schd.numActive = input.get("wavefunction.numActive", -1);
schd.expCorrelator = input.get("wavefunction.expCorrelator", false);
schd.PTlambda = input.get("PTlambda", 0.);
schd.tol = input.get("tol", 0.);
schd.beta = input.get("beta", 1.);
}
#ifndef SERIAL
boost::mpi::communicator world;
mpi::broadcast(world, schd, 0);
#endif
}
void readCorrelator(const std::pair<int, std::string>& p,
std::vector<Correlator>& correlators) {
readCorrelator(p.second, p.first, correlators);
}
void readCorrelator(std::string input, int correlatorSize,
std::vector<Correlator>& correlators) {
ifstream dump(input.c_str());
while (dump.good()) {
std::string
Line;
std::getline(dump, Line);
trim(Line);
vector<string> tok;
boost::split(tok, Line, is_any_of(", \t\n"), token_compress_on);
string ArgName = *tok.begin();
//if (dump.eof())
//break;
if (!ArgName.empty() && (boost::iequals(tok[0].substr(0,1), "#"))) continue;
if (ArgName.empty()) continue;
if (tok.size() != correlatorSize) {
cout << "Something wrong in line : "<<Line<<endl;
exit(0);
}
vector<int> asites, bsites;
for (int i=0; i<correlatorSize; i++) {
int site = atoi(tok[i].c_str());
asites.push_back(site);
bsites.push_back(site);
}
correlators.push_back(Correlator(asites, bsites));
}
}
void readHF(MatrixXd& HfmatrixA, MatrixXd& HfmatrixB, std::string hf)
{
if (hf == "rhf" || hf == "ghf") {
ifstream dump("hf.txt");
for (int i = 0; i < HfmatrixA.rows(); i++) {
for (int j = 0; j < HfmatrixA.rows(); j++){
dump >> HfmatrixA(i, j);
HfmatrixB(i, j) = HfmatrixA(i, j);
}
}
}
else {
ifstream dump("hf.txt");
for (int i = 0; i < HfmatrixA.rows(); i++)
{
for (int j = 0; j < HfmatrixA.rows(); j++)
dump >> HfmatrixA(i, j);
for (int j = 0; j < HfmatrixB.rows(); j++)
dump >> HfmatrixB(i, j);
}
}
/*
if (schd.optimizeOrbs) {
double scale = pow(1.*HfmatrixA.rows(), 0.5);
HfmatrixA += 1.e-2*MatrixXd::Random(HfmatrixA.rows(), HfmatrixA.cols())/scale;
HfmatrixB += 1.e-2*MatrixXd::Random(HfmatrixB.rows(), HfmatrixB.cols())/scale;
}
*/
}
void readPairMat(MatrixXd& pairMat)
{
ifstream dump("pairMat.txt");
for (int i = 0; i < pairMat.rows(); i++) {
for (int j = 0; j < pairMat.rows(); j++){
dump >> pairMat(i, j);
}
}
}
void readMat(MatrixXd& mat, std::string fileName)
{
ifstream dump(fileName);
for (int i = 0; i < mat.rows(); i++) {
for (int j = 0; j < mat.cols(); j++){
dump >> mat(i, j);
}
}
}
void readMat(MatrixXcd& mat, std::string fileName)
{
ifstream dump(fileName);
for (int i = 0; i < mat.rows(); i++) {
for (int j = 0; j < mat.cols(); j++){
dump >> mat(i, j);
}
}
}
void readDeterminants(std::string input, vector<Determinant> &determinants,
vector<double> &ciExpansion)
{
ifstream dump(input.c_str());
while (dump.good())
{
std::string Line;
std::getline(dump, Line);
trim_if(Line, is_any_of(", \t\n"));
vector<string> tok;
boost::split(tok, Line, is_any_of(", \t\n"), token_compress_on);
if (tok.size() > 2 )
{
ciExpansion.push_back(atof(tok[0].c_str()));
determinants.push_back(Determinant());
Determinant& det = *determinants.rbegin();
for (int i=0; i<Determinant::norbs; i++)
{
if (boost::iequals(tok[1+i], "2"))
{
det.setoccA(i, true);
det.setoccB(i, true);
}
else if (boost::iequals(tok[1+i], "a"))
{
det.setoccA(i, true);
det.setoccB(i, false);
}
if (boost::iequals(tok[1+i], "b"))
{
det.setoccA(i, false);
det.setoccB(i, true);
}
if (boost::iequals(tok[1+i], "0"))
{
det.setoccA(i, false);
det.setoccB(i, false);
}
}
//***************I AM USING alpha-beta format here, but the wavefunction is coming from Dice that uses alpha0 beta0 alpha1 beta1... format
//So the signs need to be adjusted appropriately
//cout << det<<" "<<getParityForDiceToAlphaBeta(det)<<endl;
*ciExpansion.rbegin() *= getParityForDiceToAlphaBeta(det);
}
}
}
void readDeterminants(std::string input, std::vector<int>& ref, std::vector<int>& open, std::vector<std::array<VectorXi, 2>>& ciExcitations,
std::vector<int>& ciParity, std::vector<double>& ciCoeffs)
{
int norbs = Determinant::norbs;
ifstream dump(input.c_str());
bool isFirst = true;
Determinant refDet;
VectorXi sizes = VectorXi::Zero(10);
int numDets = 0;
while (dump.good()) {
std::string Line;
std::getline(dump, Line);
boost::trim_if(Line, boost::is_any_of(", \t\n"));
vector<string> tok;
boost::split(tok, Line, boost::is_any_of(", \t\n"), boost::token_compress_on);
if (tok.size() > 2 ) {
if (isFirst) {//first det is ref
isFirst = false;
ciCoeffs.push_back(atof(tok[0].c_str()));
ciParity.push_back(1);
std::array<VectorXi, 2> empty;
ciExcitations.push_back(empty);
vector<int> closedBeta, openBeta; //no ghf det structure, so artificially using vector of ints, alpha followed by beta
for (int i=0; i<norbs; i++) {
if (boost::iequals(tok[1+i], "2")) {
refDet.setoccA(i, true);
refDet.setoccB(i, true);
ref.push_back(i);
closedBeta.push_back(i + norbs);
}
else if (boost::iequals(tok[1+i], "a")) {
refDet.setoccA(i, true);
ref.push_back(i);
openBeta.push_back(i + norbs);
}
else if (boost::iequals(tok[1+i], "b")) {
refDet.setoccB(i, true);
closedBeta.push_back(i + norbs);
open.push_back(i);
}
else if (boost::iequals(tok[1+i], "0")) {
open.push_back(i);
openBeta.push_back(i + norbs);
}
}
ref.insert(ref.end(), closedBeta.begin(), closedBeta.end());
open.insert(open.end(), openBeta.begin(), openBeta.end());
}
else {
vector<int> desA, creA, desB, creB;
for (int i=0; i<norbs; i++) {
if (boost::iequals(tok[1+i], "2")) {
if (!refDet.getoccA(i)) creA.push_back(i);
if (!refDet.getoccB(i)) creB.push_back(i);
}
else if (boost::iequals(tok[1+i], "a")) {
if (!refDet.getoccA(i)) creA.push_back(i);
if (refDet.getoccB(i)) desB.push_back(i);
}
else if (boost::iequals(tok[1+i], "b")) {
if (refDet.getoccA(i)) desA.push_back(i);
if (!refDet.getoccB(i)) creB.push_back(i);
}
else if (boost::iequals(tok[1+i], "0")) {
if (refDet.getoccA(i)) desA.push_back(i);
if (refDet.getoccB(i)) desB.push_back(i);
}
}
VectorXi cre = VectorXi::Zero(creA.size() + creB.size());
VectorXi des = VectorXi::Zero(desA.size() + desB.size());
for (int i = 0; i < creA.size(); i++) {
des[i] = std::search_n(ref.begin(), ref.end(), 1, desA[i]) - ref.begin();
cre[i] = std::search_n(open.begin(), open.end(), 1, creA[i]) - open.begin();
//cre[i] = creA[i];
}
for (int i = 0; i < creB.size(); i++) {
des[i + desA.size()] = std::search_n(ref.begin(), ref.end(), 1, desB[i] + norbs) - ref.begin();
cre[i + creA.size()] = std::search_n(open.begin(), open.end(), 1, creB[i] + norbs) - open.begin();
//cre[i + creA.size()] = creB[i] + norbs;
}
std::array<VectorXi, 2> excitations;
excitations[0] = des;
excitations[1] = cre;
if (cre.size() > schd.excitationLevel) continue;
numDets++;
ciCoeffs.push_back(atof(tok[0].c_str()));
ciParity.push_back(refDet.parityA(creA, desA) * refDet.parityB(creB, desB));
ciExcitations.push_back(excitations);
if (cre.size() < 10) sizes(cre.size())++;
}
}
}
if (commrank == 0) {
cout << "Rankwise number of excitations " << sizes.transpose() << endl;
cout << "Number of determinants " << numDets << endl << endl;
}
}
void readDeterminantsGHF(std::string input, std::vector<int>& ref, std::vector<int>& open, std::vector<std::array<VectorXi, 2>>& ciExcitations,
std::vector<int>& ciParity, std::vector<double>& ciCoeffs)
{
int norbs = Determinant::norbs;
ifstream dump(input.c_str());
bool isFirst = true;
Determinant refDet;
while (dump.good()) {
std::string Line;
std::getline(dump, Line);
boost::trim_if(Line, boost::is_any_of(", \t\n"));
vector<string> tok;
boost::split(tok, Line, boost::is_any_of(", \t\n"), boost::token_compress_on);
if (tok.size() > 2 ) {
if (isFirst) {//first det is ref
isFirst = false;
ciCoeffs.push_back(atof(tok[0].c_str()));
ciParity.push_back(1);
std::array<VectorXi, 2> empty;
ciExcitations.push_back(empty);
for (int i=0; i<norbs; i++) {
if (boost::iequals(tok[1+i], "2")) {
refDet.setoccA(2*i, true);
refDet.setoccA(2*i+1, true);
ref.push_back(2*i);
ref.push_back(2*i+1);
}
else if (boost::iequals(tok[1+i], "a")) {
refDet.setoccA(2*i, true);
ref.push_back(2*i);
open.push_back(2*i+1);
}
else if (boost::iequals(tok[1+i], "b")) {
refDet.setoccA(2*i+1, true);
ref.push_back(2*i+1);
open.push_back(2*i);
}
else if (boost::iequals(tok[1+i], "0")) {
open.push_back(2*i);
open.push_back(2*i+1);
}
}
}
else {
ciCoeffs.push_back(atof(tok[0].c_str()));
vector<int> des, cre;
for (int i=0; i<norbs; i++) {
if (boost::iequals(tok[1+i], "2")) {
if (!refDet.getoccA(2*i)) cre.push_back(2*i);
if (!refDet.getoccA(2*i+1)) cre.push_back(2*i+1);
}
else if (boost::iequals(tok[1+i], "a")) {
if (!refDet.getoccA(2*i)) cre.push_back(2*i);
if (refDet.getoccA(2*i+1)) des.push_back(2*i+1);
}
else if (boost::iequals(tok[1+i], "b")) {
if (refDet.getoccA(2*i)) des.push_back(2*i);
if (!refDet.getoccA(2*i+1)) cre.push_back(2*i+1);
}
else if (boost::iequals(tok[1+i], "0")) {
if (refDet.getoccA(2*i)) des.push_back(2*i);
if (refDet.getoccA(2*i+1)) des.push_back(2*i+1);
}
}
ciParity.push_back(refDet.parityA(cre, des));
VectorXi creV = VectorXi::Zero(cre.size());
VectorXi desV = VectorXi::Zero(des.size());
for (int i = 0; i < cre.size(); i++) {
desV[i] = std::search_n(ref.begin(), ref.end(), 1, des[i]) - ref.begin();
creV[i] = std::search_n(open.begin(), open.end(), 1, cre[i]) - open.begin();
//creV[i] = cre[i];
}
std::array<VectorXi, 2> excitations;
excitations[0] = desV;
excitations[1] = creV;
ciExcitations.push_back(excitations);
}
}
}
}
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#include <stdexcept>
#include <stdlib.h>
#include "CxAlgebra.h"
#include "CxDefs.h" // for assert.
namespace ct {
// Out = f * A * B
void Mxm(FScalar *pOut, ptrdiff_t iRowStO, ptrdiff_t iColStO,
FScalar const *pA, ptrdiff_t iRowStA, ptrdiff_t iColStA,
FScalar const *pB, ptrdiff_t iRowStB, ptrdiff_t iColStB,
size_t nRows, size_t nLink, size_t nCols, bool AddToDest, FScalar fFactor )
{
assert( iRowStO == 1 || iColStO == 1 );
assert( iRowStA == 1 || iColStA == 1 );
assert( iRowStB == 1 || iColStB == 1 );
// ^- otherwise dgemm directly not applicable. Would need local copy
// of matrix/matrices with compressed strides.
// if ( nRows == 1 || nLink == 1 || nCols == 1 ) {
// if ( !AddToDest )
// for ( uint ic = 0; ic < nCols; ++ ic )
// for ( uint ir = 0; ir < nRows; ++ ir )
// pOut[ir*iRowStO + ic*iColStO] = 0;
//
// for ( uint ic = 0; ic < nCols; ++ ic )
// for ( uint ir = 0; ir < nRows; ++ ir )
// for ( uint il = 0; il < nLink; ++ il )
// pOut[ir*iRowStO + ic*iColStO] += fFactor * pA[ir*iRowStA + il*iColStA] * pB[il*iRowStB + ic*iColStB];
// return;
// }
FScalar
Beta = AddToDest? 1.0 : 0.0;
char
TransA, TransB;
size_t
lda, ldb,
ldc = (iRowStO == 1)? iColStO : iRowStO;
if ( iRowStA == 1 ) {
TransA = 'N'; lda = iColStA;
} else {
TransA = 'T'; lda = iRowStA;
}
if ( iRowStB == 1 ) {
TransB = 'N'; ldb = iColStB;
} else {
TransB = 'T'; ldb = iRowStB;
}
#ifdef _SINGLE_PRECISION
sgemm_( TransA, TransB, nRows, nCols, nLink,
fFactor, pA, lda, pB, ldb, Beta, pOut, ldc );
#else
dgemm_( TransA, TransB, nRows, nCols, nLink,
fFactor, pA, lda, pB, ldb, Beta, pOut, ldc );
#endif
}
// note: both H and S are overwritten. Eigenvectors go into H.
void DiagonalizeGen(FScalar *pEw, FScalar *pH, size_t ldH, FScalar *pS, size_t ldS, size_t N)
{
size_t info = 0, nWork = 128*N;
FScalar *pWork = (FScalar*)::malloc(sizeof(FScalar)*nWork);
#ifdef _SINGLE_PRECISION
ssygv_(1, 'V', 'L', N, pH, ldH, pS, ldS, pEw, pWork, nWork, info );
#else
dsygv_(1, 'V', 'L', N, pH, ldH, pS, ldS, pEw, pWork, nWork, info );
#endif
::free(pWork);
if ( info != 0 ) throw std::runtime_error("dsygv failed.");
};
void Diagonalize(FScalar *pEw, FScalar *pH, size_t ldH, size_t N)
{
size_t info = 0, nWork = 128*N;
FScalar *pWork = (FScalar*)::malloc(sizeof(FScalar)*nWork);
#ifdef _SINGLE_PRECISION
ssyev_('V', 'L', N, pH, ldH, pEw, pWork, nWork, info );
#else
dsyev_('V', 'L', N, pH, ldH, pEw, pWork, nWork, info );
#endif
::free(pWork);
if ( info != 0 ) throw std::runtime_error("dsyev failed.");
};
}
// kate: indent-width 4
<file_sep>/* Copyright (c) 2012 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bfint (LICENSE). If not, see http://www.gnu.org/licenses/
*/
#pragma once
#include <vector>
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
struct BasisShell
{
double Xcoord, Ycoord, Zcoord; //center of the function
int l; //angular momentum
int nFn, nCo; //number of contracted and primitive functions
vector<double> exponents;
MatrixXd contractions; //nFn x nCo
double fCo(unsigned iExp, unsigned iCo) { return contractions(iExp, iCo); }
double fExp(unsigned iExp) { return exponents[iExp]; }
void PrintAligned(std::ostream &xout, uint Indent) const;
};
struct BasisSet
{
vector<BasisShell> BasisShells;
void PrintAligned(std::ostream &xout, uint Indent) const {
for (int i=0; i<BasisShells.size(); i++) {
xout << endl;
BasisShells[i].PrintAligned(xout, Indent);
}
xout << endl;
}
int getNbas();
};
double RawGaussNorm(double fExp, unsigned l);
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace MRLCC_CCAA {
FTensorDecl TensorDecls[43] = {
/* 0*/{"t", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "ccaa", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"k", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"k", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"k", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"W", "caca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 6*/{"W", "caac", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 7*/{"W", "cece", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 8*/{"W", "ceec", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 9*/{"W", "aeae", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"W", "aeea", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"W", "cccc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 13*/{"W", "e", "",USAGE_Intermediate, STORAGE_Memory},
/* 14*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"S1", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 18*/{"S2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 19*/{"T", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"b", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"p", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"Ap", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"P", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"AP", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"B", "ccaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 26*/{"W", "ccaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 27*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 29*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 30*/{"Ap12", "cc", "", USAGE_PlaceHolder, STORAGE_Memory},
/* 31*/{"Wcaca123", "cac", "", USAGE_PlaceHolder, STORAGE_Memory}, //b
/* 32*/{"E3123A", "aaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //RSb
/* 33*/{"p12", "cc", "", USAGE_PlaceHolder, STORAGE_Memory}, //not used
/* 34*/{"WccaA", "cca", "", USAGE_PlaceHolder, STORAGE_Memory}, //R
/* 35*/{"Waaaa123", "aaa", "", USAGE_PlaceHolder, STORAGE_Memory},
/* 36*/{"Ap12b", "cc", "", USAGE_PlaceHolder, STORAGE_Memory}, //SR
/* 37*/{"Ap12b", "cc", "", USAGE_PlaceHolder, STORAGE_Memory}, //bS
/* 38*/{"Ap12b", "cc", "", USAGE_PlaceHolder, STORAGE_Memory}, //Sb
/* 39*/{"Ap12b", "cc", "", USAGE_PlaceHolder, STORAGE_Memory}, //bR
/* 40*/{"Ap12b", "cc", "", USAGE_PlaceHolder, STORAGE_Memory}, //Rb
/* 41*/{"WccaB", "cca", "", USAGE_PlaceHolder, STORAGE_Memory}, //S
/* 42*/{"Ap2", "ccaa", "", USAGE_PlaceHolder, STORAGE_Memory},
};
/*
//Number of terms : 12
FEqInfo EqsHandCode[12] = {
{"KL,IaK,PQa,ILPQ", -1.0 , 4, {30,31,32,21}}, //Ap[KLRS] += -1.0 W[IaKb] E3[PQaRSb] p[ILPQ]
{"KL,IaL,PQa,IKPQ", -1.0 , 4, {36,31,32,21}}, //Ap[KLRS] += -1.0 W[IaLb] E3[PQaSRb] p[IKPQ]
{"KL,JaK,PQa,LJPQ", -1.0 , 4, {36,31,32,21}}, //Ap[KLRS] += -1.0 W[JaKb] E3[PQaSRb] p[LJPQ]
{"KL,JaL,PQa,KJPQ", -1.0 , 4, {30,31,32,21}}, //Ap[KLRS] += -1.0 W[JaLb] E3[PQaRSb] p[KJPQ]
{"KL,KIa,PQa,ILPQ", -1.0 , 4, {37,34,32,21}}, //Ap[KLRS] += -1.0 W[IabK] E3[PQabSR] p[ILPQ]
{"KL,LIa,PQa,IKPQ", -1.0 , 4, {38,34,32,21}}, //Ap[KLRS] += -1.0 W[IabL] E3[PQabRS] p[IKPQ]
{"KL,KJa,PQa,LJPQ", -1.0 , 4, {39,41,32,21}}, //Ap[KLRS] += -1.0 W[JabK] E3[PQaSbR] p[LJPQ]
{"KL,LJa,PQa,KJPQ", -1.0 , 4, {40,41,32,21}}, //Ap[KLRS] += -1.0 W[JabL] E3[PQaRbS] p[KJPQ]
{"KL,Pab,Qab,KLPQ", 1.0 , 4, {39,35,32,21}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabScR] p[KLPQ]
{"KL,Pab,Qab,LKPQ", 1.0 , 4, {40,35,32,21}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabRcS] p[LKPQ]
{"KL,Qab,Pab,KLPQ", 1.0 , 4, {40,35,32,21}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabRcS] p[KLPQ]
{"KL,Qab,Pab,LKPQ", 1.0 , 4, {39,35,32,21}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabScR] p[LKPQ]
};
*/
//Number of terms : 12
FEqInfo EqsHandCode[12] = {
{"KL,IaK,PQa,ILPQ", -1.0 , 4, {0,1,2,12}}, //Ap[KLRS] += -1.0 W[IaKb] E3[PQaRSb] p[ILPQ]
{"KL,IaL,PQa,IKPQ", -1.0 , 4, {6,1,2,12}}, //Ap[KLRS] += -1.0 W[IaLb] E3[PQaSRb] p[IKPQ]
{"KL,JaK,PQa,LJPQ", -1.0 , 4, {6,1,2,12}}, //Ap[KLRS] += -1.0 W[JaKb] E3[PQaSRb] p[LJPQ]
{"KL,JaL,PQa,KJPQ", -1.0 , 4, {0,1,2,12}}, //Ap[KLRS] += -1.0 W[JaLb] E3[PQaRSb] p[KJPQ]
{"KL,KIa,PQa,ILPQ", -1.0 , 4, {7,4,2,12}}, //Ap[KLRS] += -1.0 W[IabK] E3[PQabSR] p[ILPQ]
{"KL,LIa,PQa,IKPQ", -1.0 , 4, {8,4,2,12}}, //Ap[KLRS] += -1.0 W[IabL] E3[PQabRS] p[IKPQ]
{"KL,KJa,PQa,LJPQ", -1.0 , 4, {9,11,2,12}}, //Ap[KLRS] += -1.0 W[JabK] E3[PQaSbR] p[LJPQ]
{"KL,LJa,PQa,KJPQ", -1.0 , 4, {10,11,2,12}}, //Ap[KLRS] += -1.0 W[JabL] E3[PQaRbS] p[KJPQ]
{"KL,Pab,Qab,KLPQ", 1.0 , 4, {9,5,2,12}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabScR] p[KLPQ]
{"KL,Pab,Qab,LKPQ", 1.0 , 4, {10,5,2,12}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabRcS] p[LKPQ]
{"KL,Qab,Pab,KLPQ", 1.0 , 4, {10,5,2,12}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabRcS] p[KLPQ]
{"KL,Qab,Pab,LKPQ", 1.0 , 4, {9,5,2,12}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabScR] p[LKPQ]
};
//Number of terms : 452
FEqInfo EqsRes[452] = {
{"KLRS,PQRS,KLPQ", 4.0 , 3, {22,12,21}}, //Ap[KLRS] += 4.0 W[PQRS] p[KLPQ]
{"KLRS,PQRS,LKPQ", -2.0 , 3, {22,12,21}}, //Ap[KLRS] += -2.0 W[PQRS] p[LKPQ]
{"KLRS,PQSR,KLPQ", -2.0 , 3, {22,12,21}}, //Ap[KLRS] += -2.0 W[PQSR] p[KLPQ]
{"KLRS,PQSR,LKPQ", 4.0 , 3, {22,12,21}}, //Ap[KLRS] += 4.0 W[PQSR] p[LKPQ]
{"KLRS,IJKL,IJRS", 4.0 , 3, {22,11,21}}, //Ap[KLRS] += 4.0 W[IJKL] p[IJRS]
{"KLRS,IJKL,IJSR", -2.0 , 3, {22,11,21}}, //Ap[KLRS] += -2.0 W[IJKL] p[IJSR]
{"KLRS,IJLK,IJRS", -2.0 , 3, {22,11,21}}, //Ap[KLRS] += -2.0 W[IJLK] p[IJRS]
{"KLRS,IJLK,IJSR", 4.0 , 3, {22,11,21}}, //Ap[KLRS] += 4.0 W[IJLK] p[IJSR]
{"KLRS,IPKR,ILPS", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[IPKR] p[ILPS]
{"KLRS,IPKS,ILPR", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[IPKS] p[ILPR]
{"KLRS,IPLR,IKPS", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[IPLR] p[IKPS]
{"KLRS,IPLS,IKPR", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[IPLS] p[IKPR]
{"KLRS,IQKR,ILSQ", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[IQKR] p[ILSQ]
{"KLRS,IQKS,ILRQ", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[IQKS] p[ILRQ]
{"KLRS,IQLR,IKSQ", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[IQLR] p[IKSQ]
{"KLRS,IQLS,IKRQ", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[IQLS] p[IKRQ]
{"KLRS,JPKR,LJPS", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[JPKR] p[LJPS]
{"KLRS,JPKS,LJPR", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[JPKS] p[LJPR]
{"KLRS,JPLR,KJPS", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[JPLR] p[KJPS]
{"KLRS,JPLS,KJPR", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[JPLS] p[KJPR]
{"KLRS,JQKR,LJSQ", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[JQKR] p[LJSQ]
{"KLRS,JQKS,LJRQ", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[JQKS] p[LJRQ]
{"KLRS,JQLR,KJSQ", 2.0 , 3, {22,5,21}}, //Ap[KLRS] += 2.0 W[JQLR] p[KJSQ]
{"KLRS,JQLS,KJRQ", -4.0 , 3, {22,5,21}}, //Ap[KLRS] += -4.0 W[JQLS] p[KJRQ]
{"KLRS,IRPK,ILPS", 8.0 , 3, {22,6,21}}, //Ap[KLRS] += 8.0 W[IRPK] p[ILPS]
{"KLRS,IRPL,IKPS", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[IRPL] p[IKPS]
{"KLRS,IRQK,ILSQ", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[IRQK] p[ILSQ]
{"KLRS,IRQL,IKSQ", 2.0 , 3, {22,6,21}}, //Ap[KLRS] += 2.0 W[IRQL] p[IKSQ]
{"KLRS,ISPK,ILPR", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[ISPK] p[ILPR]
{"KLRS,ISPL,IKPR", 8.0 , 3, {22,6,21}}, //Ap[KLRS] += 8.0 W[ISPL] p[IKPR]
{"KLRS,ISQK,ILRQ", 2.0 , 3, {22,6,21}}, //Ap[KLRS] += 2.0 W[ISQK] p[ILRQ]
{"KLRS,ISQL,IKRQ", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[ISQL] p[IKRQ]
{"KLRS,JRPK,LJPS", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[JRPK] p[LJPS]
{"KLRS,JRPL,KJPS", 2.0 , 3, {22,6,21}}, //Ap[KLRS] += 2.0 W[JRPL] p[KJPS]
{"KLRS,JRQK,LJSQ", 8.0 , 3, {22,6,21}}, //Ap[KLRS] += 8.0 W[JRQK] p[LJSQ]
{"KLRS,JRQL,KJSQ", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[JRQL] p[KJSQ]
{"KLRS,JSPK,LJPR", 2.0 , 3, {22,6,21}}, //Ap[KLRS] += 2.0 W[JSPK] p[LJPR]
{"KLRS,JSPL,KJPR", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[JSPL] p[KJPR]
{"KLRS,JSQK,LJRQ", -4.0 , 3, {22,6,21}}, //Ap[KLRS] += -4.0 W[JSQK] p[LJRQ]
{"KLRS,JSQL,KJRQ", 8.0 , 3, {22,6,21}}, //Ap[KLRS] += 8.0 W[JSQL] p[KJRQ]
{"KLRS,PR,KLPS", 4.0 , 3, {22,3,21}}, //Ap[KLRS] += 4.0 k[PR] p[KLPS]
{"KLRS,PR,LKPS", -2.0 , 3, {22,3,21}}, //Ap[KLRS] += -2.0 k[PR] p[LKPS]
{"KLRS,PS,KLPR", -2.0 , 3, {22,3,21}}, //Ap[KLRS] += -2.0 k[PS] p[KLPR]
{"KLRS,PS,LKPR", 4.0 , 3, {22,3,21}}, //Ap[KLRS] += 4.0 k[PS] p[LKPR]
{"KLRS,QR,KLSQ", -2.0 , 3, {22,3,21}}, //Ap[KLRS] += -2.0 k[QR] p[KLSQ]
{"KLRS,QR,LKSQ", 4.0 , 3, {22,3,21}}, //Ap[KLRS] += 4.0 k[QR] p[LKSQ]
{"KLRS,QS,KLRQ", 4.0 , 3, {22,3,21}}, //Ap[KLRS] += 4.0 k[QS] p[KLRQ]
{"KLRS,QS,LKRQ", -2.0 , 3, {22,3,21}}, //Ap[KLRS] += -2.0 k[QS] p[LKRQ]
{"KLRS,IK,ILRS", -4.0 , 3, {22,2,21}}, //Ap[KLRS] += -4.0 k[IK] p[ILRS]
{"KLRS,IK,ILSR", 2.0 , 3, {22,2,21}}, //Ap[KLRS] += 2.0 k[IK] p[ILSR]
{"KLRS,IL,IKRS", 2.0 , 3, {22,2,21}}, //Ap[KLRS] += 2.0 k[IL] p[IKRS]
{"KLRS,IL,IKSR", -4.0 , 3, {22,2,21}}, //Ap[KLRS] += -4.0 k[IL] p[IKSR]
{"KLRS,JK,LJRS", 2.0 , 3, {22,2,21}}, //Ap[KLRS] += 2.0 k[JK] p[LJRS]
{"KLRS,JK,LJSR", -4.0 , 3, {22,2,21}}, //Ap[KLRS] += -4.0 k[JK] p[LJSR]
{"KLRS,JL,KJRS", -4.0 , 3, {22,2,21}}, //Ap[KLRS] += -4.0 k[JL] p[KJRS]
{"KLRS,JL,KJSR", 2.0 , 3, {22,2,21}}, //Ap[KLRS] += 2.0 k[JL] p[KJSR]
{"KLRS,IKab,ba,ILRS", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[IKab] delta[ba] p[ILRS]
{"KLRS,IKab,ba,ILSR", -2.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -2.0 W[IKab] delta[ba] p[ILSR]
{"KLRS,ILab,ba,IKRS", -2.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -2.0 W[ILab] delta[ba] p[IKRS]
{"KLRS,ILab,ba,IKSR", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[ILab] delta[ba] p[IKSR]
{"KLRS,IaKb,ba,ILRS", -8.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -8.0 W[IaKb] delta[ba] p[ILRS]
{"KLRS,IaKb,ba,ILSR", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[IaKb] delta[ba] p[ILSR]
{"KLRS,IaLb,ba,IKRS", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[IaLb] delta[ba] p[IKRS]
{"KLRS,IaLb,ba,IKSR", -8.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -8.0 W[IaLb] delta[ba] p[IKSR]
{"KLRS,JKab,ba,LJRS", -2.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -2.0 W[JKab] delta[ba] p[LJRS]
{"KLRS,JKab,ba,LJSR", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[JKab] delta[ba] p[LJSR]
{"KLRS,JLab,ba,KJRS", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[JLab] delta[ba] p[KJRS]
{"KLRS,JLab,ba,KJSR", -2.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -2.0 W[JLab] delta[ba] p[KJSR]
{"KLRS,JaKb,ba,LJRS", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[JaKb] delta[ba] p[LJRS]
{"KLRS,JaKb,ba,LJSR", -8.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -8.0 W[JaKb] delta[ba] p[LJSR]
{"KLRS,JaLb,ba,KJRS", -8.0 , 4, {22,11,27,21}}, //Ap[KLRS] += -8.0 W[JaLb] delta[ba] p[KJRS]
{"KLRS,JaLb,ba,KJSR", 4.0 , 4, {22,11,27,21}}, //Ap[KLRS] += 4.0 W[JaLb] delta[ba] p[KJSR]
{"KLRS,aPbR,ba,KLPS", 8.0 , 4, {22,5,27,21}}, //Ap[KLRS] += 8.0 W[aPbR] delta[ba] p[KLPS]
{"KLRS,aPbR,ba,LKPS", -4.0 , 4, {22,5,27,21}}, //Ap[KLRS] += -4.0 W[aPbR] delta[ba] p[LKPS]
{"KLRS,aPbS,ba,KLPR", -4.0 , 4, {22,5,27,21}}, //Ap[KLRS] += -4.0 W[aPbS] delta[ba] p[KLPR]
{"KLRS,aPbS,ba,LKPR", 8.0 , 4, {22,5,27,21}}, //Ap[KLRS] += 8.0 W[aPbS] delta[ba] p[LKPR]
{"KLRS,aQbR,ba,KLSQ", -4.0 , 4, {22,5,27,21}}, //Ap[KLRS] += -4.0 W[aQbR] delta[ba] p[KLSQ]
{"KLRS,aQbR,ba,LKSQ", 8.0 , 4, {22,5,27,21}}, //Ap[KLRS] += 8.0 W[aQbR] delta[ba] p[LKSQ]
{"KLRS,aQbS,ba,KLRQ", 8.0 , 4, {22,5,27,21}}, //Ap[KLRS] += 8.0 W[aQbS] delta[ba] p[KLRQ]
{"KLRS,aQbS,ba,LKRQ", -4.0 , 4, {22,5,27,21}}, //Ap[KLRS] += -4.0 W[aQbS] delta[ba] p[LKRQ]
{"KLRS,aRPb,ba,KLPS", -4.0 , 4, {22,6,27,21}}, //Ap[KLRS] += -4.0 W[aRPb] delta[ba] p[KLPS]
{"KLRS,aRPb,ba,LKPS", 2.0 , 4, {22,6,27,21}}, //Ap[KLRS] += 2.0 W[aRPb] delta[ba] p[LKPS]
{"KLRS,aRQb,ba,KLSQ", 2.0 , 4, {22,6,27,21}}, //Ap[KLRS] += 2.0 W[aRQb] delta[ba] p[KLSQ]
{"KLRS,aRQb,ba,LKSQ", -4.0 , 4, {22,6,27,21}}, //Ap[KLRS] += -4.0 W[aRQb] delta[ba] p[LKSQ]
{"KLRS,aSPb,ba,KLPR", 2.0 , 4, {22,6,27,21}}, //Ap[KLRS] += 2.0 W[aSPb] delta[ba] p[KLPR]
{"KLRS,aSPb,ba,LKPR", -4.0 , 4, {22,6,27,21}}, //Ap[KLRS] += -4.0 W[aSPb] delta[ba] p[LKPR]
{"KLRS,aSQb,ba,KLRQ", -4.0 , 4, {22,6,27,21}}, //Ap[KLRS] += -4.0 W[aSQb] delta[ba] p[KLRQ]
{"KLRS,aSQb,ba,LKRQ", 2.0 , 4, {22,6,27,21}}, //Ap[KLRS] += 2.0 W[aSQb] delta[ba] p[LKRQ]
{"KLRS,IJKL,QS,IJRQ", -2.0 , 4, {22,11,14,21}}, //Ap[KLRS] += -2.0 W[IJKL] E1[QS] p[IJRQ]
{"KLRS,IJKL,QR,IJSQ", 1.0 , 4, {22,11,14,21}}, //Ap[KLRS] += 1.0 W[IJKL] E1[QR] p[IJSQ]
{"KLRS,IJKL,PS,IJPR", 1.0 , 4, {22,11,14,21}}, //Ap[KLRS] += 1.0 W[IJKL] E1[PS] p[IJPR]
{"KLRS,IJKL,PR,IJPS", -2.0 , 4, {22,11,14,21}}, //Ap[KLRS] += -2.0 W[IJKL] E1[PR] p[IJPS]
{"KLRS,IJLK,QS,IJRQ", 1.0 , 4, {22,11,14,21}}, //Ap[KLRS] += 1.0 W[IJLK] E1[QS] p[IJRQ]
{"KLRS,IJLK,QR,IJSQ", -2.0 , 4, {22,11,14,21}}, //Ap[KLRS] += -2.0 W[IJLK] E1[QR] p[IJSQ]
{"KLRS,IJLK,PS,IJPR", -2.0 , 4, {22,11,14,21}}, //Ap[KLRS] += -2.0 W[IJLK] E1[PS] p[IJPR]
{"KLRS,IJLK,PR,IJPS", 1.0 , 4, {22,11,14,21}}, //Ap[KLRS] += 1.0 W[IJLK] E1[PR] p[IJPS]
{"KLRS,IPKR,QS,ILPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IPKR] E1[QS] p[ILPQ]
{"KLRS,IPKS,QR,ILPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IPKS] E1[QR] p[ILPQ]
{"KLRS,IPLR,QS,IKPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IPLR] E1[QS] p[IKPQ]
{"KLRS,IPLS,QR,IKPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IPLS] E1[QR] p[IKPQ]
{"KLRS,IQKR,PS,ILPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IQKR] E1[PS] p[ILPQ]
{"KLRS,IQKS,PR,ILPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IQKS] E1[PR] p[ILPQ]
{"KLRS,IQLR,PS,IKPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IQLR] E1[PS] p[IKPQ]
{"KLRS,IQLS,PR,IKPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IQLS] E1[PR] p[IKPQ]
{"KLRS,JPKR,QS,LJPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JPKR] E1[QS] p[LJPQ]
{"KLRS,JPKS,QR,LJPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JPKS] E1[QR] p[LJPQ]
{"KLRS,JPLR,QS,KJPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JPLR] E1[QS] p[KJPQ]
{"KLRS,JPLS,QR,KJPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JPLS] E1[QR] p[KJPQ]
{"KLRS,JQKR,PS,LJPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JQKR] E1[PS] p[LJPQ]
{"KLRS,JQKS,PR,LJPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JQKS] E1[PR] p[LJPQ]
{"KLRS,JQLR,PS,KJPQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JQLR] E1[PS] p[KJPQ]
{"KLRS,JQLS,PR,KJPQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JQLS] E1[PR] p[KJPQ]
{"KLRS,IRPK,QS,ILPQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[IRPK] E1[QS] p[ILPQ]
{"KLRS,IRPL,QS,IKPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IRPL] E1[QS] p[IKPQ]
{"KLRS,IRQK,PS,ILPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IRQK] E1[PS] p[ILPQ]
{"KLRS,IRQL,PS,IKPQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[IRQL] E1[PS] p[IKPQ]
{"KLRS,ISPK,QR,ILPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[ISPK] E1[QR] p[ILPQ]
{"KLRS,ISPL,QR,IKPQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[ISPL] E1[QR] p[IKPQ]
{"KLRS,ISQK,PR,ILPQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[ISQK] E1[PR] p[ILPQ]
{"KLRS,ISQL,PR,IKPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[ISQL] E1[PR] p[IKPQ]
{"KLRS,JRPK,QS,LJPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JRPK] E1[QS] p[LJPQ]
{"KLRS,JRPL,QS,KJPQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JRPL] E1[QS] p[KJPQ]
{"KLRS,JRQK,PS,LJPQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[JRQK] E1[PS] p[LJPQ]
{"KLRS,JRQL,PS,KJPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JRQL] E1[PS] p[KJPQ]
{"KLRS,JSPK,QR,LJPQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JSPK] E1[QR] p[LJPQ]
{"KLRS,JSPL,QR,KJPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JSPL] E1[QR] p[KJPQ]
{"KLRS,JSQK,PR,LJPQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JSQK] E1[PR] p[LJPQ]
{"KLRS,JSQL,PR,KJPQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[JSQL] E1[PR] p[KJPQ]
{"KLRS,PR,QS,KLPQ", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[PR] E1[QS] p[KLPQ]
{"KLRS,PR,QS,LKPQ", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[PR] E1[QS] p[LKPQ]
{"KLRS,PS,QR,KLPQ", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[PS] E1[QR] p[KLPQ]
{"KLRS,PS,QR,LKPQ", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[PS] E1[QR] p[LKPQ]
{"KLRS,QR,PS,KLPQ", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[QR] E1[PS] p[KLPQ]
{"KLRS,QR,PS,LKPQ", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[QR] E1[PS] p[LKPQ]
{"KLRS,QS,PR,KLPQ", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[QS] E1[PR] p[KLPQ]
{"KLRS,QS,PR,LKPQ", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[QS] E1[PR] p[LKPQ]
{"KLRS,IK,QS,ILRQ", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[IK] E1[QS] p[ILRQ]
{"KLRS,IK,QR,ILSQ", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[IK] E1[QR] p[ILSQ]
{"KLRS,IK,PS,ILPR", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[IK] E1[PS] p[ILPR]
{"KLRS,IK,PR,ILPS", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[IK] E1[PR] p[ILPS]
{"KLRS,IL,QS,IKRQ", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[IL] E1[QS] p[IKRQ]
{"KLRS,IL,QR,IKSQ", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[IL] E1[QR] p[IKSQ]
{"KLRS,IL,PS,IKPR", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[IL] E1[PS] p[IKPR]
{"KLRS,IL,PR,IKPS", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[IL] E1[PR] p[IKPS]
{"KLRS,JK,QS,LJRQ", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[JK] E1[QS] p[LJRQ]
{"KLRS,JK,QR,LJSQ", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[JK] E1[QR] p[LJSQ]
{"KLRS,JK,PS,LJPR", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[JK] E1[PS] p[LJPR]
{"KLRS,JK,PR,LJPS", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[JK] E1[PR] p[LJPS]
{"KLRS,JL,QS,KJRQ", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[JL] E1[QS] p[KJRQ]
{"KLRS,JL,QR,KJSQ", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[JL] E1[QR] p[KJSQ]
{"KLRS,JL,PS,KJPR", -1.0 , 4, {22,2,14,21}}, //Ap[KLRS] += -1.0 k[JL] E1[PS] p[KJPR]
{"KLRS,JL,PR,KJPS", 2.0 , 4, {22,2,14,21}}, //Ap[KLRS] += 2.0 k[JL] E1[PR] p[KJPS]
{"KLRS,PQRa,aS,KLPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PQRa] E1[aS] p[KLPQ]
{"KLRS,PQRa,aS,LKPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PQRa] E1[aS] p[LKPQ]
{"KLRS,PQSa,aR,KLPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PQSa] E1[aR] p[KLPQ]
{"KLRS,PQSa,aR,LKPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PQSa] E1[aR] p[LKPQ]
{"KLRS,PQaR,aS,KLPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PQaR] E1[aS] p[KLPQ]
{"KLRS,PQaR,aS,LKPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PQaR] E1[aS] p[LKPQ]
{"KLRS,PQaS,aR,KLPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PQaS] E1[aR] p[KLPQ]
{"KLRS,PQaS,aR,LKPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PQaS] E1[aR] p[LKPQ]
{"KLRS,PRSa,Qa,KLPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PRSa] E1[Qa] p[KLPQ]
{"KLRS,PRSa,Qa,LKPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PRSa] E1[Qa] p[LKPQ]
{"KLRS,PSRa,Qa,KLPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PSRa] E1[Qa] p[KLPQ]
{"KLRS,PSRa,Qa,LKPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PSRa] E1[Qa] p[LKPQ]
{"KLRS,QRSa,Pa,KLPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[QRSa] E1[Pa] p[KLPQ]
{"KLRS,QRSa,Pa,LKPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[QRSa] E1[Pa] p[LKPQ]
{"KLRS,QSRa,Pa,KLPQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[QSRa] E1[Pa] p[KLPQ]
{"KLRS,QSRa,Pa,LKPQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[QSRa] E1[Pa] p[LKPQ]
{"KLRS,IKab,QS,ba,ILRQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[IKab] E1[QS] delta[ba] p[ILRQ]
{"KLRS,IKab,QR,ba,ILSQ", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[IKab] E1[QR] delta[ba] p[ILSQ]
{"KLRS,IKab,PS,ba,ILPR", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[IKab] E1[PS] delta[ba] p[ILPR]
{"KLRS,IKab,PR,ba,ILPS", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[IKab] E1[PR] delta[ba] p[ILPS]
{"KLRS,ILab,QS,ba,IKRQ", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[ILab] E1[QS] delta[ba] p[IKRQ]
{"KLRS,ILab,QR,ba,IKSQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[ILab] E1[QR] delta[ba] p[IKSQ]
{"KLRS,ILab,PS,ba,IKPR", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[ILab] E1[PS] delta[ba] p[IKPR]
{"KLRS,ILab,PR,ba,IKPS", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[ILab] E1[PR] delta[ba] p[IKPS]
{"KLRS,IaKb,QS,ba,ILRQ", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[IaKb] E1[QS] delta[ba] p[ILRQ]
{"KLRS,IaKb,QR,ba,ILSQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[IaKb] E1[QR] delta[ba] p[ILSQ]
{"KLRS,IaKb,PS,ba,ILPR", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[IaKb] E1[PS] delta[ba] p[ILPR]
{"KLRS,IaKb,PR,ba,ILPS", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[IaKb] E1[PR] delta[ba] p[ILPS]
{"KLRS,IaLb,QS,ba,IKRQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[IaLb] E1[QS] delta[ba] p[IKRQ]
{"KLRS,IaLb,QR,ba,IKSQ", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[IaLb] E1[QR] delta[ba] p[IKSQ]
{"KLRS,IaLb,PS,ba,IKPR", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[IaLb] E1[PS] delta[ba] p[IKPR]
{"KLRS,IaLb,PR,ba,IKPS", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[IaLb] E1[PR] delta[ba] p[IKPS]
{"KLRS,JKab,QS,ba,LJRQ", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[JKab] E1[QS] delta[ba] p[LJRQ]
{"KLRS,JKab,QR,ba,LJSQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JKab] E1[QR] delta[ba] p[LJSQ]
{"KLRS,JKab,PS,ba,LJPR", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JKab] E1[PS] delta[ba] p[LJPR]
{"KLRS,JKab,PR,ba,LJPS", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[JKab] E1[PR] delta[ba] p[LJPS]
{"KLRS,JLab,QS,ba,KJRQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JLab] E1[QS] delta[ba] p[KJRQ]
{"KLRS,JLab,QR,ba,KJSQ", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[JLab] E1[QR] delta[ba] p[KJSQ]
{"KLRS,JLab,PS,ba,KJPR", 1.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 1.0 W[JLab] E1[PS] delta[ba] p[KJPR]
{"KLRS,JLab,PR,ba,KJPS", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JLab] E1[PR] delta[ba] p[KJPS]
{"KLRS,JaKb,QS,ba,LJRQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JaKb] E1[QS] delta[ba] p[LJRQ]
{"KLRS,JaKb,QR,ba,LJSQ", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[JaKb] E1[QR] delta[ba] p[LJSQ]
{"KLRS,JaKb,PS,ba,LJPR", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[JaKb] E1[PS] delta[ba] p[LJPR]
{"KLRS,JaKb,PR,ba,LJPS", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JaKb] E1[PR] delta[ba] p[LJPS]
{"KLRS,JaLb,QS,ba,KJRQ", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[JaLb] E1[QS] delta[ba] p[KJRQ]
{"KLRS,JaLb,QR,ba,KJSQ", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JaLb] E1[QR] delta[ba] p[KJSQ]
{"KLRS,JaLb,PS,ba,KJPR", -2.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += -2.0 W[JaLb] E1[PS] delta[ba] p[KJPR]
{"KLRS,JaLb,PR,ba,KJPS", 4.0 , 5, {22,11,14,27,21}}, //Ap[KLRS] += 4.0 W[JaLb] E1[PR] delta[ba] p[KJPS]
{"KLRS,IPKa,aS,ILPR", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IPKa] E1[aS] p[ILPR]
{"KLRS,IPKa,aR,ILPS", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IPKa] E1[aR] p[ILPS]
{"KLRS,IPLa,aS,IKPR", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IPLa] E1[aS] p[IKPR]
{"KLRS,IPLa,aR,IKPS", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IPLa] E1[aR] p[IKPS]
{"KLRS,IQKa,aS,ILRQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IQKa] E1[aS] p[ILRQ]
{"KLRS,IQKa,aR,ILSQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IQKa] E1[aR] p[ILSQ]
{"KLRS,IQLa,aS,IKRQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IQLa] E1[aS] p[IKRQ]
{"KLRS,IQLa,aR,IKSQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IQLa] E1[aR] p[IKSQ]
{"KLRS,IRKa,Qa,ILSQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IRKa] E1[Qa] p[ILSQ]
{"KLRS,IRKa,Pa,ILPS", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IRKa] E1[Pa] p[ILPS]
{"KLRS,IRLa,Qa,IKSQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IRLa] E1[Qa] p[IKSQ]
{"KLRS,IRLa,Pa,IKPS", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[IRLa] E1[Pa] p[IKPS]
{"KLRS,ISKa,Qa,ILRQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[ISKa] E1[Qa] p[ILRQ]
{"KLRS,ISKa,Pa,ILPR", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[ISKa] E1[Pa] p[ILPR]
{"KLRS,ISLa,Qa,IKRQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[ISLa] E1[Qa] p[IKRQ]
{"KLRS,ISLa,Pa,IKPR", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[ISLa] E1[Pa] p[IKPR]
{"KLRS,JPKa,aS,LJPR", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JPKa] E1[aS] p[LJPR]
{"KLRS,JPKa,aR,LJPS", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JPKa] E1[aR] p[LJPS]
{"KLRS,JPLa,aS,KJPR", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JPLa] E1[aS] p[KJPR]
{"KLRS,JPLa,aR,KJPS", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JPLa] E1[aR] p[KJPS]
{"KLRS,JQKa,aS,LJRQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JQKa] E1[aS] p[LJRQ]
{"KLRS,JQKa,aR,LJSQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JQKa] E1[aR] p[LJSQ]
{"KLRS,JQLa,aS,KJRQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JQLa] E1[aS] p[KJRQ]
{"KLRS,JQLa,aR,KJSQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JQLa] E1[aR] p[KJSQ]
{"KLRS,JRKa,Qa,LJSQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JRKa] E1[Qa] p[LJSQ]
{"KLRS,JRKa,Pa,LJPS", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JRKa] E1[Pa] p[LJPS]
{"KLRS,JRLa,Qa,KJSQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JRLa] E1[Qa] p[KJSQ]
{"KLRS,JRLa,Pa,KJPS", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JRLa] E1[Pa] p[KJPS]
{"KLRS,JSKa,Qa,LJRQ", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JSKa] E1[Qa] p[LJRQ]
{"KLRS,JSKa,Pa,LJPR", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JSKa] E1[Pa] p[LJPR]
{"KLRS,JSLa,Qa,KJRQ", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JSLa] E1[Qa] p[KJRQ]
{"KLRS,JSLa,Pa,KJPR", -1.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -1.0 W[JSLa] E1[Pa] p[KJPR]
{"KLRS,aPbR,QS,ba,KLPQ", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aPbR] E1[QS] delta[ba] p[KLPQ]
{"KLRS,aPbR,QS,ba,LKPQ", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aPbR] E1[QS] delta[ba] p[LKPQ]
{"KLRS,aPbS,QR,ba,KLPQ", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aPbS] E1[QR] delta[ba] p[KLPQ]
{"KLRS,aPbS,QR,ba,LKPQ", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aPbS] E1[QR] delta[ba] p[LKPQ]
{"KLRS,aQbR,PS,ba,KLPQ", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aQbR] E1[PS] delta[ba] p[KLPQ]
{"KLRS,aQbR,PS,ba,LKPQ", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aQbR] E1[PS] delta[ba] p[LKPQ]
{"KLRS,aQbS,PR,ba,KLPQ", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aQbS] E1[PR] delta[ba] p[KLPQ]
{"KLRS,aQbS,PR,ba,LKPQ", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aQbS] E1[PR] delta[ba] p[LKPQ]
{"KLRS,IRaK,Qa,ILSQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IRaK] E1[Qa] p[ILSQ]
{"KLRS,IRaK,Pa,ILPS", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[IRaK] E1[Pa] p[ILPS]
{"KLRS,IRaL,Qa,IKSQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[IRaL] E1[Qa] p[IKSQ]
{"KLRS,IRaL,Pa,IKPS", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IRaL] E1[Pa] p[IKPS]
{"KLRS,ISaK,Qa,ILRQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[ISaK] E1[Qa] p[ILRQ]
{"KLRS,ISaK,Pa,ILPR", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[ISaK] E1[Pa] p[ILPR]
{"KLRS,ISaL,Qa,IKRQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[ISaL] E1[Qa] p[IKRQ]
{"KLRS,ISaL,Pa,IKPR", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[ISaL] E1[Pa] p[IKPR]
{"KLRS,IaPK,aS,ILPR", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IaPK] E1[aS] p[ILPR]
{"KLRS,IaPK,aR,ILPS", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[IaPK] E1[aR] p[ILPS]
{"KLRS,IaPL,aS,IKPR", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[IaPL] E1[aS] p[IKPR]
{"KLRS,IaPL,aR,IKPS", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IaPL] E1[aR] p[IKPS]
{"KLRS,IaQK,aS,ILRQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[IaQK] E1[aS] p[ILRQ]
{"KLRS,IaQK,aR,ILSQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IaQK] E1[aR] p[ILSQ]
{"KLRS,IaQL,aS,IKRQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IaQL] E1[aS] p[IKRQ]
{"KLRS,IaQL,aR,IKSQ", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[IaQL] E1[aR] p[IKSQ]
{"KLRS,JRaK,Qa,LJSQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[JRaK] E1[Qa] p[LJSQ]
{"KLRS,JRaK,Pa,LJPS", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JRaK] E1[Pa] p[LJPS]
{"KLRS,JRaL,Qa,KJSQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JRaL] E1[Qa] p[KJSQ]
{"KLRS,JRaL,Pa,KJPS", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JRaL] E1[Pa] p[KJPS]
{"KLRS,JSaK,Qa,LJRQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JSaK] E1[Qa] p[LJRQ]
{"KLRS,JSaK,Pa,LJPR", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JSaK] E1[Pa] p[LJPR]
{"KLRS,JSaL,Qa,KJRQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[JSaL] E1[Qa] p[KJRQ]
{"KLRS,JSaL,Pa,KJPR", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JSaL] E1[Pa] p[KJPR]
{"KLRS,JaPK,aS,LJPR", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JaPK] E1[aS] p[LJPR]
{"KLRS,JaPK,aR,LJPS", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JaPK] E1[aR] p[LJPS]
{"KLRS,JaPL,aS,KJPR", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JaPL] E1[aS] p[KJPR]
{"KLRS,JaPL,aR,KJPS", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JaPL] E1[aR] p[KJPS]
{"KLRS,JaQK,aS,LJRQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JaQK] E1[aS] p[LJRQ]
{"KLRS,JaQK,aR,LJSQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[JaQK] E1[aR] p[LJSQ]
{"KLRS,JaQL,aS,KJRQ", -4.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -4.0 W[JaQL] E1[aS] p[KJRQ]
{"KLRS,JaQL,aR,KJSQ", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JaQL] E1[aR] p[KJSQ]
{"KLRS,aRPb,QS,ba,KLPQ", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[aRPb] E1[QS] delta[ba] p[KLPQ]
{"KLRS,aRPb,QS,ba,LKPQ", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[aRPb] E1[QS] delta[ba] p[LKPQ]
{"KLRS,aRQb,PS,ba,KLPQ", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[aRQb] E1[PS] delta[ba] p[KLPQ]
{"KLRS,aRQb,PS,ba,LKPQ", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[aRQb] E1[PS] delta[ba] p[LKPQ]
{"KLRS,aSPb,QR,ba,KLPQ", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[aSPb] E1[QR] delta[ba] p[KLPQ]
{"KLRS,aSPb,QR,ba,LKPQ", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[aSPb] E1[QR] delta[ba] p[LKPQ]
{"KLRS,aSQb,PR,ba,KLPQ", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[aSQb] E1[PR] delta[ba] p[KLPQ]
{"KLRS,aSQb,PR,ba,LKPQ", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[aSQb] E1[PR] delta[ba] p[LKPQ]
{"KLRS,Pa,aS,KLPR", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[Pa] E1[aS] p[KLPR]
{"KLRS,Pa,aS,LKPR", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[Pa] E1[aS] p[LKPR]
{"KLRS,Pa,aR,KLPS", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[Pa] E1[aR] p[KLPS]
{"KLRS,Pa,aR,LKPS", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[Pa] E1[aR] p[LKPS]
{"KLRS,Qa,aS,KLRQ", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[Qa] E1[aS] p[KLRQ]
{"KLRS,Qa,aS,LKRQ", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[Qa] E1[aS] p[LKRQ]
{"KLRS,Qa,aR,KLSQ", 1.0 , 4, {22,3,14,21}}, //Ap[KLRS] += 1.0 k[Qa] E1[aR] p[KLSQ]
{"KLRS,Qa,aR,LKSQ", -2.0 , 4, {22,3,14,21}}, //Ap[KLRS] += -2.0 k[Qa] E1[aR] p[LKSQ]
{"KLRS,PRab,ab,KLPS", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PRab] E1[ab] p[KLPS]
{"KLRS,PRab,ab,LKPS", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PRab] E1[ab] p[LKPS]
{"KLRS,PSab,ab,KLPR", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[PSab] E1[ab] p[KLPR]
{"KLRS,PSab,ab,LKPR", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PSab] E1[ab] p[LKPR]
{"KLRS,PaRb,ab,KLPS", 4.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 4.0 W[PaRb] E1[ab] p[KLPS]
{"KLRS,PaRb,ab,LKPS", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PaRb] E1[ab] p[LKPS]
{"KLRS,PaSb,ab,KLPR", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[PaSb] E1[ab] p[KLPR]
{"KLRS,PaSb,ab,LKPR", 4.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 4.0 W[PaSb] E1[ab] p[LKPR]
{"KLRS,QRab,ab,KLSQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[QRab] E1[ab] p[KLSQ]
{"KLRS,QRab,ab,LKSQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[QRab] E1[ab] p[LKSQ]
{"KLRS,QSab,ab,KLRQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[QSab] E1[ab] p[KLRQ]
{"KLRS,QSab,ab,LKRQ", 1.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 1.0 W[QSab] E1[ab] p[LKRQ]
{"KLRS,QaRb,ab,KLSQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[QaRb] E1[ab] p[KLSQ]
{"KLRS,QaRb,ab,LKSQ", 4.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 4.0 W[QaRb] E1[ab] p[LKSQ]
{"KLRS,QaSb,ab,KLRQ", 4.0 , 4, {22,12,14,21}}, //Ap[KLRS] += 4.0 W[QaSb] E1[ab] p[KLRQ]
{"KLRS,QaSb,ab,LKRQ", -2.0 , 4, {22,12,14,21}}, //Ap[KLRS] += -2.0 W[QaSb] E1[ab] p[LKRQ]
{"KLRS,IaKb,ab,ILRS", -4.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -4.0 W[IaKb] E1[ab] p[ILRS]
{"KLRS,IaKb,ab,ILSR", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IaKb] E1[ab] p[ILSR]
{"KLRS,IaLb,ab,IKRS", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[IaLb] E1[ab] p[IKRS]
{"KLRS,IaLb,ab,IKSR", -4.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -4.0 W[IaLb] E1[ab] p[IKSR]
{"KLRS,JaKb,ab,LJRS", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JaKb] E1[ab] p[LJRS]
{"KLRS,JaKb,ab,LJSR", -4.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -4.0 W[JaKb] E1[ab] p[LJSR]
{"KLRS,JaLb,ab,KJRS", -4.0 , 4, {22,5,14,21}}, //Ap[KLRS] += -4.0 W[JaLb] E1[ab] p[KJRS]
{"KLRS,JaLb,ab,KJSR", 2.0 , 4, {22,5,14,21}}, //Ap[KLRS] += 2.0 W[JaLb] E1[ab] p[KJSR]
{"KLRS,aPcb,bS,ca,KLPR", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aPcb] E1[bS] delta[ca] p[KLPR]
{"KLRS,aPcb,bS,ca,LKPR", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aPcb] E1[bS] delta[ca] p[LKPR]
{"KLRS,aPcb,bR,ca,KLPS", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aPcb] E1[bR] delta[ca] p[KLPS]
{"KLRS,aPcb,bR,ca,LKPS", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aPcb] E1[bR] delta[ca] p[LKPS]
{"KLRS,aQcb,bS,ca,KLRQ", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aQcb] E1[bS] delta[ca] p[KLRQ]
{"KLRS,aQcb,bS,ca,LKRQ", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aQcb] E1[bS] delta[ca] p[LKRQ]
{"KLRS,aQcb,bR,ca,KLSQ", 2.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += 2.0 W[aQcb] E1[bR] delta[ca] p[KLSQ]
{"KLRS,aQcb,bR,ca,LKSQ", -4.0 , 5, {22,5,14,27,21}}, //Ap[KLRS] += -4.0 W[aQcb] E1[bR] delta[ca] p[LKSQ]
{"KLRS,IabK,ab,ILRS", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IabK] E1[ab] p[ILRS]
{"KLRS,IabK,ab,ILSR", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[IabK] E1[ab] p[ILSR]
{"KLRS,IabL,ab,IKRS", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[IabL] E1[ab] p[IKRS]
{"KLRS,IabL,ab,IKSR", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[IabL] E1[ab] p[IKSR]
{"KLRS,JabK,ab,LJRS", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JabK] E1[ab] p[LJRS]
{"KLRS,JabK,ab,LJSR", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JabK] E1[ab] p[LJSR]
{"KLRS,JabL,ab,KJRS", 2.0 , 4, {22,6,14,21}}, //Ap[KLRS] += 2.0 W[JabL] E1[ab] p[KJRS]
{"KLRS,JabL,ab,KJSR", -1.0 , 4, {22,6,14,21}}, //Ap[KLRS] += -1.0 W[JabL] E1[ab] p[KJSR]
{"KLRS,abPc,bS,ca,KLPR", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[abPc] E1[bS] delta[ca] p[KLPR]
{"KLRS,abPc,bS,ca,LKPR", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[abPc] E1[bS] delta[ca] p[LKPR]
{"KLRS,abPc,bR,ca,KLPS", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[abPc] E1[bR] delta[ca] p[KLPS]
{"KLRS,abPc,bR,ca,LKPS", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[abPc] E1[bR] delta[ca] p[LKPS]
{"KLRS,abQc,bS,ca,KLRQ", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[abQc] E1[bS] delta[ca] p[KLRQ]
{"KLRS,abQc,bS,ca,LKRQ", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[abQc] E1[bS] delta[ca] p[LKRQ]
{"KLRS,abQc,bR,ca,KLSQ", -1.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += -1.0 W[abQc] E1[bR] delta[ca] p[KLSQ]
{"KLRS,abQc,bR,ca,LKSQ", 2.0 , 5, {22,6,14,27,21}}, //Ap[KLRS] += 2.0 W[abQc] E1[bR] delta[ca] p[LKSQ]
{"KLRS,IJKL,PQRS,IJPQ", 1.0 , 4, {22,11,15,21}}, //Ap[KLRS] += 1.0 W[IJKL] E2[PQRS] p[IJPQ]
{"KLRS,IJLK,PQSR,IJPQ", 1.0 , 4, {22,11,15,21}}, //Ap[KLRS] += 1.0 W[IJLK] E2[PQSR] p[IJPQ]
{"KLRS,IK,PQRS,ILPQ", -1.0 , 4, {22,2,15,21}}, //Ap[KLRS] += -1.0 k[IK] E2[PQRS] p[ILPQ]
{"KLRS,IL,PQSR,IKPQ", -1.0 , 4, {22,2,15,21}}, //Ap[KLRS] += -1.0 k[IL] E2[PQSR] p[IKPQ]
{"KLRS,JK,PQSR,LJPQ", -1.0 , 4, {22,2,15,21}}, //Ap[KLRS] += -1.0 k[JK] E2[PQSR] p[LJPQ]
{"KLRS,JL,PQRS,KJPQ", -1.0 , 4, {22,2,15,21}}, //Ap[KLRS] += -1.0 k[JL] E2[PQRS] p[KJPQ]
{"KLRS,IKab,PQRS,ba,ILPQ", 1.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += 1.0 W[IKab] E2[PQRS] delta[ba] p[ILPQ]
{"KLRS,ILab,PQSR,ba,IKPQ", 1.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += 1.0 W[ILab] E2[PQSR] delta[ba] p[IKPQ]
{"KLRS,IaKb,PQRS,ba,ILPQ", -2.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += -2.0 W[IaKb] E2[PQRS] delta[ba] p[ILPQ]
{"KLRS,IaLb,PQSR,ba,IKPQ", -2.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += -2.0 W[IaLb] E2[PQSR] delta[ba] p[IKPQ]
{"KLRS,JKab,PQSR,ba,LJPQ", 1.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += 1.0 W[JKab] E2[PQSR] delta[ba] p[LJPQ]
{"KLRS,JLab,PQRS,ba,KJPQ", 1.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += 1.0 W[JLab] E2[PQRS] delta[ba] p[KJPQ]
{"KLRS,JaKb,PQSR,ba,LJPQ", -2.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += -2.0 W[JaKb] E2[PQSR] delta[ba] p[LJPQ]
{"KLRS,JaLb,PQRS,ba,KJPQ", -2.0 , 5, {22,11,15,27,21}}, //Ap[KLRS] += -2.0 W[JaLb] E2[PQRS] delta[ba] p[KJPQ]
{"KLRS,IPKa,QaSR,ILPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IPKa] E2[QaSR] p[ILPQ]
{"KLRS,IPLa,QaRS,IKPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IPLa] E2[QaRS] p[IKPQ]
{"KLRS,IQKa,PaRS,ILPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IQKa] E2[PaRS] p[ILPQ]
{"KLRS,IQLa,PaSR,IKPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IQLa] E2[PaSR] p[IKPQ]
{"KLRS,IRKa,PQaS,ILPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IRKa] E2[PQaS] p[ILPQ]
{"KLRS,IRLa,PQSa,IKPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IRLa] E2[PQSa] p[IKPQ]
{"KLRS,ISKa,PQRa,ILPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[ISKa] E2[PQRa] p[ILPQ]
{"KLRS,ISLa,PQaR,IKPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[ISLa] E2[PQaR] p[IKPQ]
{"KLRS,JPKa,QaRS,LJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JPKa] E2[QaRS] p[LJPQ]
{"KLRS,JPLa,QaSR,KJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JPLa] E2[QaSR] p[KJPQ]
{"KLRS,JQKa,PaSR,LJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JQKa] E2[PaSR] p[LJPQ]
{"KLRS,JQLa,PaRS,KJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JQLa] E2[PaRS] p[KJPQ]
{"KLRS,JRKa,PQSa,LJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JRKa] E2[PQSa] p[LJPQ]
{"KLRS,JRLa,PQaS,KJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JRLa] E2[PQaS] p[KJPQ]
{"KLRS,JSKa,PQaR,LJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JSKa] E2[PQaR] p[LJPQ]
{"KLRS,JSLa,PQRa,KJPQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JSLa] E2[PQRa] p[KJPQ]
{"KLRS,IRaK,PQaS,ILPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[IRaK] E2[PQaS] p[ILPQ]
{"KLRS,IRaL,PQaS,IKPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IRaL] E2[PQaS] p[IKPQ]
{"KLRS,ISaK,PQaR,ILPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[ISaK] E2[PQaR] p[ILPQ]
{"KLRS,ISaL,PQaR,IKPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[ISaL] E2[PQaR] p[IKPQ]
{"KLRS,IaPK,QaSR,ILPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[IaPK] E2[QaSR] p[ILPQ]
{"KLRS,IaPL,QaRS,IKPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[IaPL] E2[QaRS] p[IKPQ]
{"KLRS,IaQK,PaSR,ILPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IaQK] E2[PaSR] p[ILPQ]
{"KLRS,IaQL,PaRS,IKPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IaQL] E2[PaRS] p[IKPQ]
{"KLRS,JRaK,PQSa,LJPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[JRaK] E2[PQSa] p[LJPQ]
{"KLRS,JRaL,PQSa,KJPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JRaL] E2[PQSa] p[KJPQ]
{"KLRS,JSaK,PQRa,LJPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JSaK] E2[PQRa] p[LJPQ]
{"KLRS,JSaL,PQRa,KJPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[JSaL] E2[PQRa] p[KJPQ]
{"KLRS,JaPK,QaSR,LJPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JaPK] E2[QaSR] p[LJPQ]
{"KLRS,JaPL,QaRS,KJPQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JaPL] E2[QaRS] p[KJPQ]
{"KLRS,JaQK,PaSR,LJPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[JaQK] E2[PaSR] p[LJPQ]
{"KLRS,JaQL,PaRS,KJPQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[JaQL] E2[PaRS] p[KJPQ]
{"KLRS,Pa,QaSR,KLPQ", 1.0 , 4, {22,3,15,21}}, //Ap[KLRS] += 1.0 k[Pa] E2[QaSR] p[KLPQ]
{"KLRS,Pa,QaRS,LKPQ", 1.0 , 4, {22,3,15,21}}, //Ap[KLRS] += 1.0 k[Pa] E2[QaRS] p[LKPQ]
{"KLRS,Qa,PaRS,KLPQ", 1.0 , 4, {22,3,15,21}}, //Ap[KLRS] += 1.0 k[Qa] E2[PaRS] p[KLPQ]
{"KLRS,Qa,PaSR,LKPQ", 1.0 , 4, {22,3,15,21}}, //Ap[KLRS] += 1.0 k[Qa] E2[PaSR] p[LKPQ]
{"KLRS,PQab,abRS,KLPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PQab] E2[abRS] p[KLPQ]
{"KLRS,PQab,abSR,LKPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PQab] E2[abSR] p[LKPQ]
{"KLRS,PRab,QaSb,KLPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PRab] E2[QaSb] p[KLPQ]
{"KLRS,PRab,QabS,LKPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PRab] E2[QabS] p[LKPQ]
{"KLRS,PSab,QabR,KLPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PSab] E2[QabR] p[KLPQ]
{"KLRS,PSab,QaRb,LKPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PSab] E2[QaRb] p[LKPQ]
{"KLRS,PaRb,QaSb,KLPQ", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[PaRb] E2[QaSb] p[KLPQ]
{"KLRS,PaRb,QaSb,LKPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PaRb] E2[QaSb] p[LKPQ]
{"KLRS,PaSb,QaRb,KLPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[PaSb] E2[QaRb] p[KLPQ]
{"KLRS,PaSb,QaRb,LKPQ", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[PaSb] E2[QaRb] p[LKPQ]
{"KLRS,QRab,PabS,KLPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[QRab] E2[PabS] p[KLPQ]
{"KLRS,QRab,PaSb,LKPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[QRab] E2[PaSb] p[LKPQ]
{"KLRS,QSab,PaRb,KLPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[QSab] E2[PaRb] p[KLPQ]
{"KLRS,QSab,PabR,LKPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[QSab] E2[PabR] p[LKPQ]
{"KLRS,QaRb,PaSb,KLPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[QaRb] E2[PaSb] p[KLPQ]
{"KLRS,QaRb,PaSb,LKPQ", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[QaRb] E2[PaSb] p[LKPQ]
{"KLRS,QaSb,PaRb,KLPQ", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[QaSb] E2[PaRb] p[KLPQ]
{"KLRS,QaSb,PaRb,LKPQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[QaSb] E2[PaRb] p[LKPQ]
{"KLRS,IaKb,QaSb,ILRQ", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[IaKb] E2[QaSb] p[ILRQ]
{"KLRS,IaKb,QaRb,ILSQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IaKb] E2[QaRb] p[ILSQ]
{"KLRS,IaKb,PaSb,ILPR", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IaKb] E2[PaSb] p[ILPR]
{"KLRS,IaKb,PaRb,ILPS", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[IaKb] E2[PaRb] p[ILPS]
{"KLRS,IaLb,QaSb,IKRQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IaLb] E2[QaSb] p[IKRQ]
{"KLRS,IaLb,QaRb,IKSQ", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[IaLb] E2[QaRb] p[IKSQ]
{"KLRS,IaLb,PaSb,IKPR", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[IaLb] E2[PaSb] p[IKPR]
{"KLRS,IaLb,PaRb,IKPS", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[IaLb] E2[PaRb] p[IKPS]
{"KLRS,JaKb,QaSb,LJRQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JaKb] E2[QaSb] p[LJRQ]
{"KLRS,JaKb,QaRb,LJSQ", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[JaKb] E2[QaRb] p[LJSQ]
{"KLRS,JaKb,PaSb,LJPR", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[JaKb] E2[PaSb] p[LJPR]
{"KLRS,JaKb,PaRb,LJPS", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JaKb] E2[PaRb] p[LJPS]
{"KLRS,JaLb,QaSb,KJRQ", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[JaLb] E2[QaSb] p[KJRQ]
{"KLRS,JaLb,QaRb,KJSQ", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JaLb] E2[QaRb] p[KJSQ]
{"KLRS,JaLb,PaSb,KJPR", -1.0 , 4, {22,5,15,21}}, //Ap[KLRS] += -1.0 W[JaLb] E2[PaSb] p[KJPR]
{"KLRS,JaLb,PaRb,KJPS", 2.0 , 4, {22,5,15,21}}, //Ap[KLRS] += 2.0 W[JaLb] E2[PaRb] p[KJPS]
{"KLRS,aPcb,QbSR,ca,KLPQ", 2.0 , 5, {22,5,15,27,21}}, //Ap[KLRS] += 2.0 W[aPcb] E2[QbSR] delta[ca] p[KLPQ]
{"KLRS,aPcb,QbRS,ca,LKPQ", 2.0 , 5, {22,5,15,27,21}}, //Ap[KLRS] += 2.0 W[aPcb] E2[QbRS] delta[ca] p[LKPQ]
{"KLRS,aQcb,PbRS,ca,KLPQ", 2.0 , 5, {22,5,15,27,21}}, //Ap[KLRS] += 2.0 W[aQcb] E2[PbRS] delta[ca] p[KLPQ]
{"KLRS,aQcb,PbSR,ca,LKPQ", 2.0 , 5, {22,5,15,27,21}}, //Ap[KLRS] += 2.0 W[aQcb] E2[PbSR] delta[ca] p[LKPQ]
{"KLRS,IabK,QaSb,ILRQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IabK] E2[QaSb] p[ILRQ]
{"KLRS,IabK,QabR,ILSQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IabK] E2[QabR] p[ILSQ]
{"KLRS,IabK,PabS,ILPR", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IabK] E2[PabS] p[ILPR]
{"KLRS,IabK,PabR,ILPS", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[IabK] E2[PabR] p[ILPS]
{"KLRS,IabL,QabS,IKRQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IabL] E2[QabS] p[IKRQ]
{"KLRS,IabL,QaRb,IKSQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IabL] E2[QaRb] p[IKSQ]
{"KLRS,IabL,PabS,IKPR", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[IabL] E2[PabS] p[IKPR]
{"KLRS,IabL,PabR,IKPS", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[IabL] E2[PabR] p[IKPS]
{"KLRS,JabK,QabS,LJRQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JabK] E2[QabS] p[LJRQ]
{"KLRS,JabK,QabR,LJSQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[JabK] E2[QabR] p[LJSQ]
{"KLRS,JabK,PaSb,LJPR", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JabK] E2[PaSb] p[LJPR]
{"KLRS,JabK,PabR,LJPS", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JabK] E2[PabR] p[LJPS]
{"KLRS,JabL,QabS,KJRQ", 2.0 , 4, {22,6,15,21}}, //Ap[KLRS] += 2.0 W[JabL] E2[QabS] p[KJRQ]
{"KLRS,JabL,QabR,KJSQ", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JabL] E2[QabR] p[KJSQ]
{"KLRS,JabL,PabS,KJPR", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JabL] E2[PabS] p[KJPR]
{"KLRS,JabL,PaRb,KJPS", -1.0 , 4, {22,6,15,21}}, //Ap[KLRS] += -1.0 W[JabL] E2[PaRb] p[KJPS]
{"KLRS,abPc,QbSR,ca,KLPQ", -1.0 , 5, {22,6,15,27,21}}, //Ap[KLRS] += -1.0 W[abPc] E2[QbSR] delta[ca] p[KLPQ]
{"KLRS,abPc,QbRS,ca,LKPQ", -1.0 , 5, {22,6,15,27,21}}, //Ap[KLRS] += -1.0 W[abPc] E2[QbRS] delta[ca] p[LKPQ]
{"KLRS,abQc,PbRS,ca,KLPQ", -1.0 , 5, {22,6,15,27,21}}, //Ap[KLRS] += -1.0 W[abQc] E2[PbRS] delta[ca] p[KLPQ]
{"KLRS,abQc,PbSR,ca,LKPQ", -1.0 , 5, {22,6,15,27,21}}, //Ap[KLRS] += -1.0 W[abQc] E2[PbSR] delta[ca] p[LKPQ]
{"KLRS,Pabc,abcS,KLPR", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[Pabc] E2[abcS] p[KLPR]
{"KLRS,Pabc,abcS,LKPR", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[Pabc] E2[abcS] p[LKPR]
{"KLRS,Pabc,abcR,KLPS", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[Pabc] E2[abcR] p[KLPS]
{"KLRS,Pabc,abcR,LKPS", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[Pabc] E2[abcR] p[LKPS]
{"KLRS,Qabc,abcS,KLRQ", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[Qabc] E2[abcS] p[KLRQ]
{"KLRS,Qabc,abcS,LKRQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[Qabc] E2[abcS] p[LKRQ]
{"KLRS,Qabc,abcR,KLSQ", 1.0 , 4, {22,12,15,21}}, //Ap[KLRS] += 1.0 W[Qabc] E2[abcR] p[KLSQ]
{"KLRS,Qabc,abcR,LKSQ", -2.0 , 4, {22,12,15,21}}, //Ap[KLRS] += -2.0 W[Qabc] E2[abcR] p[LKSQ]
/*
{"KLRS,IaKb,PQaRSb,ILPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[IaKb] E3[PQaRSb] p[ILPQ]
{"KLSR,IaLb,PQaRSb,IKPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[IaLb] E3[PQaSRb] p[IKPQ]
{"KLSR,JaKb,PQaRSb,LJPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[JaKb] E3[PQaSRb] p[LJPQ]
{"KLRS,JaLb,PQaRSb,KJPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[JaLb] E3[PQaRSb] p[KJPQ]
{"KLbS,KIaR,PQaRSb,ILPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[IabK] E3[PQabSR] p[ILPQ]
{"KLSb,LIaR,PQaRSb,IKPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[IabL] E3[PQabRS] p[IKPQ]
{"KLbR,KJaS,PQaRSb,LJPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[JabK] E3[PQaSbR] p[LJPQ]
{"KLRb,LJaS,PQaRSb,KJPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[JabL] E3[PQaRbS] p[KJPQ]
{"KLcR,PabS,QabRSc,KLPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabScR] p[KLPQ]
{"KLRc,PabS,QabRSc,LKPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabRcS] p[LKPQ]
{"KLRc,QabS,PabRSc,KLPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabRcS] p[KLPQ]
{"KLcR,QabS,PabRSc,LKPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabScR] p[LKPQ]
*/
};
FEqInfo Overlap[14] = {
{"KLRS,PR,KLPS", 2.0 , 3, {20,28,26}}, //b[KLRS] += 2.0 delta[PR] V[KLPS]
{"KLRS,PR,LKPS", -1.0 , 3, {20,28,26}}, //b[KLRS] += -1.0 delta[PR] V[LKPS]
{"KLRS,PS,KLPR", -1.0 , 3, {20,28,26}}, //b[KLRS] += -1.0 delta[PS] V[KLPR]
{"KLRS,PS,LKPR", 2.0 , 3, {20,28,26}}, //b[KLRS] += 2.0 delta[PS] V[LKPR]
{"KLRS,QS,KLRQ", -1.0 , 3, {20,14,26}}, //b[KLRS] += -1.0 E1[QS] V[KLRQ]
{"KLRS,QS,LKRQ", 0.5 , 3, {20,14,26}}, //b[KLRS] += 0.5 E1[QS] V[LKRQ]
{"KLRS,QR,KLSQ", 0.5 , 3, {20,14,26}}, //b[KLRS] += 0.5 E1[QR] V[KLSQ]
{"KLRS,QR,LKSQ", -1.0 , 3, {20,14,26}}, //b[KLRS] += -1.0 E1[QR] V[LKSQ]
{"KLRS,PS,KLPR", 0.5 , 3, {20,14,26}}, //b[KLRS] += 0.5 E1[PS] V[KLPR]
{"KLRS,PS,LKPR", -1.0 , 3, {20,14,26}}, //b[KLRS] += -1.0 E1[PS] V[LKPR]
{"KLRS,PR,KLPS", -1.0 , 3, {20,14,26}}, //b[KLRS] += -1.0 E1[PR] V[KLPS]
{"KLRS,PR,LKPS", 0.5 , 3, {20,14,26}}, //b[KLRS] += 0.5 E1[PR] V[LKPS]
{"KLRS,PQRS,KLPQ", 0.5 , 3, {20,15,26}}, //b[KLRS] += 0.5 E2[PQRS] V[KLPQ]
{"KLRS,PQSR,LKPQ", 0.5 , 3, {20,15,26}}, //b[KLRS] += 0.5 E2[PQSR] V[LKPQ]
};
FEqInfo MakeS1[7] = {
{"PQRS,PR,QS", 4.0 , 3, {17,28,28}}, //S1[PQRS] += 4.0 delta[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PS,QR", -2.0 , 3, {17,28,28}}, //S1[PQRS] += -2.0 delta[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,QS,PR", -2.0 , 3, {17,14,28}}, //S1[PQRS] += -2.0 E1[QS] delta[PR] delta[IK] delta[JL] []
{"PQRS,QR,PS", 1.0 , 3, {17,14,28}}, //S1[PQRS] += 1.0 E1[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,PS,QR", 1.0 , 3, {17,14,28}}, //S1[PQRS] += 1.0 E1[QS] delta[PR] delta[IL] delta[JK] []
{"PQRS,PR,QS", -2.0 , 3, {17,14,28}}, //S1[PQRS] += -2.0 E1[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PQRT,TS", 1.0 , 3, {17,15,28}}, //S1[PQRS] += 1.0 E2[PQRS] delta[IK] delta[JL] []
};
FEqInfo MakeS2[14] = {
{"PQRS,PR,QS", 4.0 , 5, {18,28,28}}, //S1[PQRS] += 4.0 delta[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PR,QS", -2.0 , 5, {18,28,28}}, //S1[PQRS] += -2.0 delta[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,PS,QR", -2.0 , 5, {18,28,28}}, //S1[PQRS] += -2.0 delta[PS] delta[QR] delta[IK] delta[JL] []
{"PQRS,PS,QR", 4.0 , 5, {18,28,28}}, //S1[PQRS] += 4.0 delta[PS] delta[QR] delta[IL] delta[JK] []
{"PQRS,QS,PR", -2.0 , 5, {18,14,28}}, //S1[PQRS] += -2.0 E1[QS] delta[PR] delta[IK] delta[JL] []
{"PQRS,QS,PR", 1.0 , 5, {18,14,28}}, //S1[PQRS] += 1.0 E1[QS] delta[PR] delta[IL] delta[JK] []
{"PQRS,QR,PS", 1.0 , 5, {18,14,28}}, //S1[PQRS] += 1.0 E1[QR] delta[PS] delta[IK] delta[JL] []
{"PQRS,QR,PS", -2.0 , 5, {18,14,28}}, //S1[PQRS] += -2.0 E1[QR] delta[PS] delta[IL] delta[JK] []
{"PQRS,PS,QR", 1.0 , 5, {18,14,28}}, //S1[PQRS] += 1.0 E1[PS] delta[QR] delta[IK] delta[JL] []
{"PQRS,PS,QR", -2.0 , 5, {18,14,28}}, //S1[PQRS] += -2.0 E1[PS] delta[QR] delta[IL] delta[JK] []
{"PQRS,PR,QS", -2.0 , 5, {18,14,28}}, //S1[PQRS] += -2.0 E1[PR] delta[QS] delta[IK] delta[JL] []
{"PQRS,PR,QS", 1.0 , 5, {18,14,28}}, //S1[PQRS] += 1.0 E1[PR] delta[QS] delta[IL] delta[JK] []
{"PQRS,PQRT,TS", 1.0 , 4, {18,15,28}}, //S1[PQRS] += 1.0 E2[PQRS] delta[IK] delta[JL] []
{"PQRS,PQTR,TS", 1.0 , 4, {18,15,28}}, //S1[PQRS] += 1.0 E2[PQSR] delta[IL] delta[JK] []
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "MRLCC_CCAA";
Out.perturberClass = "CCAA";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 43;
Out.nDomainDecls = 0;
Out.EqsHandCode = FEqSet(&EqsHandCode[0], 12, "MRLCC_CCAA/Res");
Out.EqsRes = FEqSet(&EqsRes[0], 452, "MRLCC_CCAA/Res");
Out.Overlap = FEqSet(&Overlap[0], 14, "MRLCC_CCAA/Overlap");
Out.MakeS1 = FEqSet(&MakeS1[0], 7, "MRLCC_CCAA/Overlap");
Out.MakeS2 = FEqSet(&MakeS2[0], 14, "MRLCC_CCAA/Overlap");
};
};
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NNBSWalker_HEADER_H
#define NNBSWalker_HEADER_H
#include "input.h"
#include "Determinants.h"
#include "global.h"
#include "fnn.h"
#include "igl/slice.h"
using namespace Eigen;
/**
Vector of Jastrow-Slater walkers to work with the PermutedWavefunction
*
*/
class NNBSWalker
{
public:
Determinant det;
VectorXd occ; // same as det but a vector of +1 and -1 instead of bits
MatrixXd occSlice; // occupied slice of coefficient matrix, for wave function evaluation
MatrixXd occSliceInv; // for wave function derivatives
// constructors
// default
NNBSWalker(){};
// the following constructors are used by the wave function initWalker function
// for deterministic
NNBSWalker(MatrixXd& moCoeffs, Determinant &pd)
{
det = pd;
int norbs = Determinant::norbs;
int nelec = Determinant::nalpha + Determinant::nbeta;
occ = VectorXd::Zero(2*norbs);
for (int i = 0; i < norbs; i++) {
occ[i] = pd.getoccA(i) ? 1. : -1.;
occ[norbs + i] = pd.getoccB(i) ? 1. : -1.;
}
vector<int> openOrbs, closedOrbs;
vector<int> closedBeta, openBeta;
det.getOpenClosedAlphaBeta(openOrbs, closedOrbs, openBeta, closedBeta);
for (int& c_i : closedBeta) c_i += Determinant::norbs;
closedOrbs.insert(closedOrbs.end(), closedBeta.begin(), closedBeta.end());
Eigen::Map<VectorXi> occRows(&closedOrbs[0], closedOrbs.size());
VectorXi occColumns = VectorXi::LinSpaced(nelec, 0, nelec - 1);
igl::slice(moCoeffs, occRows, occColumns, occSlice);
};
NNBSWalker(MatrixXd& moCoeffs)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
int nelec = nalpha + nbeta;
char file[5000];
sprintf(file, "BestDeterminant.txt");
ifstream ofile(file);
if (ofile) {// read bestdet from prev run
if (commrank == 0) {
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> det;
}
#ifndef SERIAL
MPI_Bcast(&det.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&det.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
else {// guess or read given
det = Determinant();
if (boost::iequals(schd.determinantFile, "")) {
// choose alpha occupations randomly
std::vector<int> bitmask(nalpha, 1);
bitmask.resize(norbs, 0); // N-K trailing 0's
vector<int> comb;
random_shuffle(bitmask.begin(), bitmask.end());
for (int i = 0; i < norbs; i++) {
if (bitmask[i] == 1) det.setoccA(i, true);
}
// fill beta, trying to avoid occupied alphas as much as possible
int nbetaFilled = 0;
// first pass, only fill empty orbs
for (int i = 0; i < norbs; i++) {
if (nbetaFilled == nbeta) break;
if (bitmask[i] == 0) { // empty
det.setoccB(i, true);
nbetaFilled++;
}
}
// if betas leftover, fill sequentially
if (nbetaFilled < nbeta) {
for (int i = 0; i < norbs; i++) {
if (nbetaFilled == nbeta) break;
if (bitmask[i] == 1) {// alpha occupied
det.setoccB(i, true);
nbetaFilled++;
}
}
}
}
else if (boost::iequals(schd.determinantFile, "bestDet")) {
std::vector<Determinant> dets;
std::vector<double> ci;
readDeterminants(schd.determinantFile, dets, ci);
det = dets[0];
}
}
occ = VectorXd::Zero(2*norbs);
for (int i = 0; i < norbs; i++) {
occ[i] = det.getoccA(i) ? 1. : -1.;
occ[norbs + i] = det.getoccB(i) ? 1. : -1.;
}
vector<int> openOrbs, closedOrbs;
vector<int> closedBeta, openBeta;
det.getOpenClosedAlphaBeta(openOrbs, closedOrbs, openBeta, closedBeta);
for (int& c_i : closedBeta) c_i += Determinant::norbs;
closedOrbs.insert(closedOrbs.end(), closedBeta.begin(), closedBeta.end());
Eigen::Map<VectorXi> occRows(&closedOrbs[0], closedOrbs.size());
VectorXi occColumns = VectorXi::LinSpaced(nelec, 0, nelec - 1);
igl::slice(moCoeffs, occRows, occColumns, occSlice);
};
// this is used for storing bestDet
Determinant getDet() { return det; }
// used during sampling
void updateWalker(const MatrixXd &moCoeffs, const fnn &fnnb, int ex1, int ex2, bool doparity = true)
{
int norbs = Determinant::norbs;
int nelec = Determinant::nalpha + Determinant::nbeta;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
int i = I / 2, a = A / 2;
int j = J / 2, b = B / 2;
int sz1 = I%2, sz2 = J%2;
det.setocc(i, sz1, false);
det.setocc(a, sz1, true);
occ[sz1 * norbs + i] = -1.;
occ[sz1 * norbs + a] = 1.;
if (ex2 != 0) {
det.setocc(j, sz2, false);
det.setocc(b, sz2, true);
occ[sz2 * norbs + j] = -1.;
occ[sz2 * norbs + b] = 1.;
}
vector<int> openOrbs, closedOrbs;
vector<int> closedBeta, openBeta;
det.getOpenClosedAlphaBeta(openOrbs, closedOrbs, openBeta, closedBeta);
for (int& c_i : closedBeta) c_i += Determinant::norbs;
closedOrbs.insert(closedOrbs.end(), closedBeta.begin(), closedBeta.end());
Eigen::Map<VectorXi> occRows(&closedOrbs[0], closedOrbs.size());
VectorXi occColumns = VectorXi::LinSpaced(nelec, 0, nelec - 1);
igl::slice(moCoeffs, occRows, occColumns, occSlice);
}
//to be defined for metropolis
void update(int i, int a, bool sz, const MatrixXd &ref, const fnn &corr) { return; };
// used for debugging
friend ostream& operator<<(ostream& os, const NNBSWalker& w) {
os << "det " << w.det << endl;
os << "occ\n" << w.occ << endl << endl;
os << "occSlice\n" << w.occSlice << endl << endl;
return os;
}
};
#endif
<file_sep>import numpy as np
import sys, os, climin.amsgrad, scipy
from functools import reduce
from subprocess import check_output, check_call, CalledProcessError
import conjgrad as cj
def getopts(argv):
opts = {} # Empty dictionary to store key-value pairs.
while argv: # While there are arguments left to parse...
if argv[0][0] == '-': # Found a "-name value" pair.
opts[argv[0]] = argv[1] # Add key and value to the dictionary.
argv = argv[1:] # Reduce the argument list by copying it starting from index 1.
return opts
m_stepsize = 0.001
m_decay_mom1 = 0.1
m_decay_mom2 = 0.001
T = 0.001
mpiprefix = " mpirun "
executable = "/Users/sandeepsharma/Academics/Programs/VMC/bin/PythonInterface"
myargs = getopts(sys.argv)
if '-i' in myargs:
inFile = myargs['-i']
if '-n' in myargs:
numprocs = int(myargs['-n'])
mpiprefix = "mpirun -n %i"%(numprocs)
if '-stepsize' in myargs:
m_stepsize = float(myargs['-stepsize'])
if '-decay1' in myargs:
m_decay_mom1 = float(myargs['-decay1'])
if '-decay2' in myargs:
m_decay_mom2 = float(myargs['-decay2'])
if '-T' in myargs:
T = float(myargs['-T'])
f = open(inFile, 'r')
correlatorSize, numCorrelators = 0, 0
Restart = False
ciExpansion = []
doHessian = False
sr = False
gd = False
maxIter = 1000
numVars = 0
UHF = False
optvar = False
print "#*********INPUT FILE"
for line in f:
linesp = line.split();
print "#", line,
#read the correlator file to determine the number of jastrow factors
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "correlator"):
correlatorFile = linesp[2]
correlatorSize = int(linesp[1])
numCorrelators = 0
#print linesp, correlatorFile
f2 = open(correlatorFile, 'r')
for line2 in f2:
if (line2.strip(' \n') != ''):
numCorrelators += 1
numVars += numCorrelators*2**(2*correlatorSize)
elif ( len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "restart"):
Restart = True
#read the determinant file to see the number of determinants
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "determinants"):
determinantFile = linesp[1]
f2 = open(determinantFile, 'r')
for line2 in f2:
if (line2.strip(' \n') != ''):
tok = line2.split()
ciExpansion.append(float(tok[0]))
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "uhf"):
UHF = True
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "dohessian"):
doHessian = True
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "maxiter"):
maxIter = int(linesp[1])
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "optvar"):
optvar = True
if (len(linesp) != 0 and linesp[0][0] != '#' and linesp[0].lower() == "sr"):
sr = True
if (len(linesp) != 0 and linesp[0][0] != '#' and linesp[0].lower() == "gd"):
gd = True
print "#*********END OF INPUT FILE"
print "#opt-params"
print "#stepsize : %f"%(m_stepsize)
print "#decay_mom1 : %f"%(m_decay_mom1)
print "#decay_mom2 : %f"%(m_decay_mom2)
print "#**********"
print "#T: %f"%(T)
if (len(ciExpansion) == 0) :
ciExpansion = [1.]
hffilename = "hf.txt"
hffile = open(hffilename, "r")
lines = hffile.readlines()
norbs = len(lines)
hforbs = np.zeros((norbs*len(lines[0].split()),))
for i in range(len(lines)):
linesp = lines[i].split();
for j in range(len(linesp)):
if (j < norbs ):
hforbs[i*norbs+j] = float(linesp[j])
else:
hforbs[norbs*norbs+i*norbs+j-norbs] = float(linesp[j])
numCPS = numVars
numVars += len(ciExpansion) + hforbs.shape[0]
emin = 1.e10
def d_loss_wrt_pars(wrt):
global emin
wrt.astype('float64').tofile("params.bin")
try:
cmd = ' '.join((mpiprefix, executable, inFile))
cmd = "%s " % (cmd)
#check_call(cmd, shell=True)
out=check_output(cmd, shell=True).strip()
print out
sys.stdout.flush()
if (optvar):
e = float(out.split()[1])
else:
e = float(out.split()[0])
except CalledProcessError as err:
raise err
if e<emin:
emin = 1.*e
wrt.astype('float64').tofile("params_min.bin")
eminA = np.asarray([emin])
eminA.astype('float64').tofile("emin.bin")
p = np.fromfile("grad.bin", dtype="float64")
p.reshape(wrt.shape)
return p
wrt = np.ones(shape=(numVars,))
wrt[numCPS : numCPS+len(ciExpansion)] = np.asarray(ciExpansion)
wrt[numCPS+len(ciExpansion) : ] = hforbs
civars = len(ciExpansion)
if (Restart):
wrt = np.fromfile("params.bin", dtype = "float64")
emin = np.fromfile("emin.bin", dtype = "float64")[0]
if (doHessian):
for i in range(maxIter):
grad = d_loss_wrt_pars(wrt)
Hessian = np.fromfile("hessian.bin", dtype="float64")
Smatrix = np.fromfile("smatrix.bin", dtype="float64")
Hessian.shape = (numVars+1, numVars+1)
Smatrix.shape = (numVars+1, numVars+1)
Hessian[1:, 1:] += 0.1*np.eye(numVars)
#make the tangent space orthogonal to the wavefunction
Uo = 0.* Smatrix
Uo[0,0] = 1.0;
for i in range(numVars):
Uo[0, i+1] = -Smatrix[0, i+1]
Uo[i+1, i+1] = 1.0
Smatrix = reduce(np.dot, (Uo.T, Smatrix, Uo))
Hessian = reduce(np.dot, (Uo.T, Hessian, Uo))
[ds, vs] = np.linalg.eigh(Smatrix)
cols = []
for i in range(numVars+1):
if (abs(ds[i]) > 1.e-8):
cols.append(i)
U = np.zeros((numVars+1, len(cols)))
for i in range(len(cols)):
U[:,i] = vs[:,cols[i]]/(ds[cols[i]]**0.5)
Hessian_prime = reduce(np.dot, (U.T, Hessian, U))
[dc, dv] = np.linalg.eig(Hessian_prime)
index = [np.argmin(dc).real]
#print "Expected energy in next step : ", dc[index].real
#print "Number of total/nonredundant pramas: ", numVars+1, len(cols)
sys.stdout.flush()
update = np.dot(U, dv[:,index].real)
dw = update[1:]/update[0]
dw.shape = wrt.shape
wrt += dw
if (sr):
for i in range(maxIter):
grad = d_loss_wrt_pars(wrt)
Smatrix = np.fromfile("smatrix.bin", dtype="float64")
Smatrix.shape = (numVars+1, numVars+1)
Smatrix[1:,1:] += 1.e-1 * np.eye(numVars)
'''
ds, vs = np.linalg.eigh(Smatrix)
cols = []
for i in range(numVars+1):
if (abs(ds[i]) > 1.e-8):
cols.append(i)
U = np.zeros((numVars+1,len(cols)))
dsinv = np.zeros((len(cols),len(cols)))
for i in range(len(cols)):
U[:,i] = vs[:,cols[i]]
dsinv[i,i] = 1 / ds[cols[i]]
Sinv = reduce(np.dot, (U,dsinv,U.T))
'''
b = np.zeros((numVars+1,1))
for i in range(len(b)):
if i == 0:
b[i] = Smatrix[i,0]
else:
b[i] = Smatrix[i,0] - T * grad[i-1]
#x, res, rank, s = np.linalg.lstsq(Smatrix,b)
#x, info = scipy.sparse.linalg.cg(Smatrix,b)
#x = np.linalg.solve(Smatrix,b)
xguess = np.zeros((numVars+1,1))
xguess[0,0] = 1
xguess[1:,0] = wrt
#xguess = np.random.rand(numVars+1,1)
x = cj.conjgrad(Smatrix,b,xguess)
#Sinv = np.linalg.pinv(Smatrix,1.e-15)
#x = np.dot(Sinv,b)
dw = x[1:] / x[0]
dw.shape = wrt.shape
wrt += dw
if (gd):
for i in range(maxIter):
grad = d_loss_wrt_pars(wrt)
wrt -= T * grad
else :
#wrt = np.fromfile("params.bin", dtype="float64")
#opt = climin.GradientDescent(wrt, d_loss_wrt_pars, step_rate=0.01, momentum=.95)
#opt = climin.rmsprop.RmsProp(wrt, d_loss_wrt_pars, step_rate=0.0001, decay=0.9)
opt = climin.amsgrad.Amsgrad(wrt, d_loss_wrt_pars, step_rate=m_stepsize, decay_mom1=m_decay_mom1, decay_mom2=m_decay_mom2, momentum=0.0)
if (Restart):
opt.est_mom1_b = np.fromfile("moment1.bin", dtype="float64")
opt.est_mom2_b = np.fromfile("moment2.bin", dtype="float64")
for info in opt:
if info['n_iter'] >= maxIter:
break
opt.est_mom1_b.astype("float64").tofile("moment1.bin")
opt.est_mom2_b.astype("float64").tofile("moment2.bin")
if (os.path.isfile("updateparams.txt")):
f = open("updateparams.txt", 'r')
for line in f:
linesp = line.split();
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "stepsize"):
m_stepsize = float(linesp[1])
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "decay1"):
m_decay_mom1 = float(linesp[1])
if (len(linesp) != 0 and linesp[0][0] != "#" and linesp[0].lower() == "decay2"):
m_decay_mom2 = float(linesp[1])
print "#updating opt-params"
print "#stepsize : %f"%(m_stepsize)
print "#decay_mom1 : %f"%(m_decay_mom1)
print "#decay_mom2 : %f"%(m_decay_mom2)
print "#**********"
opt.step_rate = m_stepsize
opt.decay_mom1 = m_decay_mom1
opt.decay_mom2 = m_decay_mom2
f.close()
os.remove("updateparams.txt")
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include "igl/slice.h"
#include "igl/slice_into.h"
#include "Determinants.h"
#include "Slater.h"
#include "global.h"
#include "input.h"
using namespace Eigen;
Slater::Slater()
{
initHforbs();
initDets();
}
int Slater::getNumOfDets() const {return determinants.size();}
//void Slater::initWalker(HFWalker &walk) const
//{
//walk = HFWalker(*this);
//}
//void Slater::initWalker(HFWalker &walk, const Determinant &d) const
//{
//walk = HFWalker(*this, d);
//}
void Slater::initHforbs()
{
ifstream dump("hf.txt");
if (dump) {
int norbs = Determinant::norbs;
int size; //dimension of the mo coeff matrix
//initialize hftype and hforbs
if (schd.hf == "uhf") {
hftype = HartreeFock::UnRestricted;
MatrixXcd Hforbs = MatrixXcd::Zero(norbs, 2*norbs);
readMat(Hforbs, "hf.txt");
if (schd.ifComplex && Hforbs.imag().isZero(0)) Hforbs.imag() = 0.01 * MatrixXd::Random(norbs, 2*norbs);
HforbsA = Hforbs.block(0, 0, norbs, norbs);
HforbsB = Hforbs.block(0, norbs, norbs, norbs);
}
else {
if (schd.hf == "rhf") {
hftype = HartreeFock::Restricted;
size = norbs;
}
else if (schd.hf == "ghf") {
hftype = HartreeFock::Generalized;
size = 2*norbs;
}
MatrixXcd Hforbs = MatrixXcd::Zero(size, size);
readMat(Hforbs, "hf.txt");
if (schd.ifComplex && Hforbs.imag().isZero(0)) Hforbs.imag() = 0.1 * MatrixXd::Random(size, size) / norbs;
HforbsA = Hforbs;
HforbsB = Hforbs;
}
}
}
void Slater::initDets()
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
//initialize slater determinants
if (boost::iequals(schd.determinantFile, "") || boost::iequals(schd.determinantFile, "bestDet")) {
determinants.resize(1);
ciExpansion.resize(1, 1.0);
if (schd.hf == "rhf" || schd.hf == "uhf") {
for (int i = 0; i < nalpha; i++)
determinants[0].setoccA(i, true);
for (int i = 0; i < nbeta; i++)
determinants[0].setoccB(i, true);
}
else {
//jailbreaking existing dets for ghf use, filling alpha orbitals first and then beta, a ghf det wrapper maybe cleaner
int nelec = nalpha + nbeta;
if (nelec <= norbs) {
for (int i = 0; i < nelec; i++)
determinants[0].setoccA(i, true);
}
else {
for (int i = 0; i < norbs; i++)
determinants[0].setoccA(i, true);
for (int i = 0; i < nelec-norbs; i++)
determinants[0].setoccB(i, true);
}
}
}
else {
readDeterminants(schd.determinantFile, determinants, ciExpansion);
}
}
void Slater::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
int norbs = Determinant::norbs;
for (int i = 0; i < determinants.size(); i++)
v[i] = ciExpansion[i];
int numDeterminants = determinants.size();
if (hftype == Generalized) {
for (int i = 0; i < 2*norbs; i++) {
for (int j = 0; j < 2*norbs; j++) {
v[numDeterminants + 4 * i * norbs + 2 * j] = HforbsA(i, j).real();
v[numDeterminants + 4 * i * norbs + 2 * j + 1] = HforbsA(i, j).imag();
}
}
}
else {
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
if (hftype == Restricted) {
v[numDeterminants + 2 * i * norbs + 2 * j] = HforbsA(i, j).real();
v[numDeterminants + 2 * i * norbs + 2 * j + 1] = HforbsA(i, j).imag();
}
else {
v[numDeterminants + 2 * i * norbs + 2 * j] = HforbsA(i, j).real();
v[numDeterminants + 2 * i * norbs + 2 * j + 1] = HforbsA(i, j).imag();
v[numDeterminants + 2 * norbs * norbs + 2 * i * norbs + 2 * j] = HforbsB(i, j).real();
v[numDeterminants + 2 * norbs * norbs + 2 * i * norbs + 2 * j + 1] = HforbsB(i, j).imag();
}
}
}
}
}
long Slater::getNumVariables() const
{
long numVars = 0;
numVars += determinants.size();
if (hftype == UnRestricted)
//if (hftype == 1)
numVars += 4 * HforbsA.rows() * HforbsA.rows();
else
numVars += 2 * HforbsA.rows() * HforbsA.rows();
return numVars;
}
void Slater::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
int norbs = Determinant::norbs;
for (int i = 0; i < determinants.size(); i++)
ciExpansion[i] = v[i];
int numDeterminants = determinants.size();
if (hftype == Generalized) {
for (int i = 0; i < 2*norbs; i++) {
for (int j = 0; j < 2*norbs; j++) {
HforbsA(i, j) = std::complex<double>(v[numDeterminants + 4 * i * norbs + 2 * j], v[numDeterminants + 4 * i * norbs + 2 * j + 1]);
HforbsB(i, j) = HforbsA(i, j);
}
}
}
else {
for (int i = 0; i < norbs; i++) {
for (int j = 0; j < norbs; j++) {
if (hftype == Restricted) {
HforbsA(i, j) = std::complex<double>(v[numDeterminants + 2 * i * norbs + 2 * j], v[numDeterminants + 2 * i * norbs + 2 * j + 1]);
HforbsB(i, j) = HforbsA(i, j);
}
else {
HforbsA(i, j) = std::complex<double>(v[numDeterminants + 2 * i * norbs + 2 * j], v[numDeterminants + 2 * i * norbs + 2 * j + 1]);
HforbsB(i, j) = std::complex<double>(v[numDeterminants + 2 * norbs * norbs + 2 * i * norbs + 2 * j], v[numDeterminants + 2 * norbs * norbs + 2 * i * norbs + 2 * j + 1]);
}
}
}
}
}
void Slater::printVariables() const
{
cout << endl<<"CI-expansion"<<endl;
for (int i = 0; i < determinants.size(); i++) {
cout << " " << ciExpansion[i] << endl;
}
cout << endl<<"DeterminantA"<<endl;
//for r/ghf
for (int i = 0; i < HforbsA.rows(); i++) {
for (int j = 0; j < HforbsA.rows(); j++)
cout << " " << HforbsA(i, j);
cout << endl;
}
if (hftype == UnRestricted) {
//if (hftype == 1) {
cout << endl
<< "DeterminantB" << endl;
for (int i = 0; i < HforbsB.rows(); i++) {
for (int j = 0; j < HforbsB.rows(); j++)
cout << " " << HforbsB(i, j);
cout << endl;
}
}
cout << endl;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PROFILE_HEADER_H
#define PROFILE_HEADER_H
struct Profile {
double SinglesTime = 0;
size_t SinglesCount = 0;
double DoubleTime = 0;
size_t DoubleCount = 0;
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPTIMIZERFTRL_HEADER_H
#define OPTIMIZERFTRL_HEADER_H
#include <Eigen/Dense>
#include <boost/serialization/serialization.hpp>
#include "iowrapper.h"
#include "global.h"
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
using namespace Eigen;
using namespace boost;
class FTRL
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & lambda
& zVec
& sumGradSquare
& iter;
}
public:
double alpha;
double beta;
double lambda;
VectorXd zVec;
VectorXd sumGradSquare;
int maxIter;
int iter;
FTRL(double palpha=0.001, double pbeta=1.,
int pmaxIter=1000) : alpha(palpha), beta(pbeta), maxIter(pmaxIter)
{
iter = 0;
}
void write(VectorXd& vars)
{
if (commrank == 0)
{
char file[5000];
sprintf(file, "ftrl.bkp");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << *this;
save << vars;
ofs.close();
}
}
void read(VectorXd& vars)
{
if (commrank == 0)
{
char file[5000];
sprintf(file, "ftrl.bkp");
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> *this;
load >> vars;
ifs.close();
}
}
template<typename Function>
void optimize(VectorXd &vars, Function& getGradient, bool restart)
{
if (restart)
{
if (commrank == 0)
read(vars);
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
boost::mpi::broadcast(world, vars, 0);
#endif
}
else if (zVec.rows() == 0)
{
lambda = 0.;
zVec = VectorXd::Zero(vars.rows());
sumGradSquare = VectorXd::Zero(vars.rows());
}
VectorXd grad = VectorXd::Zero(vars.rows());
while (iter < maxIter)
{
double E0, stddev = 0.0, rt = 1.0;
VectorXd varsOld = vars;
getGradient(vars, grad, E0, stddev, rt);
if (commrank == 0 && schd.printGrad) {cout << "totalGrad" << endl; cout << grad << endl;}
write(vars);
if (commrank == 0)
{
for (int i = 0; i < vars.rows(); i++) {
zVec(i) += grad(i) + vars(i) * (pow(sumGradSquare(i), 0.5) - pow(sumGradSquare(i) + grad(i) * grad(i), 0.5)) / alpha;
sumGradSquare(i) += grad(i) * grad(i);
vars(i) = - zVec(i) * alpha / (beta + pow(sumGradSquare(i), 0.5));
}
}
#ifndef SERIAL
MPI_Bcast(&vars[0], vars.rows(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0)
std::cout << format("%5i %14.8f (%8.2e) %14.8f %8.1f %10i %8.2f\n") % iter % E0 % stddev % (grad.norm()) % (rt) % (schd.stochasticIter) % ((getTime() - startofCalc));
iter++;
}
}
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include "igl/slice.h"
#include "igl/slice_into.h"
#include "Determinants.h"
#include "Pfaffian.h"
#include "global.h"
#include "input.h"
using namespace Eigen;
Pfaffian::Pfaffian()
{
int norbs = Determinant::norbs;
pairMat = MatrixXcd::Zero(2*norbs, 2*norbs);
readMat(pairMat, "pairMat.txt");
if (schd.ifComplex && pairMat.imag().isZero(0)) pairMat.imag() = 0.01 * MatrixXd::Random(2*norbs, 2*norbs);
pairMat = (pairMat - pairMat.transpose().eval()) / 2;
}
void Pfaffian::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
int norbs = Determinant::norbs;
for (int i = 0; i < 2 * norbs; i++) {
for (int j = 0; j < 2 * norbs; j++) {
v[4 * i * norbs + 2 * j] = pairMat(i, j).real();
v[4 * i * norbs + 2 * j + 1] = pairMat(i, j).imag();
}
}
}
long Pfaffian::getNumVariables() const
{
int norbs = Determinant::norbs;
return 8 * norbs * norbs;
}
void Pfaffian::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
int norbs = Determinant::norbs;
for (int i = 0; i < 2 * norbs; i++) {
for (int j = 0; j < 2 * norbs; j++) {
pairMat(i, j) = std::complex<double>(v[4 * i * norbs + 2 * j], v[4 * i * norbs + 2 * j + 1]);
//pairMat(j, i) = pairMat(i,j);
}
}
pairMat = (pairMat - pairMat.transpose().eval())/2;
}
void Pfaffian::printVariables() const
{
cout << endl << "pairMat" << endl;
for (int i = 0; i < pairMat.rows(); i++) {
for (int j = 0; j < pairMat.rows(); j++)
cout << " " << pairMat(i, j);
cout << endl;
}
cout << endl;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPTIMIZERSR_HEADER_H
#define OPTIMIZERSR_HEADER_H
#include <Eigen/Dense>
#include <boost/serialization/serialization.hpp>
#include "iowrapper.h"
#include "global.h"
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
using namespace Eigen;
using namespace boost;
using namespace std;
class DirectMetric
{
public:
vector<double> T;
vector<VectorXd> Vectors;
double diagshift;
MatrixXd S;
DirectMetric(double _diagshift) : diagshift(_diagshift) {}
void BuildMetric()
{
double Tau = 0.0;
int dim = Vectors[0].rows();
S = MatrixXd::Zero(dim, dim);
for (int i = 0; i < Vectors.size(); i++)
{
S += T[i] * Vectors[i] * Vectors[i].adjoint();
Tau += T[i];
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(Tau), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(S(0,0)), S.rows() * S.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
S /= Tau;
}
void multiply(VectorXd &x, VectorXd& Ax)
{
double Tau = 0.0;
int dim = x.rows();
if (Ax.rows() != x.rows())
Ax = VectorXd::Zero(dim);
else
Ax.setZero();
for (int i = 0; i < Vectors.size(); i++)
{
double factor = Vectors[i].adjoint() * x;
Ax += T[i] * Vectors[i] * factor;
Tau += T[i];
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(Ax(0)), Ax.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Tau), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
Ax /= Tau;
Ax += diagshift * x;
}
};
void ConjGrad(DirectMetric &A, VectorXd &b, int n, VectorXd &x);
void PInv(MatrixXd &A, MatrixXd &Ainv);
class SR
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & stepsize
& iter;
}
public:
double stepsize;
int maxIter;
int iter;
SR(double pstepsize=0.01, int pmaxIter=1000) : stepsize(pstepsize), maxIter(pmaxIter)
{
iter = 0;
}
void write(VectorXd& vars)
{
if (commrank == 0)
{
char file[5000];
sprintf(file, "sr.bkp");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << *this;
save << vars;
ofs.close();
}
}
void read(VectorXd& vars)
{
if (commrank == 0)
{
char file[50];
sprintf(file, "sr.bkp");
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> *this;
load >> vars;
ifs.close();
}
}
template<typename Function>
void optimize(VectorXd &vars, Function &getMetric, bool restart)
{
if (restart)
{
if (commrank == 0)
read(vars);
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
boost::mpi::broadcast(world, vars, 0);
#endif
}
int numVars = vars.rows();
VectorXd grad, x, H;
DirectMetric S(schd.sDiagShift);
double E0, stddev, rt;
while (iter < maxIter)
{
E0 = 0.0;
stddev = 0.0;
rt = 0.0;
grad.setZero(numVars);
x.setZero(numVars + 1);
H.setZero(numVars + 1);
S.Vectors.clear();
S.T.clear();
getMetric(vars, grad, H, S, E0, stddev, rt);
write(vars);
/*
FOR DEBUGGING PURPOSE
*/
/*
S.BuildMetric();
for(int i=0; i<vars.rows(); i++)
S.S(i,i) += 1.e-4;
MatrixXd s_inv = MatrixXd::Zero(vars.rows() + 1, vars.rows() + 1);
PIn(S.S,s_inv);
x = s_inv * s.H;
*/
//cout << s.H << endl<<endl;
//cout << x <<endl<<endl<<endl;;
//xguess << 1.0, vars;
x[0] = 1.0;
ConjGrad(S, H, schd.cgIter, x);
for (int i = 0; i < vars.rows(); i++)
{
vars(i) += (x(i+1) / x(0));
}
#ifndef SERIAL
MPI_Bcast(&(vars[0]), vars.rows(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0)
std::cout << format("%5i %14.8f (%8.2e) %14.8f %8.1f %10i %8.2f\n") % iter % E0 % stddev % (grad.norm()) % (rt) % (schd.stochasticIter) % ((getTime() - startofCalc));
iter++;
}
}
};
#endif
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace MRLCC_AAVV {
FTensorDecl TensorDecls[31] = {
/* 0*/{"b", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"B", "eeaa", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"t", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 3*/{"T", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 4*/{"p", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 5*/{"P", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 6*/{"Ap", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 7*/{"AP", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 8*/{"R", "eeaa", "",USAGE_Amplitude, STORAGE_Memory},
/* 9*/{"k", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"k", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"k", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"W", "caca", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 13*/{"W", "caac", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 14*/{"W", "cece", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 15*/{"W", "ceec", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 16*/{"W", "aeae", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 17*/{"W", "aeea", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 18*/{"W", "cccc", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 19*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 20*/{"Inter", "e", "",USAGE_Intermediate, STORAGE_Memory},
/* 21*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 22*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 23*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 24*/{"S1", "aAaA", "",USAGE_Density, STORAGE_Memory},
/* 25*/{"S2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 26*/{"W", "eeaa", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 27*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 29*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 30*/{"Inter", "ee", "", USAGE_Intermediate, STORAGE_Memory},
};
//Number of terms : 11
FEqInfo EqsRes[8] = {
{"abcd,ef,abeg,cdfg", -4.0 , 4, {6,10,4,22}}, //-4.0 Ap[abcd] k[ef] p[abeg] E2[cdfg]
{"abcd,ae,befg,cdgf", 4.0 , 4, {6,11,4,22}}, //4.0 Ap[abcd] k[ae] p[befg] E2[cdgf]
{"abcd,efgh,abef,cdgh", -2.0 , 4, {6,19,4,22}}, //-2.0 Ap[abcd] W[efgh] p[abef] E2[cdgh]
{"abcd,efig,abfh,cdgh,ie", -8.0 , 5, {6,12,4,22,27}}, //-8.0 Ap[abcd] W[efig] p[abfh] E2[cdgh] delta[ie]
{"abcd,efgi,abfh,cdgh,ie", 4.0 , 5, {6,13,4,22,27}}, //4.0 Ap[abcd] W[efgi] p[abfh] E2[cdgh] delta[ie]
//the next commented two are replaced by the following 3
//{"abcd,eaif,bfgh,cdhg,ie", 8.0 , 5, {6,14,4,22,27}}, //8.0 Ap[abcd] W[eaif] p[bfgh] E2[cdhg] delta[ie]
//{"abcd,eafi,bfgh,cdhg,ie", -4.0 , 5, {6,15,4,22,27}}, //-4.0 Ap[abcd] W[eafi] p[bfgh] E2[cdhg] delta[ie]
{"af,eaif,ie", 8.0, 3, {30,14,27}},
{"af,eafi,ie", -4.0, 3, {30,15,27}},
{"abcd,af,bfgh,cdhg", 1.0 , 4, {6,30,4,22}},
//{"abcd,abef,efgh,cdgh", 2.0 , 4, {6,20,4,22}}, //2.0 Ap[abcd] W[abef] p[efgh] E2[cdgh]
//{"abcd,efgh,abei,higfdc", -4.0 , 4, {6,19,4,23}}, //-4.0 Ap[abcd] W[efgh] p[abei] E3[cdfgih]
//{"abcd,eafg,bfhi,ihgedc", 4.0 , 4, {6,17,4,23}}, //4.0 Ap[abcd] W[eafg] p[bfhi] E3[cdeghi]
//{"abcd,eafg,bghi,fhiedc", 4.0 , 4, {6,16,4,23}}, //4.0 Ap[abcd] W[eafg] p[bghi] E3[cdeihf]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[2] = {
{"ABRS,ABPQ,RSPQ", 0.5, 3, {0, 26, 22}},
{"BARS,ABPQ,RSQP", 0.5, 3, {0, 26, 22}}
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "MRLCC_AAVV";
Out.perturberClass = "AAVV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 31;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsRes = FEqSet(&EqsRes[0], 8, "MRLCC_AAVV/Res");
Out.Overlap = FEqSet(&Overlap[0], 2, "MRLCC_AAVV/Overlap");
};
};
<file_sep>#include "interface.h"
#include "workArray.h"
#include "Integral3c.h"
#include "Integral2c.h"
void calcShellIntegralWrapper_3c(double* integrals, int sh1, int sh2, int sh3, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
initWorkArray();
calcShellIntegral(integrals, sh1, sh2, sh3, ao_loc, atm, natm, bas, nbas, env, Lattice);
}
void calcIntegralWrapper_3c(double* integrals, int* sh, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
initWorkArray();
calcIntegral_3c(integrals, sh, ao_loc, atm, natm, bas, nbas, env, Lattice);
}
void calcShellNuclearWrapper(double* integrals, int sh1, int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
initWorkArray();
calcShellNuclearIntegral(integrals, sh1, sh2, ao_loc, atm, natm, bas, nbas, env, Lattice);
}
void calcNuclearWrapper(double* integrals, int* sh, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
initWorkArray();
calcNuclearIntegral(integrals, sh, ao_loc, atm, natm, bas, nbas, env, Lattice);
}
void calcShellIntegralWrapper_2c(char* name, double* integrals, int sh1, int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
initWorkArray();
calcShellIntegral_2c(name, integrals, sh1, sh2, ao_loc, atm, natm, bas, nbas, env, Lattice);
}
void calcIntegralWrapper_2c(char* name, double* integrals, int* sh, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
initWorkArray();
calcIntegral_2c(name, integrals, sh, ao_loc, atm, natm, bas, nbas, env, Lattice);
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "SCPT.h"
#include "SelectedCI.h"
#include "igl/slice.h"
#include "igl/slice_into.h"
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
template<typename Wfn>
SCPT<Wfn>::SCPT()
{
wave.readWave();
// Find which excitation classes are being considered. The classes are
// labelled by integers from 0 to 8, and defined in SimpleWalker.h
if (schd.nciCore == 0) {
classesUsed[0] = true;
classesUsed[1] = true;
classesUsed[2] = true;
} else {
classesUsed[0] = true;
classesUsed[1] = true;
classesUsed[2] = true;
classesUsed[3] = true;
classesUsed[4] = true;
//classesUsed[5] = true;
classesUsed[6] = true;
//classesUsed[7] = true;
if (!schd.determCCVV)
classesUsed[8] = true;
else
classesUsedDeterm[8] = true;
// AAVV class
normsDeterm[2] = true;
// CAAV class
normsDeterm[4] = true;
// CCAA class
normsDeterm[6] = true;
}
int numCore = schd.nciCore;
int numVirt = Determinant::norbs - schd.nciCore - schd.nciAct;
// The number of coefficients in each excitation class:
// 0 holes, 0 particles:
numCoeffsPerClass[0] = 1;
// 0 holes, 1 particle:
numCoeffsPerClass[1] = 2*numVirt;
// 0 holes, 2 particles:
numCoeffsPerClass[2] = 2*numVirt * (2*numVirt - 1) / 2;
// 1 hole, 0 particles:
numCoeffsPerClass[3] = 2*numCore;
// 1 hole, 1 particle:
numCoeffsPerClass[4] = (2*numCore) * (2*numVirt);
// 1 hole, 2 particle:
//numCoeffsPerClass[5] = (2*numCore) * (2*numVirt * (2*numVirt - 1) / 2);
// 2 hole, 0 particles:
numCoeffsPerClass[6] = 2*numCore * (2*numCore - 1) / 2;
// 2 hole, 1 particle:
//numCoeffsPerClass[7] = (2*numCore * (2*numCore - 1) / 2) * (2*numVirt);
// Class 5 (2 holes, 1 particle), class 7 (1 holes, 2 particles) and
// class 8 (2 holes, 2 particles) are more complicated. They are set up here:
//createClassIndMap(numCoeffsPerClass[5], numCoeffsPerClass[7], numCoeffsPerClass[8]);
cumNumCoeffs[0] = 0;
for (int i = 1; i < 9; i++)
{
// If the previous class (labelled i-1) is being used, add it to the
// cumulative counter.
if (classesUsed[i-1]) {
cumNumCoeffs[i] = cumNumCoeffs[i-1] + numCoeffsPerClass[i-1];
}
else {
cumNumCoeffs[i] = cumNumCoeffs[i-1];
}
}
numCoeffs = 0;
for (int i = 0; i < 9; i++)
{
// The total number of coefficients. Only include a class if that
// class is being used.
if (classesUsed[i]) numCoeffs += numCoeffsPerClass[i];
}
// Resize coeffs
coeffs = VectorXd::Zero(numCoeffs);
moEne = VectorXd::Zero(Determinant::norbs);
//coeffs order: phi0, singly excited (spin orb index), doubly excited (spin orb pair index)
// Use a constant amplitude for each contracted state except
// the CASCI wave function.
double amp = -std::min(0.5, 5.0/std::sqrt(numCoeffs));
coeffs(0) = 1.0;
for (int i=1; i < numCoeffs; i++) {
coeffs(i) = amp;
}
char file[5000];
sprintf(file, "ciCoeffs.txt");
ifstream ofile(file);
if (ofile) {
for (int i = 0; i < coeffs.size(); i++) {
ofile >> coeffs(i);
}
}
char filem[5000];
sprintf(filem, "moEne.txt");
ifstream ofilem(filem);
if (ofilem) {
for (int i = 0; i < Determinant::norbs; i++) {
ofilem >> moEne(i);
}
}
else {
if (commrank == 0) cout << "moEne.txt not found!\n";
exit(0);
}
}
template<typename Wfn>
void SCPT<Wfn>::createClassIndMap(int& numStates_1h2p, int& numStates_2h1p, int& numStates_2h2p) {
// Loop over all combinations of vore and virtual pairs.
// For each, see if the corresponding Hamiltonian element is non-zero.
// If so, give it an index and put that index in a hash table for
// later access. If not, then we do not want to consider the corresponding
// internally contracted state.
int norbs = Determinant::norbs;
int first_virtual = 2*(schd.nciCore + schd.nciAct);
// Class 5 (1 holes, 2 particles)
numStates_1h2p = 0;
for (int i = first_virtual+1; i < 2*norbs; i++) {
for (int j = first_virtual; j < i; j++) {
for (int a = 0; a < 2*schd.nciCore; a++) {
// If this condition is not met, then it is not possible for this
// internally contracted state to be accessed by a single
// application of the Hamiltonian (due to spin conservation).
if (i%2 == a%2 || j%2 == a%2) {
std::array<int,3> inds = {i, j, a};
class_1h2p_ind[inds] = numStates_1h2p;
numStates_1h2p += 1;
}
}
}
}
// Class 7 (2 holes, 1 particles)
numStates_2h1p = 0;
for (int i = first_virtual; i < 2*norbs; i++) {
for (int a = 1; a < 2*schd.nciCore; a++) {
for (int b = 0; b < a; b++) {
// If this condition is not met, then it is not possible for this
// internally contracted state to be accessed by a single
// application of the Hamiltonian (due to spin conservation).
if (i%2 == a%2 || i%2 == b%2) {
std::array<int,3> inds = {i, a, b};
class_2h1p_ind[inds] = numStates_2h1p;
numStates_2h1p += 1;
}
}
}
}
// Class 8 (2 holes, 2 particles)
numStates_2h2p = 0;
for (int i = first_virtual+1; i < 2*norbs; i++) {
for (int j = first_virtual; j < i; j++) {
for (int a = 1; a < 2*schd.nciCore; a++) {
for (int b = 0; b < a; b++) {
morework.setCounterToZero();
generateAllScreenedExcitationsCAS_2h2p(schd.epsilon, morework, i, j, a, b);
if (morework.nExcitations > 0) {
std::array<int,4> inds = {i, j, a, b};
class_2h2p_ind[inds] = numStates_2h2p;
numStates_2h2p += 1;
}
}
}
}
}
}
template<typename Wfn>
typename Wfn::ReferenceType& SCPT<Wfn>::getRef() { return wave.getRef(); }
template<typename Wfn>
typename Wfn::CorrType& SCPT<Wfn>::getCorr() { return wave.getCorr(); }
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::initWalker(Walker& walk) {
this->wave.initWalker(walk);
}
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::initWalker(Walker& walk, Determinant& d) {
this->wave.initWalker(walk, d);
}
//void initWalker(Walker& walk) {
// this->wave.initWalker(walk);
//}
template<typename Wfn>
void SCPT<Wfn>::getVariables(Eigen::VectorXd& vars) {
vars = coeffs;
}
template<typename Wfn>
void SCPT<Wfn>::printVariables() {
cout << "ci coeffs\n" << coeffs << endl;
}
template<typename Wfn>
void SCPT<Wfn>::updateVariables(Eigen::VectorXd& vars) {
coeffs = vars;
}
template<typename Wfn>
long SCPT<Wfn>::getNumVariables() {
return coeffs.size();
}
template<typename Wfn>
template<typename Walker>
int SCPT<Wfn>::coeffsIndex(Walker& walk) {
int norbs = Determinant::norbs;
if (walk.excitation_class == 0) {
// CAS det (0 holes, 0 particles)
return 0;
}
else if (walk.excitation_class == 1) {
// 0 holes, 1 particle
return cumNumCoeffs[1] + *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
}
else if (walk.excitation_class == 2) {
// 0 holes, 2 particles
int a = *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
int b = *(std::next(walk.excitedOrbs.begin())) - 2*schd.nciCore - 2*schd.nciAct;
int A = max(a,b) - 1, B = min(a,b);
return cumNumCoeffs[2] + A*(A+1)/2 + B;
}
else if (walk.excitation_class == 3) {
// 1 hole, 0 particles
return cumNumCoeffs[3] + *walk.excitedHoles.begin();
}
else if (walk.excitation_class == 4) {
// 1 hole, 1 particles
int i = *walk.excitedHoles.begin();
int a = *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
int numVirt = norbs - schd.nciCore - schd.nciAct;
return cumNumCoeffs[4] + 2*numVirt*i + a;
}
else if (walk.excitation_class == 5) {
// 1 hole, 2 particles
int i = *walk.excitedHoles.begin();
int a = *walk.excitedOrbs.begin();
int b = *(std::next(walk.excitedOrbs.begin()));
int A = max(a,b), B = min(a,b);
std::array<int,3> inds = {A, B, i};
auto it1 = class_1h2p_ind.find(inds);
if (it1 != class_1h2p_ind.end())
return cumNumCoeffs[5] + it1->second;
else
return -1;
}
else if (walk.excitation_class == 6) {
// 2 hole, 0 particles
int i = *walk.excitedHoles.begin();
int j = *(std::next(walk.excitedHoles.begin()));
int I = max(i,j) - 1, J = min(i,j);
return cumNumCoeffs[6] + I*(I+1)/2 + J;
}
else if (walk.excitation_class == 7) {
// 2 holes, 1 particles
int i = *walk.excitedHoles.begin();
int j = *(std::next(walk.excitedHoles.begin()));
int I = max(i,j), J = min(i,j);
int a = *walk.excitedOrbs.begin();
std::array<int,3> inds = {a, I, J};
auto it1 = class_2h1p_ind.find(inds);
if (it1 != class_2h1p_ind.end())
return cumNumCoeffs[7] + it1->second;
else
return -1;
}
else if (walk.excitation_class == 8) {
// 2 holes, 2 particles
int i = *walk.excitedHoles.begin();
int j = *(std::next(walk.excitedHoles.begin()));
int I = max(i,j), J = min(i,j);
int a = *walk.excitedOrbs.begin();
int b = *(std::next(walk.excitedOrbs.begin()));
int A = max(a,b), B = min(a,b);
std::array<int,4> inds = {A, B, I, J};
auto it1 = class_2h2p_ind.find(inds);
if (it1 != class_2h2p_ind.end())
return cumNumCoeffs[8] + it1->second;
else
return -1;
}
else return -1;
}
// This perform the inverse of the coeffsIndex function: given the
// index of a perturber, return the external (non-active) orbtials
// involved. This only works for the main perturber types used -
// V, VV, C, CV, CC. These only have one or two external orbitals,
// which this function will return.
template<typename Wfn>
void SCPT<Wfn>::getOrbsFromIndex(const int index, int& i, int& j)
{
int norbs = Determinant::norbs;
int firstVirt = 2*(schd.nciCore + schd.nciAct);
int numVirt = 2*(norbs - schd.nciCore - schd.nciAct);
i = -1;
j = -1;
if (index >= cumNumCoeffs[1] && index < cumNumCoeffs[2]) {
// AAAV perturber
i = index - cumNumCoeffs[1] + firstVirt;
}
else if (index >= cumNumCoeffs[2] && index < cumNumCoeffs[3]) {
// AAVV perturber
int index2 = index - cumNumCoeffs[2];
j = (int) floor(-0.5 + pow(0.25 + 2*index2, 0.5));
i = index2 - j*(j+1)/2;
i += firstVirt;
j += firstVirt + 1;
}
else if (index >= cumNumCoeffs[3] && index < cumNumCoeffs[4]) {
// CAAA perturber
i = index - cumNumCoeffs[3];
}
else if (index >= cumNumCoeffs[4] && index < cumNumCoeffs[5]) {
// CAAV perturber
int index2 = index - cumNumCoeffs[4];
j = index2 % numVirt;
i = floor(index2 / numVirt);
j += firstVirt;
}
else if (index >= cumNumCoeffs[6] && index < cumNumCoeffs[7]) {
// CCAA perturber
int index2 = index - cumNumCoeffs[6];
j = (int) floor(-0.5 + pow(0.25 + 2*index2, 0.5));
i = index2 - j*(j+1)/2;
j += 1;
}
}
// Take two orbital indices i and j, and convert them to a string.
// This is intended for use with two orbital obtained from the
// getOrbsFromIndex function, which are then to be output to
// pt2_energies files.
template<typename Wfn>
string SCPT<Wfn>::formatOrbString(const int i, const int j) {
string str;
if (i >= 0 && j == -1) {
string tempStr = '(' + to_string(i) + ')';
int tempLen = tempStr.length();
str = string(12 - tempLen, ' ') + tempStr;
}
else if (i >= 0 && j >= 0 ) {
string tempStr = '(' + to_string(i) + ',' + to_string(j) + ')';
int tempLen = tempStr.length();
str = string(12 - tempLen, ' ') + tempStr;
}
else {
str = string(12, ' ');
}
return str;
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::getOverlapFactor(int i, int a, const Walker& walk, bool doparity) const
{
return 1.;
} // not used
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::getOverlapFactor(int I, int J, int A, int B, const Walker& walk, bool doparity) const
{
return 1.;
} // not used
template<typename Wfn>
template<typename Walker>
bool SCPT<Wfn>::checkWalkerExcitationClass(Walker &walk) {
if (!classesUsed[walk.excitation_class]) return false;
int coeffsIndex = this->coeffsIndex(walk);
if (coeffsIndex == -1)
return false;
else
return true;
}
// ham is a sample of the diagonal element of the Dyall ham
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::HamAndOvlp(Walker &walk, double &ovlp, double &locEne, double &ham,
double &norm, int coeffsIndex, workingArray& work, bool fillExcitations)
{
int norbs = Determinant::norbs;
double ciCoeff = coeffs(coeffsIndex);
morework.setCounterToZero();
double ovlp0, ham0;
if (coeffsIndex == 0) {
wave.HamAndOvlp(walk, ovlp0, ham0, morework, true);
ovlp = ciCoeff * ovlp0;
}
else {
wave.HamAndOvlp(walk, ovlp0, ham0, morework, false);
ovlp = ciCoeff * ovlp0;
}
ovlp_current = ovlp;
if (ovlp == 0.) return; //maybe not necessary
if (abs(ciCoeff) < 1.e-5) norm = 0;
else norm = 1 / ciCoeff / ciCoeff;
locEne = walk.d.Energy(I1, I2, coreE);
// Get the diagonal Dyall Hamiltonian element from this determinant
Determinant dAct = walk.d;
double ene_h = 0.0, ene_hh = 0.0, ene_p = 0.0, ene_pp = 0.0;
if (walk.excitedOrbs.size() > 0) {
dAct.setocc(*walk.excitedOrbs.begin(), false);
ene_p = moEne((*walk.excitedOrbs.begin())/2);
}
if (walk.excitedOrbs.size() == 2) {
dAct.setocc(*(std::next(walk.excitedOrbs.begin())), false);
ene_pp = moEne((*(std::next(walk.excitedOrbs.begin())))/2);
}
if (walk.excitedHoles.size() > 0) {
dAct.setocc(*walk.excitedHoles.begin(), true);
ene_h = moEne((*walk.excitedHoles.begin())/2);
}
if (walk.excitedHoles.size() == 2) {
dAct.setocc(*(std::next(walk.excitedHoles.begin())), true);
ene_hh = moEne((*(std::next(walk.excitedHoles.begin())))/2);
}
ham = (dAct.Energy(I1, I2, coreE) + ene_p + ene_pp - ene_h - ene_hh) / ciCoeff / ciCoeff;
// Generate all excitations (after screening)
work.setCounterToZero();
generateAllScreenedSingleExcitationsDyallOld(walk.d, dAct, schd.epsilon, schd.screen, work, false);
generateAllScreenedDoubleExcitationsDyallOld(walk.d, schd.epsilon, schd.screen, work, false);
//loop over all the screened excitations
//cout << endl << "m dets\n" << endl << endl;
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
double tiaD = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double isDyall = 0.;
if (work.ovlpRatio[i] != 0.) {
isDyall = 1.;
if (ex2 == 0) tiaD = work.ovlpRatio[i];
work.ovlpRatio[i] = 0.;
}
auto walkCopy = walk;
double parity = 1.;
Determinant dcopy = walkCopy.d;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[i], work.excitation2[i], false);
// Is this excitation class being used? If not, then move to the next excitation.
if (!classesUsed[walkCopy.excitation_class]) continue;
int coeffsCopyIndex = this->coeffsIndex(walkCopy);
if (coeffsCopyIndex == -1) continue;
//if (walkCopy.excitedOrbs.size() > 2) continue;
parity *= dcopy.parity(A/2, I/2, I%2);
if (ex2 != 0) {
dcopy.setocc(I, false);
dcopy.setocc(A, true);
parity *= dcopy.parity(B/2, J/2, J%2);
}
morework.setCounterToZero();
if (coeffsCopyIndex == 0) {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, true);
ham += isDyall * parity * tiaD * ovlp0 / ciCoeff / ovlp;
locEne += parity * tia * ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
}
else {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, false);
ham += isDyall * parity * tiaD * ham0 / ciCoeff / ovlp;
locEne += parity * tia * ham0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ham0 * coeffs(coeffsCopyIndex) / ovlp;
}
}
}
// ham is a sample of the diagonal element of the Dyall Hamiltonian
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::FastHamAndOvlp(Walker &walk, double &ovlp, double &ham, workingArray& work, bool fillExcitations)
{
double ovlp0, ham0;
double tiaD, parity;
int norbs = Determinant::norbs;
work.setCounterToZero();
morework.setCounterToZero();
//if (coeffsIndex == 0)
// cout << "ERROR: FastHamAndOvlp should not be used within the CASCI space." << endl;
//else
wave.HamAndOvlp(walk, ovlp, ham0, morework, false);
ovlp_current = ovlp;
if (ovlp == 0.) return;
// Get the diagonal Dyall Hamiltonian element from this determinant
Determinant dAct = walk.d;
double ene_h = 0.0, ene_hh = 0.0, ene_p = 0.0, ene_pp = 0.0;
if (walk.excitedOrbs.size() > 0) {
dAct.setocc(*walk.excitedOrbs.begin(), false);
ene_p = moEne((*walk.excitedOrbs.begin())/2);
}
if (walk.excitedOrbs.size() == 2) {
dAct.setocc(*(std::next(walk.excitedOrbs.begin())), false);
ene_pp = moEne((*(std::next(walk.excitedOrbs.begin())))/2);
}
if (walk.excitedHoles.size() > 0) {
dAct.setocc(*walk.excitedHoles.begin(), true);
ene_h = moEne((*walk.excitedHoles.begin())/2);
}
if (walk.excitedHoles.size() == 2) {
dAct.setocc(*(std::next(walk.excitedHoles.begin())), true);
ene_hh = moEne((*(std::next(walk.excitedHoles.begin())))/2);
}
ham = (dAct.Energy(I1, I2, coreE) + ene_p + ene_pp - ene_h - ene_hh);
// Generate all excitations (after screening)
work.setCounterToZero();
generateAllScreenedSingleExcitationsDyall(walk.d, dAct, schd.epsilon, schd.screen, work, false);
generateAllScreenedDoubleExcitationsDyall(walk.d, schd.epsilon, schd.screen, work, false);
// loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
double tiaD = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
// If this is true, then this is a valid excitation for the Dyall
// Hamiltonian (i.e., using the active space Hamiltonian only).
if (work.ovlpRatio[i] != 0.) {
if (ex2 == 0) tiaD = work.ovlpRatio[i];
work.ovlpRatio[i] = 0.;
} else {
continue;
}
auto walkCopy = walk;
Determinant dcopy = walkCopy.d;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[i], work.excitation2[i], false);
parity = 1.;
parity *= dcopy.parity(A/2, I/2, I%2);
if (ex2 != 0) {
dcopy.setocc(I, false);
dcopy.setocc(A, true);
parity *= dcopy.parity(B/2, J/2, J%2);
}
morework.setCounterToZero();
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, false);
ham += parity * tiaD * ham0 / ovlp;
work.ovlpRatio[i] = ham0 / ovlp;
}
}
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::HamAndSCNorms(Walker &walk, double &ovlp, double &ham, Eigen::VectorXd &normSamples,
vector<Determinant>& initDets, vector<double>& largestCoeffs,
workingArray& work, bool calcExtraNorms)
{
// which excitation classes should we consider?
bool useAAVV;
bool useCAAV;
bool useCAVV;
bool useCCAA;
bool useCCAV;
bool useCCVV;
if (calcExtraNorms) {
useAAVV = classesUsed[2];
useCAAV = classesUsed[4];
useCAVV = classesUsed[5];
useCCAA = classesUsed[6];
useCCAV = classesUsed[7];
useCCVV = classesUsed[8];
} else {
// only consider these classes if we're not calculating the norms separately
useAAVV = classesUsed[2] && !normsDeterm[2];
useCAAV = classesUsed[4] && !normsDeterm[4];
useCAVV = classesUsed[5] && !normsDeterm[5];
useCCAA = classesUsed[6] && !normsDeterm[6];
useCCAV = classesUsed[7] && !normsDeterm[7];
useCCVV = classesUsed[8] && !normsDeterm[8];
}
int norbs = Determinant::norbs;
double ham0;
morework.setCounterToZero();
// Get the WF overlap with the walker, ovlp
wave.HamAndOvlp(walk, ovlp, ham0, morework, true);
ovlp_current = ovlp;
if (ovlp == 0.) return;
ham = walk.d.Energy(I1, I2, coreE);
// Generate all screened excitations
work.setCounterToZero();
size_t nExcitationsCASCI = 0;
int nSpinCore = 2*schd.nciCore;
int firstSpinVirt = 2*(schd.nciCore + schd.nciAct);
vector<int> closed;
vector<int> open;
walk.d.getOpenClosed(open, closed);
// single excitations
for (int i = 0; i < closed.size(); i++) {
bool iCore = closed[i] < nSpinCore;
for (int a = 0; a < open.size(); a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > schd.epsilon)
{
bool aVirt = open[a] >= firstSpinVirt;
bool caavExcit = iCore && aVirt;
if (!useCAAV && caavExcit) continue;
int ex1 = closed[i] * 2 * norbs + open[a];
int ex2 = 0.0;
double tia = walk.d.Hij_1ExciteScreened(open[a], closed[i], I2hb,
schd.screen, false);
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// double excitations
int nclosed = closed.size();
for (int i = 0; i<nclosed; i++) {
bool iCore = closed[i] < nSpinCore;
for (int j = 0; j<i; j++) {
bool jCore = closed[j] < nSpinCore;
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hb.getIntegralArray(closed[i], closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, schd.epsilon, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closed[i] % 2,
b = 2 * orbIndices[2 * index + 1] + closed[j] % 2;
if (walk.d.getocc(a) || walk.d.getocc(b)) continue;
bool aVirt = a >= firstSpinVirt;
bool bVirt = b >= firstSpinVirt;
bool ccvvExcit = iCore && aVirt && bVirt;
if (!useCCVV && ccvvExcit) continue;
bool cavvExcit = jCore && (!iCore) && aVirt && bVirt;
if (!useCAVV && cavvExcit) continue;
bool ccavExcit = iCore && ((aVirt && (!bVirt)) || ((!aVirt) && bVirt));
if (!useCCAV && ccavExcit) continue;
bool aavvExcit = (!jCore) && aVirt && bVirt;
if (!useAAVV && aavvExcit) continue;
bool caavExcit = jCore && (!iCore) && ( (aVirt && (!bVirt)) || ((bVirt && (!aVirt))) );
if (!useCAAV && caavExcit) continue;
bool ccaaExcit = iCore && (!aVirt) && (!bVirt);
if (!useCCAA && ccaaExcit) continue;
int ex1 = closed[i] * 2 * norbs + a;
int ex2 = closed[j] * 2 * norbs + b;
double tia = integrals[index];
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// For the CTMC algorithm, only need excitations within the CASCI space.
// Update the number of excitations to reflect this
work.nExcitations = nExcitationsCASCI;
}
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::AddSCNormsContrib(Walker &walk, double &ovlp, double &ham, Eigen::VectorXd &normSamples,
vector<Determinant>& initDets, vector<double>& largestCoeffs,
workingArray& work, bool calcExtraNorms, int& ex1, int& ex2,
double& tia, size_t& nExcitationsCASCI)
{
// This is called for each excitations from a determinant in the CASCI
// space (walk.d)
// If the excitations is within the CASCI space, store the overlap factor
// in the work array, for the CTMC algorithm to make a move.
// Otherwise, add contributions to the estimates of the norms.
// Also, if the given excited determinant has the largest coefficient found,
// then store the determinant and the coefficient in initDets and largestCoeffs.
int norbs = Determinant::norbs;
double ovlp0, ham0;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
auto walkCopy = walk;
double parity = 1.0;
Determinant dcopy = walkCopy.d;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(), ex1, ex2, false);
parity *= dcopy.parity(A/2, I/2, I%2);
if (ex2 != 0) {
dcopy.setocc(I, false);
dcopy.setocc(A, true);
parity *= dcopy.parity(B/2, J/2, J%2);
}
//work.ovlpRatio[i] = 0.0;
if (walkCopy.excitation_class == 0) {
// For the CTMC algorithm (which is performed within the CASCI space, when
// calculating the SC norms), we need the ratio of overlaps for connected
// determinants within the CASCI space. Store these in the work array, and
// override other excitations, which we won't need any more.
double ovlpRatio = wave.Overlap(walkCopy.d) / ovlp;
work.excitation1[nExcitationsCASCI] = ex1;
work.excitation2[nExcitationsCASCI] = ex2;
work.ovlpRatio[nExcitationsCASCI] = ovlpRatio;
ham += parity * tia * ovlpRatio;
nExcitationsCASCI += 1;
return;
} else if (!classesUsed[walkCopy.excitation_class]) {
// Is this excitation class being used? If not, then move to the next excitation
return;
} else if (normsDeterm[walkCopy.excitation_class]) {
// Is the norm for this class being calculated exactly? If so, move to the next excitation
// The exception is if we want to record the maximum coefficient size (calcExtraNorms == true)
if (!calcExtraNorms) return;
}
int ind = this->coeffsIndex(walkCopy);
if (ind == -1) return;
morework.setCounterToZero();
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, false);
normSamples(ind) += parity * tia * ham0 / ovlp;
// If this is the determinant with the largest coefficient found within
// the SC space so far, then store it.
if (abs(ham0) > largestCoeffs[ind]) {
initDets[ind] = walkCopy.d;
largestCoeffs[ind] = abs(ham0);
}
}
// this is a version of HamAndSCNorms, optimized for the case where only
// classes AAAV (class 1) and CAAA (class 3) are needed
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::HamAndSCNormsCAAA_AAAV(Walker &walk, double &ovlp, double &ham, Eigen::VectorXd &normSamples,
vector<Determinant>& initDets, vector<double>& largestCoeffs,
workingArray& work, bool calcExtraNorms)
{
int norbs = Determinant::norbs;
double ham0;
morework.setCounterToZero();
// Get the WF overlap with the walker, ovlp
wave.HamAndOvlp(walk, ovlp, ham0, morework, true);
ovlp_current = ovlp;
if (ovlp == 0.) return;
ham = walk.d.Energy(I1, I2, coreE);
// Generate all screened excitations
work.setCounterToZero();
size_t nExcitationsCASCI = 0;
int nSpinCore = 2*schd.nciCore;
int firstSpinVirt = 2*(schd.nciCore + schd.nciAct);
vector<int> closed;
vector<int> open;
walk.d.getOpenClosed(open, closed);
auto ub_1 = upper_bound(open.begin(), open.end(), firstSpinVirt - 1);
int indActOpen = std::distance(open.begin(), ub_1);
auto ub_2 = upper_bound(closed.begin(), closed.end(), nSpinCore - 1);
int indCoreClosed = std::distance(closed.begin(), ub_2);
// single excitations within the CASCI space
// loop over all occupied orbitals in the active space
for (int i = indCoreClosed; i < closed.size(); i++) {
int closedOrb = closed[i];
int closedOffset = closedOrb * 2 * norbs;
// loop over all unoccupied orbitals in the active space
for (int a = 0; a < indActOpen; a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > schd.epsilon)
{
int ex1 = closedOffset + open[a];
int ex2 = 0;
double tia = walk.d.Hij_1ExciteScreened(open[a], closedOrb, I2hb,
schd.screen, false);
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// double excitations within the CASCI space
// loop over all closed orbitals in the active space
for (int i = indCoreClosed; i < closed.size(); i++) {
int closedOrb_i = closed[i];
int closedOffset_i = closedOrb_i * 2 * norbs;
// loop over all closed orbitals in the active space s.t. j<i
for (int j = indCoreClosed; j<i; j++) {
int closedOrb_j = closed[j];
int closedOffset_j = closedOrb_j * 2 * norbs;
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArrayCAS(closedOrb_i, closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, schd.epsilon, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closedOrb_i % 2,
b = 2 * orbIndices[2 * index + 1] + closedOrb_j % 2;
if (walk.d.getocc(a) || walk.d.getocc(b)) continue;
int ex1 = closedOffset_i + a;
int ex2 = closedOffset_j + b;
double tia = integrals[index];
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// single excitations for CAAA class
// loop over all core orbitals (which will all be occupied)
for (int i = 0; i < indCoreClosed; i++) {
int closedOrb = closed[i];
int closedOffset = closedOrb * 2 * norbs;
// loop over all open orbitals in the active space
for (int a = 0; a < indActOpen; a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > schd.epsilon)
{
int ex1 = closedOffset + open[a];
int ex2 = 0;
double tia = walk.d.Hij_1ExciteScreened(open[a], closedOrb, I2hb,
schd.screen, false);
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// double excitations for CAAA class
// loop over all closed orbitals in the active space
for (int i = indCoreClosed; i < closed.size(); i++) {
int closedOrb_i = closed[i];
int closedOffset_i = closedOrb_i * 2 * norbs;
// loop over all core orbitals (which will all be occupied)
for (int j = 0; j < indCoreClosed; j++) {
int closedOrb_j = closed[j];
int closedOffset_j = closedOrb_j * 2 * norbs;
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArrayCAS(closedOrb_i, closed[j], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, schd.epsilon, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
int a = 2 * orbIndices[2 * index] + closedOrb_i % 2,
b = 2 * orbIndices[2 * index + 1] + closedOrb_j % 2;
if (walk.d.getocc(a) || walk.d.getocc(b)) continue;
int ex1 = closedOffset_i + a;
int ex2 = closedOffset_j + b;
double tia = integrals[index];
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// single excitations for AAAV class
// loop over all occupied orbitals in the active space
for (int i = indCoreClosed; i < closed.size(); i++) {
int closedOrb = closed[i];
int closedOffset = closedOrb * 2 * norbs;
// loop over all virtual orbitals (which will all be unoccupied)
for (int a = indActOpen; a < open.size(); a++) {
if (closed[i] % 2 == open[a] % 2 &&
abs(I2hb.Singles(closed[i], open[a])) > schd.epsilon)
{
int ex1 = closedOffset + open[a];
int ex2 = 0;
double tia = walk.d.Hij_1ExciteScreened(open[a], closedOrb, I2hb,
schd.screen, false);
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// double excitations for AAAV class
// loop over all virtual orbitals
for (int a = firstSpinVirt; a < 2 * norbs; a++) {
// loop over all open orbitals in the active space
for (int b = 0; b < indActOpen; b++) {
int openOrb_b = open[b];
const float *integrals; const short* orbIndices;
size_t numIntegrals;
I2hbCAS.getIntegralArrayCAS(a, open[b], integrals, orbIndices, numIntegrals);
size_t numLargeIntegrals = std::lower_bound(integrals, integrals + numIntegrals, schd.epsilon, [](const float &x, float val){ return fabs(x) > val; }) - integrals;
// for all HCI integrals
for (size_t index = 0; index < numLargeIntegrals; index++)
{
int i = 2 * orbIndices[2 * index] + a % 2,
j = 2 * orbIndices[2 * index + 1] + openOrb_b % 2;
if ( (!walk.d.getocc(i)) || (!walk.d.getocc(j)) ) continue;
int ex1 = i * 2 * norbs + a;
int ex2 = j * 2 * norbs + openOrb_b;
double tia = integrals[index];
AddSCNormsContrib(walk, ovlp, ham, normSamples, initDets, largestCoeffs,
work, calcExtraNorms, ex1, ex2, tia, nExcitationsCASCI);
}
}
}
// For the CTMC algorithm, only need excitations within the CASCI space.
// Update the number of excitations to reflect this
work.nExcitations = nExcitationsCASCI;
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::doNEVPT2_CT(Walker& walk) {
int norbs = Determinant::norbs;
// add noise to avoid zero coeffs
if (commrank == 0) {
//cout << "starting sampling at " << setprecision(4) << getTime() - startofCalc << endl;
auto random = std::bind(std::uniform_real_distribution<double>(0., 1.e-6), std::ref(generator));
for (int i=0; i < coeffs.size(); i++) {
if (coeffs(i) == 0) coeffs(i) = random();
}
}
#ifndef SERIAL
MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
// sampling
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
double ovlp = 0., normSample = 0., hamSample = 0., locEne = 0., waveEne = 0.;
VectorXd ham = VectorXd::Zero(coeffs.size()), norm = VectorXd::Zero(coeffs.size());
workingArray work;
int coeffsIndex = this->coeffsIndex(walk);
HamAndOvlp(walk, ovlp, locEne, hamSample, normSample, coeffsIndex, work);
int iter = 0;
double cumdeltaT = 0.;
int printMod = max(1, schd.stochasticIter / 10);
while (iter < schd.stochasticIter) {
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
double ratio = deltaT / cumdeltaT;
norm *= (1 - ratio);
norm(coeffsIndex) += ratio * normSample;
ham *= (1 - ratio);
ham(coeffsIndex) += ratio * hamSample;
waveEne *= (1 - ratio);
waveEne += ratio * locEne;
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
// Make sure that the walker is within one of the classes being sampled, after this move
if (!classesUsed[walk.excitation_class]) continue;
coeffsIndex = this->coeffsIndex(walk);
if (coeffsIndex == -1) continue;
HamAndOvlp(walk, ovlp, locEne, hamSample, normSample, coeffsIndex, work);
iter++;
if (commrank == 0 && iter % printMod == 1) cout << "iter " << iter << " t " << setprecision(4) << getTime() - startofCalc << endl;
}
norm *= cumdeltaT;
ham *= cumdeltaT;
waveEne *= cumdeltaT;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, norm.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ham.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(waveEne), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
norm /= cumdeltaT;
ham /= cumdeltaT;
waveEne /= cumdeltaT;
std::vector<int> largeNormIndices;
int counter = 0;
for (int i = 0; i < coeffs.size(); i++) {
if (norm(i) > schd.overlapCutoff) {
largeNormIndices.push_back(i);
}
}
Map<VectorXi> largeNormSlice(&largeNormIndices[0], largeNormIndices.size());
VectorXd largeNorms;
igl::slice(norm, largeNormSlice, largeNorms);
VectorXd largeHam;
igl::slice(ham, largeNormSlice, largeHam);
VectorXd ene = (largeHam.array() / largeNorms.array()).matrix();
double ene2 = 0.;
coeffs.setZero();
coeffs(0) = 1.;
for (int i = 1; i < largeNorms.size(); i++) {
ene2 += largeNorms(i) / largeNorms(0) / (ene(0) - ene(i));
coeffs(largeNormIndices[i]) = 1 / (ene(0) - ene(i));
}
if (commrank == 0) {
cout << "ref energy: " << setprecision(12) << ene(0) << endl;
cout << "stochastic nevpt2 energy: " << ene(0) + ene2 << endl;
cout << "stochastic waveEne: " << waveEne << endl;
// If any classes are to be obtained deterministically, then do this now
if (any_of(classesUsedDeterm.begin(), classesUsedDeterm.end(), [](bool i){return i;}) ) {
double energy_ccvv = 0.0;
if (classesUsedDeterm[8]) {
energy_ccvv = get_ccvv_energy();
cout << "deterministic CCVV energy: " << setprecision(12) << energy_ccvv << endl;
}
cout << "total nevpt2 energy: " << ene(0) + ene2 + energy_ccvv << endl;
}
if (schd.printVars) cout << endl << "ci coeffs\n" << coeffs << endl;
}
}
// Output the header for the "norms" file, which will output the norms of
// the strongly contracted (SC) states, divided by the norm of the CASCI
// state (squared)
template<typename Wfn>
double SCPT<Wfn>::outputNormFileHeader(FILE* out_norms)
{
fprintf(out_norms, "# 1. iteration");
fprintf(out_norms, " # 2. residence_time");
fprintf(out_norms, " # 3. casci_energy");
for (int ind = 1; ind < numCoeffs; ind++) {
int label = ind + 3;
string header;
header.append(to_string(label));
header.append(". weighted_norm_");
header.append(to_string(ind));
stringstream fixed_width;
// fix the width of each column to 28 characters
fixed_width << setw(28) << header;
string fixed_width_str = fixed_width.str();
fprintf(out_norms, fixed_width_str.c_str());
}
fprintf(out_norms, "\n");
}
// Create directories where the norm files will be stored
template<typename Wfn>
void SCPT<Wfn>::createDirForSCNorms()
{
// create ./norms
boost::filesystem::path pathNorms( boost::filesystem::current_path() / "norms" );
if (commrank == 0) {
if (!boost::filesystem::exists(pathNorms))
boost::filesystem::create_directory(pathNorms);
// create ./norms/exact
boost::filesystem::path pathNormsExact( boost::filesystem::current_path() / "norms/exact" );
if (!boost::filesystem::exists(pathNormsExact))
boost::filesystem::create_directory(pathNormsExact);
}
// wait for process 0 to create directory
MPI_Barrier(MPI_COMM_WORLD);
// create ./norms/proc_i
boost::filesystem::path pathNormsProc( boost::filesystem::current_path() / "norms/proc_" );
pathNormsProc += to_string(commrank);
if (!boost::filesystem::exists(pathNormsProc))
boost::filesystem::create_directory(pathNormsProc);
return;
}
// Create directories where the init_dets files will be stored
template<typename Wfn>
void SCPT<Wfn>::createDirForInitDets()
{
// create ./init_dets
boost::filesystem::path pathInitDets( boost::filesystem::current_path() / "init_dets" );
if (commrank == 0) {
if (!boost::filesystem::exists(pathInitDets))
boost::filesystem::create_directory(pathInitDets);
}
// wait for process 0 to create directory
MPI_Barrier(MPI_COMM_WORLD);
// create ./init_dets/proc_i
boost::filesystem::path pathInitDetsProc( boost::filesystem::current_path() / "init_dets/proc_" );
pathInitDetsProc += to_string(commrank);
if (!boost::filesystem::exists(pathInitDetsProc))
boost::filesystem::create_directory(pathInitDetsProc);
return;
}
// Create directories where the norm files will be stored
template<typename Wfn>
void SCPT<Wfn>::createDirForNormsBinary()
{
if (commrank == 0) {
// create ./norms
boost::filesystem::path pathNorms( boost::filesystem::current_path() / "norm_data" );
if (!boost::filesystem::exists(pathNorms))
boost::filesystem::create_directory(pathNorms);
}
// wait for process 0 to create directory
MPI_Barrier(MPI_COMM_WORLD);
// create ./norms/proc_i
boost::filesystem::path pathNormsProc( boost::filesystem::current_path() / "norm_data/proc_" );
pathNormsProc += to_string(commrank);
if (!boost::filesystem::exists(pathNormsProc))
boost::filesystem::create_directory(pathNormsProc);
return;
}
// Print norms to output files.
// If determClasses is true, only print the norms from classes where the
// norms are being found exactly.
// Otherwise, print the norms calculated stochastically, summed up until
// the current iteration. Also print the current estimate of the the
// CASCI energy, and the residence time.
template<typename Wfn>
void SCPT<Wfn>::printSCNorms(int& iter, double& deltaT_Tot, double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, bool determClasses)
{
if (! determClasses) {
// First print the CASCI energy estimate
string energyFileName = "norms/proc_" + to_string(commrank) + "/cas_energy_" + to_string(commrank) + ".dat";
ofstream out_energy;
out_energy.open(energyFileName);
out_energy << "Iteration: " << iter << endl;
out_energy.precision(12);
out_energy << scientific;
out_energy << "Total summed numerator for the CASCI energy: " << energyCAS_Tot << endl;
out_energy << "Total summed residence time: " << deltaT_Tot << endl;
out_energy.close();
}
// Next print the norms of each of the classes
for (int i=1; i<9; i++)
{
if (classesUsed[i]) {
if ((determClasses && normsDeterm[i]) || (!determClasses && !normsDeterm[i])) {
string fileName;
if (!determClasses)
fileName = "norms/proc_" + to_string(commrank) + "/norms_" + classNames[i] + "_" + to_string(commrank) + ".dat";
else
fileName = "norms/exact/norms_" + classNames[i] + "_exact.dat";
ofstream out_norms;
out_norms.open(fileName);
if (!determClasses)
out_norms << "Iteration: " << iter << endl;
else
out_norms << "Norms calculated deterministically" << endl;
out_norms.precision(12);
out_norms << scientific;
if (!determClasses)
out_norms << "Total summed residence time: " << deltaT_Tot << endl;
for (int ind = cumNumCoeffs[i]; ind < cumNumCoeffs[i]+numCoeffsPerClass[i]; ind++)
out_norms << norms_Tot(ind) << endl;
out_norms.close();
}
}
}
}
template<typename Wfn>
void SCPT<Wfn>::readStochNorms(double& deltaT_Tot, double& energyCAS_Tot, Eigen::VectorXd& norms_Tot)
{
std::string line;
vector<string> tok;
// Read CASCI energy
string energyFileName = "norms/proc_" + to_string(commrank) + "/cas_energy_" + to_string(commrank) + ".dat";
ifstream dump;
dump.open(energyFileName);
// First line contains the iteration number
std::getline(dump, line);
// Second line contains the energy as the final element
std::getline(dump, line);
boost::trim_if(line, boost::is_any_of(", \t\n"));
boost::split(tok, line, boost::is_any_of(", \t\n"), boost::token_compress_on);
energyCAS_Tot = stod(tok.back());
// Third line contains the residence time as the final element
std::getline(dump, line);
boost::trim_if(line, boost::is_any_of(", \t\n"));
boost::split(tok, line, boost::is_any_of(", \t\n"), boost::token_compress_on);
deltaT_Tot = stod(tok.back());
dump.close();
// Read in the stochastically-sampled norms
for (int i=1; i<9; i++)
{
if (classesUsed[i]) {
string fileName = "norms/proc_" + to_string(commrank) + "/norms_" +
classNames[i] + "_" + to_string(commrank) + ".dat";
ifstream dump;
dump.open(fileName);
// First two lines are not needed
std::getline(dump, line);
std::getline(dump, line);
int ind = cumNumCoeffs[i];
// Data starts on line 3
std::getline(dump, line);
while (dump.good())
{
boost::trim_if(line, boost::is_any_of(", \t\n"));
boost::split(tok, line, boost::is_any_of(", \t\n"), boost::token_compress_on);
norms_Tot[ind] = stod(tok[0]);
std::getline(dump, line);
ind++;
}
}
}
}
template<typename Wfn>
void SCPT<Wfn>::readDetermNorms(Eigen::VectorXd& norms_Tot)
{
std::string line;
vector<string> tok;
// Read in the exactly-calculated norms
for (int i=1; i<9; i++)
{
if (classesUsed[i] && normsDeterm[i]) {
string fileName = "norms/exact/norms_" + classNames[i] + "_exact.dat";
ifstream dump;
dump.open(fileName);
// First line is not needed
std::getline(dump, line);
int ind = cumNumCoeffs[i];
// Data starts on line 3
std::getline(dump, line);
while (dump.good())
{
boost::trim_if(line, boost::is_any_of(", \t\n"));
boost::split(tok, line, boost::is_any_of(", \t\n"), boost::token_compress_on);
norms_Tot[ind] = stod(tok[0]);
std::getline(dump, line);
ind++;
}
}
}
}
// Print initial determinants to output files
// We only need to print out the occupations in the active spaces
// The occupations of the core and virtual orbitals are determined
// from the label of the SC state, which is fixed by the deterministic
// ordering (the same as used in coeffsIndex).
template<typename Wfn>
void SCPT<Wfn>::printInitDets(vector<Determinant>& initDets, vector<double>& largestCoeffs)
{
// Loop over all classes
for (int i=1; i<9; i++)
{
if (classesUsed[i]) {
string fileName;
fileName = "init_dets/proc_" + to_string(commrank) + "/init_dets_" +
classNames[i] + "_" + to_string(commrank) + ".dat";
ofstream out_init_dets;
out_init_dets.open(fileName);
for (int ind = cumNumCoeffs[i]; ind < cumNumCoeffs[i]+numCoeffsPerClass[i]; ind++) {
out_init_dets << setprecision(12) << largestCoeffs[ind] << " ";
initDets[ind].printActive(out_init_dets);
out_init_dets << endl;
}
out_init_dets.close();
}
}
}
// read determinants in to the initDets array from previously output files
template<typename Wfn>
void SCPT<Wfn>::readInitDets(vector<Determinant>& initDets, vector<double>& largestCoeffs)
{
string fileName;
std::string line;
double coeff;
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
int numVirt = norbs - first_virtual;
// For each class, loop over all perturbers in the same order that they
// are printed in the init_dets files (which is the same ordering used
// in coeffsIndex)
// Currently this will only read in classes:
// AAAV, AAVV, CAAA, CAAV and CCAA
// First, create a determinant with all core orbitals doubly occupied:
Determinant detCAS;
for (int i=0; i<schd.nciCore; i++) {
detCAS.setoccA(i, true);
detCAS.setoccB(i, true);
}
// AAAV
fileName = "init_dets/proc_" + to_string(commrank) + "/init_dets_AAAV_" + to_string(commrank) + ".dat";
ifstream dump;
dump.open(fileName);
for (int r=2*first_virtual; r<2*norbs; r++) {
int ind = cumNumCoeffs[1] + r - 2*first_virtual;
std::getline(dump, line);
Determinant d(detCAS);
readDetActive(line, d, coeff);
d.setocc(r, true);
initDets[ind] = d;
largestCoeffs[ind] = coeff;
}
dump.close();
// AAVV
fileName = "init_dets/proc_" + to_string(commrank) + "/init_dets_AAVV_" + to_string(commrank) + ".dat";
dump.open(fileName);
for (int r=2*first_virtual+1; r<2*norbs; r++) {
for (int s=2*first_virtual; s<r; s++) {
int R = r - 2*first_virtual - 1;
int S = s - 2*first_virtual;
int ind = cumNumCoeffs[2] + R*(R+1)/2 + S;
std::getline(dump, line);
Determinant d(detCAS);
readDetActive(line, d, coeff);
d.setocc(r, true);
d.setocc(s, true);
initDets[ind] = d;
largestCoeffs[ind] = coeff;
}
}
dump.close();
// CAAA
fileName = "init_dets/proc_" + to_string(commrank) + "/init_dets_CAAA_" + to_string(commrank) + ".dat";
dump.open(fileName);
for (int i=0; i<2*schd.nciCore; i++) {
int ind = cumNumCoeffs[3] + i;
std::getline(dump, line);
Determinant d(detCAS);
readDetActive(line, d, coeff);
d.setocc(i, false);
initDets[ind] = d;
largestCoeffs[ind] = coeff;
}
dump.close();
// CAAV
fileName = "init_dets/proc_" + to_string(commrank) + "/init_dets_CAAV_" + to_string(commrank) + ".dat";
dump.open(fileName);
for (int i=0; i<2*schd.nciCore; i++) {
for (int r=2*first_virtual; r<2*norbs; r++) {
int ind = cumNumCoeffs[4] + 2*numVirt*i + (r - 2*schd.nciCore - 2*schd.nciAct);
std::getline(dump, line);
Determinant d(detCAS);
readDetActive(line, d, coeff);
d.setocc(i, false);
d.setocc(r, true);
initDets[ind] = d;
largestCoeffs[ind] = coeff;
}
}
dump.close();
// CCAA
fileName = "init_dets/proc_" + to_string(commrank) + "/init_dets_CCAA_" + to_string(commrank) + ".dat";
dump.open(fileName);
for (int i=1; i<2*schd.nciCore; i++) {
for (int j=0; j<i; j++) {
int ind = cumNumCoeffs[6] + (i-1)*i/2 + j;
std::getline(dump, line);
Determinant d(detCAS);
readDetActive(line, d, coeff);
d.setocc(i, false);
d.setocc(j, false);
initDets[ind] = d;
largestCoeffs[ind] = coeff;
}
}
dump.close();
}
// From a given line of an output file, containing only the occupations of
// orbitals within the active space, construct the corresponding determinant
// (with all core obritals occupied, all virtual orbitals unocuppied).
// This is specifically used by for readInitDets
template<typename Wfn>
void SCPT<Wfn>::readDetActive(string& line, Determinant& det, double& coeff)
{
boost::trim_if(line, boost::is_any_of(", \t\n"));
vector<string> tok;
boost::split(tok, line, boost::is_any_of(", \t\n"), boost::token_compress_on);
coeff = stod(tok[0]);
int offset = schd.nciCore;
for (int i=0; i<schd.nciAct; i++)
{
if (boost::iequals(tok[i+1], "2"))
{
det.setoccA(i+offset, true);
det.setoccB(i+offset, true);
}
else if (boost::iequals(tok[i+1], "a"))
{
det.setoccA(i+offset, true);
det.setoccB(i+offset, false);
}
if (boost::iequals(tok[i+1], "b"))
{
det.setoccA(i+offset, false);
det.setoccB(i+offset, true);
}
if (boost::iequals(tok[i+1], "0"))
{
det.setoccA(i+offset, false);
det.setoccB(i+offset, false);
}
}
}
template<typename Wfn>
void SCPT<Wfn>::printNormDataBinary(vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, double& deltaT_Tot)
{
if (commrank == 0) cout << "About to print norm data..." << endl;
string name_1 = "norm_data/proc_" + to_string(commrank) + "/norms_" + to_string(commrank) + ".bkp";
ofstream file_1(name_1, std::ios::binary);
boost::archive::binary_oarchive oa1(file_1);
oa1 << norms_Tot;
file_1.close();
string name_2 = "norm_data/proc_" + to_string(commrank) + "/init_dets_" + to_string(commrank) + ".bkp";
ofstream file_2(name_2, std::ios::binary);
boost::archive::binary_oarchive oa2(file_2);
oa2 << initDets;
file_2.close();
string name_3 = "norm_data/proc_" + to_string(commrank) + "/coeffs_" + to_string(commrank) + ".bkp";
ofstream file_3(name_3, std::ios::binary);
boost::archive::binary_oarchive oa3(file_3);
oa3 << largestCoeffs;
file_3.close();
string name_4 = "norm_data/proc_" + to_string(commrank) + "/energy_cas_" + to_string(commrank) + ".bkp";
ofstream file_4(name_4, std::ios::binary);
boost::archive::binary_oarchive oa4(file_4);
oa4 << energyCAS_Tot;
file_4.close();
string name_5 = "norm_data/proc_" + to_string(commrank) + "/delta_t_" + to_string(commrank) + ".bkp";
ofstream file_5(name_5, std::ios::binary);
boost::archive::binary_oarchive oa5(file_5);
oa5 << deltaT_Tot;
file_5.close();
if (commrank == 0) cout << "Printing complete." << endl << endl;
}
template<typename Wfn>
void SCPT<Wfn>::readNormDataBinary(vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, double& deltaT_Tot, bool readDeltaT)
{
if (commrank == 0) cout << "About to read norm data..." << endl;
string name_1 = "norm_data/proc_" + to_string(commrank) + "/norms_" + to_string(commrank) + ".bkp";
ifstream file_1(name_1, std::ios::binary);
boost::archive::binary_iarchive oa1(file_1);
oa1 >> norms_Tot;
file_1.close();
string name_2 = "norm_data/proc_" + to_string(commrank) + "/init_dets_" + to_string(commrank) + ".bkp";
ifstream file_2(name_2, std::ios::binary);
boost::archive::binary_iarchive oa2(file_2);
oa2 >> initDets;
file_2.close();
string name_3 = "norm_data/proc_" + to_string(commrank) + "/coeffs_" + to_string(commrank) + ".bkp";
ifstream file_3(name_3, std::ios::binary);
boost::archive::binary_iarchive oa3(file_3);
oa3 >> largestCoeffs;
file_3.close();
string name_4 = "norm_data/proc_" + to_string(commrank) + "/energy_cas_" + to_string(commrank) + ".bkp";
ifstream file_4(name_4, std::ios::binary);
boost::archive::binary_iarchive oa4(file_4);
oa4 >> energyCAS_Tot;
file_4.close();
if (readDeltaT) {
string name_5 = "norm_data/proc_" + to_string(commrank) + "/delta_t_" + to_string(commrank) + ".bkp";
ifstream file_5(name_5, std::ios::binary);
boost::archive::binary_iarchive oa5(file_5);
oa5 >> deltaT_Tot;
file_5.close();
}
if (commrank == 0) cout << "Reading complete." << endl << endl;
}
template<typename Wfn>
void SCPT<Wfn>::readNormDataText(vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, double& deltaT_Tot)
{
// Read in the stochastically-sampled norms
if (commrank == 0) cout << "About to read stochastically-sampled norms..." << endl;
readStochNorms(deltaT_Tot, energyCAS_Tot, norms_Tot);
if (commrank == 0) cout << "Reading complete." << endl;
energyCAS_Tot /= deltaT_Tot;
norms_Tot /= deltaT_Tot;
if (commrank == 0) cout << "About to read exactly-calculated norms..." << endl;
readDetermNorms(norms_Tot);
if (commrank == 0) cout << "Reading complete." << endl;
// Read in the exactly-calculated norms
if (commrank == 0) cout << "About to read initial determinants..." << endl;
readInitDets(initDets, largestCoeffs);
if (commrank == 0) cout << "Reading complete." << endl;
if (commrank == 0) cout << endl;
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::doNEVPT2_CT_Efficient(Walker& walk) {
double energy_ccvv = 0.0;
if (commrank == 0) {
cout << "Integrals and wave function preparation finished in " << getTime() - startofCalc << " s\n";
if (any_of(classesUsedDeterm.begin(), classesUsedDeterm.end(), [](bool i){return i;}) ) {
if (classesUsedDeterm[8])
{
energy_ccvv = get_ccvv_energy();
cout << endl << "Deterministic CCVV energy: " << setprecision(12) << energy_ccvv << endl << endl;
}
}
}
if (schd.SCNormsBurnIn >= schd.stochasticIterNorms) {
if (commrank == 0) {
cout << "WARNING: The number of sampling iterations for N_l^k estimation is"
" not larger than the number of burn-in iterations. Setting the number"
" of burn-in iterations to 0." << endl << endl;
}
schd.SCNormsBurnIn = 0;
}
if (schd.SCEnergiesBurnIn >= schd.stochasticIterEachSC) {
if (commrank == 0) {
cout << "WARNING: The number of sampling iterations for E_l^k estimation is"
" not larger than the number of burn-in iterations. Setting the number"
" of burn-in iterations to 0." << endl << endl;
}
schd.SCEnergiesBurnIn = 0;
}
MPI_Barrier(MPI_COMM_WORLD);
if (commrank == 0) cout << "About to sample the norms of the strongly contracted states..." << endl << endl;
double timeNormsInit = getTime();
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
workingArray work;
double ham = 0., hamSample = 0., ovlp = 0.;
double deltaT = 0., deltaT_Tot = 0.;
double energyCAS = 0., energyCAS_Tot = 0.;
if (commrank == 0) {
cout << "About to allocate arrays for sampling..." << endl;
cout << "Total number of strongly contracted states to sample: " << numCoeffs << endl;
}
VectorXd normSamples = VectorXd::Zero(coeffs.size());
VectorXd norms_Tot = VectorXd::Zero(coeffs.size());
if (schd.printSCNorms) createDirForNormsBinary();
// As we calculate the SC norms, we will simultaneously find the determinants
// within each SC space that have the highest coefficient, as found during
// the sampling. These quantities are searched for in the following arrays.
vector<Determinant> initDets;
initDets.resize(numCoeffs, walk.d);
vector<double> largestCoeffs;
largestCoeffs.resize(numCoeffs, 0.0);
MPI_Barrier(MPI_COMM_WORLD);
if (commrank == 0) cout << "Allocation of sampling arrays now finished." << endl << endl;
if (schd.continueSCNorms) {
readNormDataBinary(initDets, largestCoeffs, energyCAS_Tot, norms_Tot, deltaT_Tot, true);
energyCAS_Tot *= deltaT_Tot;
norms_Tot *= deltaT_Tot;
}
// If we are generating the norms stochastically here, rather than
// reading them back in:
if (!schd.readSCNorms)
{
if (commrank == 0) cout << "About to call first instance of HamAndSCNorms..." << endl;
HamAndSCNorms(walk, ovlp, hamSample, normSamples, initDets, largestCoeffs, work, false);
if (commrank == 0) cout << "First instance of HamAndSCNorms complete." << endl;
int iter = 1;
int printMod;
if (schd.fixedResTimeNEVPT_Norm) {
printMod = 10;
} else {
printMod = max(1, schd.stochasticIterNorms / 10);
}
if (commrank == 0) {
cout << "iter: 0" << " t: " << setprecision(6) << getTime() - startofCalc << endl;
}
while (true) {
// Condition for exiting loop:
// This depends on what 'mode' we are running in - constant
// residence time, or constant iteration count
if (schd.fixedResTimeNEVPT_Norm) {
if (deltaT_Tot >= schd.resTimeNEVPT_Norm)
break;
} else {
if (iter > schd.stochasticIterNorms)
break;
}
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
if (iter > schd.SCNormsBurnIn)
{
double deltaT = 1.0 / (cumovlpRatio);
energyCAS = deltaT * hamSample;
normSamples *= deltaT;
// These hold the running totals
deltaT_Tot += deltaT;
energyCAS_Tot += energyCAS;
norms_Tot += normSamples;
}
//if (schd.printSCNorms && iter % schd.printSCNormFreq == 0)
// printSCNorms(iter, deltaT_Tot, energyCAS_Tot, norms_Tot, false);
// Pick the next determinant by the CTMC algorithm
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
if (walk.excitation_class != 0) cout << "ERROR: walker not in CASCI space!" << endl;
normSamples.setZero();
// For schd.nIterFindInitDets iterations, we want to sample the
// norms for *all* S_l^k, including those for which we can find
// N_l^k exactly (this allows us to generate initital determinants).
// This is the condition for the iterations in which we do this:
bool sampleAllNorms;
if (schd.fixedResTimeNEVPT_Norm) {
// In this case, we use the first schd.nIterFindInitDets iterations
// *after* the burn-in period.
sampleAllNorms = (iter >= schd.SCNormsBurnIn) && (iter < schd.SCNormsBurnIn + schd.nIterFindInitDets);
} else {
// In this case, we just use the final schd.nIterFindInitDets iterations.
sampleAllNorms = schd.stochasticIterNorms - schd.nIterFindInitDets < iter;
}
HamAndSCNorms(walk, ovlp, hamSample, normSamples, initDets, largestCoeffs, work, sampleAllNorms);
if (commrank == 0 && (iter % printMod == 0 || iter == 1))
cout << "iter: " << iter << " t: " << setprecision(6) << getTime() - startofCalc << endl;
iter++;
}
int samplingIters = iter - schd.SCNormsBurnIn - 1;
//cout << "proc: " << commrank << " samplingIters: " << samplingIters << endl;
energyCAS_Tot /= deltaT_Tot;
norms_Tot /= deltaT_Tot;
if (any_of(normsDeterm.begin(), normsDeterm.end(), [](bool i){return i;}) )
{
MatrixXd oneRDM, twoRDM;
readSpinRDM(oneRDM, twoRDM);
if (normsDeterm[2])
calc_AAVV_NormsFromRDMs(twoRDM, norms_Tot);
if (normsDeterm[4])
calc_CAAV_NormsFromRDMs(oneRDM, twoRDM, norms_Tot);
if (normsDeterm[6])
calc_CCAA_NormsFromRDMs(oneRDM, twoRDM, norms_Tot);
if (schd.printSCNorms && commrank == 0)
printSCNorms(iter, deltaT_Tot, energyCAS_Tot, norms_Tot, true);
}
if (commrank == 0)
{
cout << endl << "Calculation of strongly contracted norms complete." << endl;
cout << "Total time for norms calculation: " << getTime() - timeNormsInit << endl << endl;
}
}
if (schd.readSCNorms) {
readNormDataBinary(initDets, largestCoeffs, energyCAS_Tot, norms_Tot, deltaT_Tot, false);
}
if (schd.printSCNorms && (!schd.readSCNorms)) {
printNormDataBinary(initDets, largestCoeffs, energyCAS_Tot, norms_Tot, deltaT_Tot);
}
if (schd.sampleNEVPT2Energy) {
if (commrank == 0) {
cout << "Now sampling the NEVPT2 energy..." << endl;
}
// Next we calculate the SC state energies and the final PT2 energy estimate
double timeEnergyInit = getTime();
double ene2;
if (schd.efficientNEVPT_2) {
ene2 = sampleSCEnergies(walk, initDets, largestCoeffs, energyCAS_Tot, norms_Tot, work);
}
if (schd.efficientNEVPT || schd.exactE_NEVPT) {
ene2 = sampleAllSCEnergies(walk, initDets, largestCoeffs, energyCAS_Tot, norms_Tot, work);
}
if (schd.NEVPT_writeE || schd.NEVPT_readE) {
ene2 = calcAllSCEnergiesExact(walk, initDets, largestCoeffs, energyCAS_Tot, norms_Tot, work);
}
if (commrank == 0) {
cout << "Sampling complete." << endl << endl;
cout << "Total time for energy sampling " << getTime() - timeEnergyInit << " seconds" << endl;
cout << "CAS energy: " << setprecision(10) << energyCAS_Tot << endl;
cout << "SC-NEVPT2(s) second-order energy: " << setprecision(10) << ene2 << endl;
cout << "Total SC-NEVPT(s) energy: " << setprecision(10) << energyCAS_Tot + ene2 << endl;
if (any_of(classesUsedDeterm.begin(), classesUsedDeterm.end(), [](bool i){return i;}) ) {
if (classesUsedDeterm[8])
{
cout << "SC-NEVPT2(s) second-order energy with CCVV: " << energy_ccvv + ene2 << endl;
cout << "Total SC-NEVPT2(s) energy with CCVV: " << energyCAS_Tot + ene2 + energy_ccvv << endl;
}
}
}
} // If sampling the energy
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::sampleSCEnergies(Walker& walk, vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, workingArray& work)
{
vector<double> cumNorm;
cumNorm.resize(numCoeffs, 0.0);
vector<int> indexMap;
indexMap.resize(numCoeffs, 0);
int numCoeffsToSample = 0;
double totCumNorm = 0.;
for (int i = 1; i < numCoeffs; i++) {
if (norms_Tot(i) > schd.overlapCutoff) {
totCumNorm += norms_Tot(i);
cumNorm[numCoeffsToSample] = totCumNorm;
initDets[numCoeffsToSample] = initDets[i];
largestCoeffs[numCoeffsToSample] = largestCoeffs[i];
indexMap[numCoeffsToSample] = i;
numCoeffsToSample += 1;
}
}
if (commrank == 0) {
cout << "Total cumulative squared norm (process 0): " << totCumNorm << endl << endl;
}
double energySample = 0., energyTot = 0, biasTot = 0;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
FILE * pt2_out;
string pt2OutName = "pt2_energies_";
pt2OutName.append(to_string(commrank));
pt2OutName.append(".dat");
pt2_out = fopen(pt2OutName.c_str(), "w");
fprintf(pt2_out, "# 1. iter 2. energy 3. E_0 - E_l^k 4. E_l^K variance "
"5. Bias correction 6. class 7. C/V orbs 8. niters 9. time\n");
double timeInTotal = getTime();
int orbi, orbj;
int iter = 0;
while (iter < schd.numSCSamples) {
double timeIn = getTime();
double nextSCRandom = random() * totCumNorm;
int nextSC = std::lower_bound(cumNorm.begin(), (cumNorm.begin() + numCoeffsToSample), nextSCRandom) - cumNorm.begin();
if (abs(largestCoeffs[nextSC]) < 1.e-15) cout << "Error: no initial determinant found: " << setprecision(20) << largestCoeffs[nextSC] << endl;
this->wave.initWalker(walk, initDets[nextSC]);
double SCHam, SCHamVar;
int samplingIters;
if (schd.printSCEnergies) {
SCHam = doSCEnergyCTMCPrint(walk, work, iter, schd.nWalkSCEnergies);
} else {
doSCEnergyCTMC(walk, work, SCHam, SCHamVar, samplingIters);
}
// If this same SC sector is sampled again, start from the final
// determinant from this time:
if (schd.continueMarkovSCPT) initDets[nextSC] = walk.d;
energySample = totCumNorm / (energyCAS_Tot - SCHam);
double biasCorr = - totCumNorm * ( SCHamVar / pow( energyCAS_Tot - SCHam, 3) );
energyTot += energySample;
biasTot += biasCorr;
double timeOut = getTime();
double eDiff = energyCAS_Tot - SCHam;
// Get the external orbs of the perturber, for printing
getOrbsFromIndex(indexMap[nextSC], orbi, orbj);
string orbString = formatOrbString(orbi, orbj);
fprintf(pt2_out, "%9d %.12e %.12e %.12e %.12e %4s %12s %8d %.4e\n",
iter, energySample, eDiff, SCHamVar, biasCorr,
classNames2[walk.excitation_class].c_str(),
orbString.c_str(), samplingIters, timeOut-timeIn);
fflush(pt2_out);
iter++;
}
double timeOutTotal = getTime();
double timeTotal = timeOutTotal - timeInTotal;
fclose(pt2_out);
energyTot /= iter;
biasTot /= iter;
// Average over MPI processes
double energyFinal = 0., biasFinal = 0.;
#ifndef SERIAL
// Check how long processes have to wait for other MPI processes to finish
double timeIn = getTime();
MPI_Barrier(MPI_COMM_WORLD);
double timeOut = getTime();
if (commrank == 0) cout << "MPI Barrier time: " << timeOut-timeIn << " seconds" << endl;
// Gather and print energy estimates from all MPI processes
double energyTotAll[commsize];
MPI_Gather(&(energyTot), 1, MPI_DOUBLE, &(energyTotAll), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
double biasTotAll[commsize];
MPI_Gather(&(biasTot), 1, MPI_DOUBLE, &(biasTotAll), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
// Gather the total time on each process
double timeTotalAll[commsize];
MPI_Gather(&(timeTotal), 1, MPI_DOUBLE, &(timeTotalAll), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if (commrank == 0) {
// Print final estimates from each process
FILE * mpi_out;
mpi_out = fopen("pt2_energies_avg.dat", "w");
fprintf(mpi_out, "# 1. proc label 2. energy "
"3. bias correction 4. time\n");
for (int i=0; i<commsize; i++) {
fprintf(mpi_out, "%15d %.12e %.12e %.6e\n",
i, energyTotAll[i], biasTotAll[i], timeTotalAll[i]);
}
fclose(mpi_out);
// Calculate the energy and bias averaged over all processes
for (int i=0; i<commsize; i++) {
energyFinal += energyTotAll[i];
biasFinal += biasTotAll[i];
}
energyFinal /= commsize;
biasFinal /= commsize;
// Calculate the standard error for the energy and bias estimates
double stdDevEnergy = 0., stdDevBias = 0.;
for (int i=0; i<commsize; i++) {
stdDevEnergy += pow( energyTotAll[i] - energyFinal, 2 );
stdDevBias += pow( biasTotAll[i] - biasFinal, 2 );
}
stdDevEnergy /= commsize - 1;
stdDevBias /= commsize - 1;
cout.precision(12);
cout << "Energy error estimate: " << sqrt(stdDevEnergy / commsize) << endl;
cout << "Bias correction error estimate: " << sqrt(stdDevBias / commsize) << endl;
}
MPI_Bcast(&energyFinal, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&biasFinal, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#else
energyFinal = energyTot;
biasFinal = biasTot;
#endif
// Final energy returned includes the bias correction estimate
return energyFinal + biasFinal;
}
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::doSCEnergyCTMC(Walker& walk, workingArray& work, double& final_ham, double& var, int& samplingIters)
{
double ham = 0., hamSample = 0., ovlp = 0.;
double numerator = 0., numerator_Tot = 0.;
double deltaT = 0., deltaT_Tot = 0.;
int nSampleIters = schd.stochasticIterEachSC - schd.SCEnergiesBurnIn;
vector<double> x, w;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
//int coeffsIndexCopy = this->coeffsIndex(walk);
//if (coeffsIndexCopy != ind) cout << "ERROR at 1: " << ind << " " << coeffsIndexCopy << endl;
// Now, sample the SC energy in this space
FastHamAndOvlp(walk, ovlp, hamSample, work);
int iter = 0;
while (true) {
// Condition for exiting loop:
// This depends on what 'mode' we are running in - constant
// residence time, or constant iteration count
if (schd.fixedResTimeNEVPT_Ene) {
if (deltaT_Tot >= schd.resTimeNEVPT_Ene)
break;
} else {
if (iter >= schd.stochasticIterEachSC)
break;
}
double cumovlpRatio = 0.;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
// Only start accumulating data if beyond the burn-in period
if (iter >= schd.SCEnergiesBurnIn) {
deltaT = 1.0 / (cumovlpRatio);
numerator = deltaT*hamSample;
x.push_back(hamSample);
w.push_back(deltaT);
numerator_Tot += numerator;
deltaT_Tot += deltaT;
}
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
//int coeffsIndexCopy = this->coeffsIndex(walk);
//if (coeffsIndexCopy != ind) cout << "ERROR at 2: " << ind << " " << coeffsIndexCopy << endl;
FastHamAndOvlp(walk, ovlp, hamSample, work);
iter++;
}
samplingIters = iter - schd.SCEnergiesBurnIn;
final_ham = numerator_Tot/deltaT_Tot;
// Estimate the error on final_ham
var = SCEnergyVar(x, w);
}
// Estimate the variance of the weighted mean used to estimate E_l^k
template<typename Wfn>
double SCPT<Wfn>::SCEnergyVar(vector<double>& x, vector<double>& w)
{
// This uses blocks of data, to account for the serial correlation
int n = x.size();
// If we only have one sample, we can't estimate the variance, so
// just return 0 instead
if (n == 1)
{
return 0.0;
}
int block_size = min(n/5, 16);
if (block_size < 1) {
block_size = 1;
}
int nblocks = n/block_size;
vector<double> x_1, w_1;
x_1.assign(nblocks, 0.0);
w_1.assign(nblocks, 0.0);
for (int i = 0; i < nblocks; i++)
{
for (int j = 0; j < block_size; j++)
{
w_1[i] += w[block_size*i + j];
x_1[i] += w[block_size*i + j] * x[block_size*i + j];
}
x_1[i] /= w_1[i];
}
n = nblocks;
x = x_1;
w = w_1;
double x_bar = 0.0, W = 0.0;
for (int i = 0; i < n; i++)
{
x_bar += w[i] * x[i];
W += w[i];
}
x_bar /= W;
double var = 0.;
for (int i = 0; i < n; i++)
{
var += pow(w[i]*x[i] - W*x_bar, 2)
- 2*x_bar*(w[i] - W)*(w[i]*x[i] - W*x_bar)
+ pow(x_bar, 2) * pow(w[i] - W, 2);
}
var *= n / (n - 1.0);
var /= pow(W, 2);
return var;
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::doSCEnergyCTMCPrint(Walker& walk, workingArray& work, int sampleIter, int nWalk)
{
double ham = 0., hamSample = 0., ovlp = 0.;
double numerator = 0., numerator_Tot = 0.;
double deltaT = 0., deltaT_Tot = 0.;
vector<double> numerator_Avg(schd.stochasticIterEachSC, 0.0);
vector<double> deltaT_Avg(schd.stochasticIterEachSC, 0.0);
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
Determinant initDet = walk.d;
FILE * out;
string outputFile = "sc_energies.";
outputFile.append(to_string(commrank));
outputFile.append(".");
outputFile.append(to_string(sampleIter));
out = fopen(outputFile.c_str(), "w");
fprintf(out, "# 1. iteration 2. weighted_energy 3. residence_time\n");
//int coeffsIndexCopy = this->coeffsIndex(walk);
//if (coeffsIndexCopy != ind) cout << "ERROR at 1: " << ind << " " << coeffsIndexCopy << endl;
for (int i=0; i<nWalk; i++) {
// Reinitialize the walker
this->wave.initWalker(walk, initDet);
// Now, sample the SC energy in this space
FastHamAndOvlp(walk, ovlp, hamSample, work);
int iter = 0;
while (iter < schd.stochasticIterEachSC) {
double cumovlpRatio = 0.;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
deltaT = 1.0 / (cumovlpRatio);
numerator = deltaT*hamSample;
numerator_Avg[iter] += numerator;
deltaT_Avg[iter] += deltaT;
numerator_Tot += numerator;
deltaT_Tot += deltaT;
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
//int coeffsIndexCopy = this->coeffsIndex(walk);
//if (coeffsIndexCopy != ind) cout << "ERROR at 2: " << ind << " " << coeffsIndexCopy << endl;
FastHamAndOvlp(walk, ovlp, hamSample, work);
iter++;
}
}
double final_ham = numerator_Tot/deltaT_Tot;
for (int i=0; i<schd.stochasticIterEachSC; i++) {
fprintf(out, "%14d %.12e %.12e\n", i, numerator_Avg[i], deltaT_Avg[i]);
}
fclose(out);
return final_ham;
}
// Wrapper function for calling doSCEnergyCTMC, which estimates E_l^k,
// given the appropriate input information, and then to print this info
// to the provded pt2_out file.
// This is designed to be called by sampleAllSCEnergies.
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::SCEnergyWrapper(Walker& walk, int iter, FILE * pt2_out, Determinant& det,
double& energyCAS_Tot, double norm, int orbi, int orbj,
bool exactCalc, bool exactRead, double& SCHam, workingArray& work) {
double SCHamVar = 0.;
int samplingIters = 0;
double timeIn = getTime();
this->wave.initWalker(walk, det);
// If we have already read in SCHam, then we don't need to
// calculate or sample it here.
if (!exactRead) {
if (exactCalc) {
doSCEnergyExact(walk, work, SCHam, SCHamVar, samplingIters);
}
else {
doSCEnergyCTMC(walk, work, SCHam, SCHamVar, samplingIters);
}
}
double energySample = norm / (energyCAS_Tot - SCHam);
double biasCorr = - norm * ( SCHamVar / pow( energyCAS_Tot - SCHam, 3) );
double eDiff = energyCAS_Tot - SCHam;
string orbString = formatOrbString(orbi, orbj);
double timeOut = getTime();
fprintf(pt2_out, "%9d %.12e %.12e %.12e %.12e %4s %12s %8d %.4e\n",
iter, energySample, eDiff, SCHamVar, biasCorr,
classNames2[walk.excitation_class].c_str(),
orbString.c_str(), samplingIters, timeOut-timeIn);
fflush(pt2_out);
return energySample;
}
// Loop over *all* S_l^k subspaces (for the classes AAAV, AAVV, CAAA,
// CAAV and CCAA) for which the calculated norm is above the threshold,
// and sample E_l^k for each. The final PT2 energy is then output as a
// sum over all of these spaces.
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::sampleAllSCEnergies(Walker& walk, vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, workingArray& work)
{
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
int numVirt = norbs - first_virtual;
double ene2 = 0., SCHam = 0.;
FILE * pt2_out;
string pt2OutName = "pt2_energies_";
pt2OutName.append(to_string(commrank));
pt2OutName.append(".dat");
pt2_out = fopen(pt2OutName.c_str(), "w");
fprintf(pt2_out, "# 1. iter 2. energy 3. E_0 - E_l^k 4. E_l^K variance "
"5. Bias correction 6. class 7. C/V orbs 8. niters 9. time\n");
int iter = 0;
// AAAV
for (int r=2*first_virtual; r<2*norbs; r++) {
int ind = cumNumCoeffs[1] + r - 2*first_virtual;
if (norms_Tot(ind) > schd.overlapCutoff) {
if (largestCoeffs[ind] == 0.0) cout << "Error: No initial determinant found. " << r << endl;
int orb1 = r;
int orb2 = -1;
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDets[ind], energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.exactE_NEVPT, false, SCHam, work);
iter++;
}
}
// AAVV
for (int r=2*first_virtual+1; r<2*norbs; r++) {
for (int s=2*first_virtual; s<r; s++) {
int R = r - 2*first_virtual - 1;
int S = s - 2*first_virtual;
int ind = cumNumCoeffs[2] + R*(R+1)/2 + S;
if (norms_Tot(ind) > schd.overlapCutoff) {
if (largestCoeffs[ind] == 0.0) {
cout << "Warning: No initial determinant found. " << r << " " << s << endl;
continue;
}
int orb1 = r;
int orb2 = s;
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDets[ind], energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.exactE_NEVPT, false, SCHam, work);
iter++;
}
}
}
// CAAA
for (int i=0; i<2*schd.nciCore; i++) {
int ind = cumNumCoeffs[3] + i;
if (norms_Tot(ind) > schd.overlapCutoff) {
if (largestCoeffs[ind] == 0.0) cout << "Error: No initial determinant found. " << i << endl;
int orb1 = i;
int orb2 = -1;
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDets[ind], energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.exactE_NEVPT, false, SCHam, work);
iter++;
}
}
// CAAV
for (int i=0; i<2*schd.nciCore; i++) {
for (int r=2*first_virtual; r<2*norbs; r++) {
int ind = cumNumCoeffs[4] + 2*numVirt*i + (r - 2*schd.nciCore - 2*schd.nciAct);
if (norms_Tot(ind) > schd.overlapCutoff) {
if (largestCoeffs[ind] == 0.0) {
cout << "Warning: No initial determinant found. " << i << " " << r << endl;
continue;
}
int orb1 = i;
int orb2 = r;
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDets[ind], energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.exactE_NEVPT, false, SCHam, work);
iter++;
}
}
}
// CCAA
for (int i=1; i<2*schd.nciCore; i++) {
for (int j=0; j<i; j++) {
int ind = cumNumCoeffs[6] + (i-1)*i/2 + j;
if (norms_Tot(ind) > schd.overlapCutoff) {
if (largestCoeffs[ind] == 0.0) {
cout << "Warning: No initial determinant found. " << i << " " << j << endl;
continue;
}
int orb1 = i;
int orb2 = j;
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDets[ind], energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.exactE_NEVPT, false, SCHam, work);
iter++;
}
}
}
fclose(pt2_out);
return ene2;
}
// Loop over *all* S_l^k subspaces (for the classes AAAV, AAVV, CAAA,
// CAAV and CCAA), and either exactly calculate of read in E_l^k for each.
// The final PT2 energy is then output as a sum over all of these spaces.
//
// The difference between this and sampleAllSCEnergies is that *all*
// S_l^k are considered, even if the norm was calculated as zero, if run
// in write mode, and all E_l^k are then written out. If run in read mode,
// then all E_l^k are read in from this file instead, for quick calculation.
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::calcAllSCEnergiesExact(Walker& walk, vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, workingArray& work)
{
vector<double> exactEnergies;
if (schd.NEVPT_readE) {
string name = "exact_energies.bkp";
ifstream file(name, std::ios::binary);
boost::archive::binary_iarchive oa(file);
oa >> exactEnergies;
file.close();
}
else {
exactEnergies.resize(numCoeffs, 0.0);
}
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
int numVirt = norbs - first_virtual;
double ene2 = 0., SCHam = 0.;
FILE * pt2_out;
string pt2OutName = "pt2_energies_";
pt2OutName.append(to_string(commrank));
pt2OutName.append(".dat");
pt2_out = fopen(pt2OutName.c_str(), "w");
fprintf(pt2_out, "# 1. iter 2. energy 3. E_0 - E_l^k 4. E_l^K variance "
"5. Bias correction 6. class 7. C/V orbs 8. niters 9. time\n");
int iter = 0;
// AAAV
for (int r=2*first_virtual; r<2*norbs; r++) {
int ind = cumNumCoeffs[1] + r - 2*first_virtual;
int orb1 = r;
int orb2 = -1;
Determinant initDet = generateInitDet(orb1, orb2);
if (schd.NEVPT_readE) SCHam = exactEnergies.at(ind);
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDet, energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.NEVPT_writeE, schd.NEVPT_readE, SCHam, work);
if (schd.NEVPT_writeE) exactEnergies.at(ind) = SCHam;
iter++;
}
// AAVV
for (int r=2*first_virtual+1; r<2*norbs; r++) {
for (int s=2*first_virtual; s<r; s++) {
int R = r - 2*first_virtual - 1;
int S = s - 2*first_virtual;
int ind = cumNumCoeffs[2] + R*(R+1)/2 + S;
int orb1 = r;
int orb2 = s;
Determinant initDet = generateInitDet(orb1, orb2);
if (schd.NEVPT_readE) SCHam = exactEnergies.at(ind);
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDet, energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.NEVPT_writeE, schd.NEVPT_readE, SCHam, work);
if (schd.NEVPT_writeE) exactEnergies.at(ind) = SCHam;
exactEnergies.at(ind) = SCHam;
iter++;
}
}
// CAAA
for (int i=0; i<2*schd.nciCore; i++) {
int ind = cumNumCoeffs[3] + i;
int orb1 = i;
int orb2 = -1;
Determinant initDet = generateInitDet(orb1, orb2);
if (schd.NEVPT_readE) SCHam = exactEnergies.at(ind);
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDet, energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.NEVPT_writeE, schd.NEVPT_readE, SCHam, work);
if (schd.NEVPT_writeE) exactEnergies.at(ind) = SCHam;
exactEnergies.at(ind) = SCHam;
iter++;
}
// CAAV
for (int i=0; i<2*schd.nciCore; i++) {
for (int r=2*first_virtual; r<2*norbs; r++) {
int ind = cumNumCoeffs[4] + 2*numVirt*i + (r - 2*schd.nciCore - 2*schd.nciAct);
int orb1 = i;
int orb2 = r;
Determinant initDet = generateInitDet(orb1, orb2);
if (schd.NEVPT_readE) SCHam = exactEnergies.at(ind);
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDet, energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.NEVPT_writeE, schd.NEVPT_readE, SCHam, work);
if (schd.NEVPT_writeE) exactEnergies.at(ind) = SCHam;
exactEnergies.at(ind) = SCHam;
iter++;
}
}
// CCAA
for (int i=1; i<2*schd.nciCore; i++) {
for (int j=0; j<i; j++) {
int ind = cumNumCoeffs[6] + (i-1)*i/2 + j;
int orb1 = i;
int orb2 = j;
Determinant initDet = generateInitDet(orb1, orb2);
if (schd.NEVPT_readE) SCHam = exactEnergies.at(ind);
ene2 += SCEnergyWrapper(walk, iter, pt2_out, initDet, energyCAS_Tot,
norms_Tot(ind), orb1, orb2, schd.NEVPT_writeE, schd.NEVPT_readE, SCHam, work);
if (schd.NEVPT_writeE) exactEnergies.at(ind) = SCHam;
exactEnergies.at(ind) = SCHam;
iter++;
}
}
fclose(pt2_out);
if (schd.NEVPT_writeE) {
string name = "exact_energies.bkp";
ofstream file(name, std::ios::binary);
boost::archive::binary_oarchive oa(file);
oa << exactEnergies;
file.close();
}
return ene2;
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::doSCEnergyCTMCSync(Walker& walk, int& ind, workingArray& work, string& outputFile)
{
FILE * out;
if (commrank == 0) {
out = fopen(outputFile.c_str(), "w");
fprintf(out, "# 1. iteration 2. weighted_energy 3. residence_time\n");
}
double ham = 0., hamSample = 0., ovlp = 0.;
double numerator = 0., numerator_MPI = 0., numerator_Tot = 0.;
double deltaT = 0., deltaT_Tot = 0., deltaT_MPI = 0.;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
int coeffsIndexCopy = this->coeffsIndex(walk);
if (coeffsIndexCopy != ind) cout << "ERROR at 1: " << ind << " " << coeffsIndexCopy << endl;
// Now, sample the SC energy in this space
FastHamAndOvlp(walk, ovlp, hamSample, work);
int iter = 0;
while (iter < schd.stochasticIterEachSC) {
double cumovlpRatio = 0.;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
deltaT = 1.0 / (cumovlpRatio);
numerator = deltaT*hamSample;
#ifndef SERIAL
MPI_Allreduce(&(numerator), &(numerator_MPI), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&(deltaT), &(deltaT_MPI), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#else
numerator_MPI = numerator;
deltaT_MPI = deltaT;
#endif
if (commrank == 0) fprintf(out, "%14d %.12e %.12e\n", iter, numerator_MPI, deltaT_MPI);
numerator_Tot += numerator_MPI;
deltaT_Tot += deltaT_MPI;
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
int coeffsIndexCopy = this->coeffsIndex(walk);
if (coeffsIndexCopy != ind) cout << "ERROR at 2: " << ind << " " << coeffsIndexCopy << endl;
FastHamAndOvlp(walk, ovlp, hamSample, work);
iter++;
}
double final_ham = numerator_Tot/deltaT_Tot;
if (commrank == 0) cout << "ham: " << setprecision(10) << final_ham << endl;
if (commrank == 0) fclose(out);
return final_ham;
}
template<typename Wfn>
template<typename Walker>
void SCPT<Wfn>::doSCEnergyExact(Walker& walk, workingArray& work, double& SCHam, double& SCHamVar, int& samplingIters) {
int firstActive = schd.nciCore;
int firstVirtual = schd.nciCore + schd.nciAct;
Determinant dExternal = walk.d;
// Remove all electrons from the active space
for (int i = firstActive; i<firstVirtual; i++) {
dExternal.setoccA(i, false);
dExternal.setoccB(i, false);
}
int nalpha = Determinant::nalpha - dExternal.Nalpha();
int nbeta = Determinant::nbeta - dExternal.Nbeta();
// Generate all determinants in the appropriate S_l^k
vector<Determinant> allDets;
generateAllDeterminantsActive(allDets, dExternal, schd.nciCore, schd.nciAct, nalpha, nbeta);
double hamTot = 0., normTot = 0.;
double largestOverlap = 0.;
Determinant bestDet;
int nDets = allDets.size();
for (int i = 0; i < allDets.size(); i++) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
double ovlp = 0., ham = 0.;
FastHamAndOvlp(walk, ovlp, ham, work);
hamTot += ovlp * ovlp * ham;
normTot += ovlp * ovlp;
if (abs(ovlp) > largestOverlap) {
largestOverlap = abs(ovlp);
bestDet = allDets[i];
}
}
if (abs(normTot) > 1.e-12) {
SCHam = hamTot / normTot;
} else {
SCHam = 0.;
}
SCHamVar = 0.;
samplingIters = 0;
}
// Generate an initial determinant with external orbitals orb1 and orb2
// set as appropriate, and all orbitals in the active space unoccupied.
template<typename Wfn>
Determinant SCPT<Wfn>::generateInitDet(int orb1, int orb2) {
// The inital determinant at this point, taken from
// Wfn.bestDeterminant, has all core orbitals doubly occupied and
// all virtual orbitals unoccupied.
Determinant initDet = this->wave.bestDeterminant;
int firstActive = schd.nciCore;
int firstVirtual = schd.nciCore + schd.nciAct;
// Unset all active orbitals
for (int i = firstActive; i<firstVirtual; i++) {
initDet.setoccA(i, false);
initDet.setoccB(i, false);
}
// Set the core and virtual orbitals as appropriate
for (int i=0; i<2; i++) {
int orb;
if (i == 0) {
orb = orb1;
} else {
orb = orb2;
}
// orb == -1 indicates that this orbital is not in use (i.e. we
// only have a single excitation).
if (orb == -1) continue;
if (orb < 2*firstActive) {
if (orb % 2 == 0) {
initDet.setoccA(orb/2, false);
} else {
initDet.setoccB(orb/2, false);
}
} else if (orb >= 2*firstVirtual) {
if (orb % 2 == 0) {
initDet.setoccA(orb/2, true);
} else {
initDet.setoccB(orb/2, true);
}
}
}
return initDet;
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::compareStochPerturberEnergy(Walker& walk, int orb1, int orb2, double CASEnergy, int nsamples) {
// First, calculate the *exact* perturber energy
int firstActive = schd.nciCore;
int firstVirtual = schd.nciCore + schd.nciAct;
Determinant dExternal = walk.d;
// Set the core and virtual orbitals as appropriate
for (int i=0; i<2; i++) {
int orb;
if (i == 0) {
orb = orb1;
} else {
orb = orb2;
}
// orb == -1 indicates that this orbital is not in use (i.e. we
// only have a single excitation).
if (orb == -1) continue;
if (orb < 2*firstActive) {
if (orb % 2 == 0) {
dExternal.setoccA(orb/2, false);
} else {
dExternal.setoccB(orb/2, false);
}
} else if (orb >= 2*firstVirtual) {
if (orb % 2 == 0) {
dExternal.setoccA(orb/2, true);
} else {
dExternal.setoccB(orb/2, true);
}
}
}
// Construct a determinant with all active orbitals unoccupied
// (but core and virtual occupations are the same)
for (int i = firstActive; i<firstVirtual; i++) {
dExternal.setoccA(i, false);
dExternal.setoccB(i, false);
}
// Get the number of alpha and beta electrons in the active space
int nalpha = Determinant::nalpha - dExternal.Nalpha();
int nbeta = Determinant::nbeta - dExternal.Nbeta();
// Generate all determinants in the appropriate S_l^k
vector<Determinant> allDets;
generateAllDeterminantsActive(allDets, dExternal, schd.nciCore, schd.nciAct, nalpha, nbeta);
workingArray work;
double hamTot = 0., normTot = 0.;
double largestOverlap = 0.;
Determinant bestDet;
int nDets = allDets.size();
for (int i = 0; i < allDets.size(); i++) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
double ovlp = 0., ham = 0.;
FastHamAndOvlp(walk, ovlp, ham, work);
hamTot += ovlp * ovlp * ham;
normTot += ovlp * ovlp;
if (abs(ovlp) > largestOverlap) {
largestOverlap = abs(ovlp);
bestDet = allDets[i];
}
}
double perturberEnergy = hamTot / normTot;
cout << "Exact perturber energy, E_l^k: " << setprecision(12) << perturberEnergy << endl;
// Now generate stochastic samples
FILE * pt2_out;
string pt2OutName = "stoch_samples_";
pt2OutName.append(to_string(commrank));
pt2OutName.append(".dat");
pt2_out = fopen(pt2OutName.c_str(), "w");
fprintf(pt2_out, "# 1. iter 2. E_l^k 3. E_l^K variance 4. Bias correction "
"5. E_0 - E_l^k 6. 1/(E_0 - E_l^k) 7. niters 8. time\n");
for (int iter=0; iter<nsamples; iter++) {
double SCHam = 0., SCHamVar = 0.;
int samplingIters;
double timeIn = getTime();
this->wave.initWalker(walk, bestDet);
doSCEnergyCTMC(walk, work, SCHam, SCHamVar, samplingIters);
double timeOut = getTime();
double eDiff = CASEnergy - SCHam;
double energySample = 1.0/eDiff;
double biasCorr = - SCHamVar / pow( CASEnergy - SCHam, 3);
// Get the external orbs of the perturber, for printing
string orbString = formatOrbString(orb1, orb2);
fprintf(pt2_out, "%9d %.12e %.12e %.12e %.12e %.12e %8d %.4e\n",
iter, SCHam, SCHamVar, biasCorr, eDiff, energySample, samplingIters, timeOut-timeIn);
fflush(pt2_out);
}
fclose(pt2_out);
}
template<typename Wfn>
template<typename Walker>
double SCPT<Wfn>::doNEVPT2_Deterministic(Walker& walk) {
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminantsFOIS(allDets, norbs, nalpha, nbeta);
workingArray work;
double overlapTot = 0., overlapTotCASCI = 0.;
VectorXd ham = VectorXd::Zero(coeffs.size()), norm = VectorXd::Zero(coeffs.size());
double waveEne = 0.;
//w.printVariables();
VectorXd normSamples = VectorXd::Zero(coeffs.size()), SCNorm = VectorXd::Zero(coeffs.size());
vector<Determinant> initDets;
initDets.resize(numCoeffs, walk.d);
vector<double> largestCoeffs;
largestCoeffs.resize(numCoeffs, 0.0);
for (int i = commrank; i < allDets.size(); i += commsize) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
if (!classesUsed[walk.excitation_class]) continue;
int coeffsIndex = this->coeffsIndex(walk);
if (coeffsIndex == -1) continue;
double ovlp = 0., normSample = 0., hamSample = 0., locEne = 0.;
HamAndOvlp(walk, ovlp, locEne, hamSample, normSample, coeffsIndex, work);
overlapTot += ovlp * ovlp;
ham(coeffsIndex) += (ovlp * ovlp) * hamSample;
norm(coeffsIndex) += (ovlp * ovlp) * normSample;
waveEne += (ovlp * ovlp) * locEne;
if (walk.excitation_class == 0) {
normSamples.setZero();
HamAndSCNorms(walk, ovlp, hamSample, normSamples, initDets, largestCoeffs, work, true);
SCNorm += (ovlp * ovlp) * normSamples;
overlapTotCASCI += ovlp * ovlp;
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(waveEne), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ham.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, norm.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, SCNorm.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(overlapTotCASCI), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
waveEne = waveEne / overlapTot;
ham = ham / overlapTot;
norm = norm / overlapTot;
SCNorm = SCNorm / overlapTotCASCI;
// Print the exact squared norms
//if (commrank == 0) {
// cout << "Exact norms:" << endl;
// int numVirt = norbs - schd.nciCore - schd.nciAct;
// int first_virtual = schd.nciCore + schd.nciAct;
// cout << "Class AAAV: " << endl;
// for (int r=2*first_virtual; r<2*norbs; r++) {
// int ind = cumNumCoeffs[1] + r - 2*first_virtual;
// cout << "r: " << r << " norm: " << setprecision(12) << norm(ind) / norm(0) << endl;
// }
// cout << "Class AAVV: " << endl;
// for (int r=2*first_virtual+1; r<2*norbs; r++) {
// for (int s=2*first_virtual; s<r; s++) {
// int R = r - 2*first_virtual - 1;
// int S = s - 2*first_virtual;
// int ind = cumNumCoeffs[2] + R*(R+1)/2 + S;
// cout << "r: " << r << " s: " << s << " norm: " << setprecision(12) << norm(ind) / norm(0) << endl;
// }
// }
// cout << "Class CAAA: " << endl;
// for (int i=0; i<2*schd.nciCore; i++) {
// int ind = cumNumCoeffs[3] + i;
// cout << "i: " << i << " norm: " << setprecision(12) << norm(ind) / norm(0) << endl;
// }
// cout << "Class CAAV: " << endl;
// for (int i=0; i<2*schd.nciCore; i++) {
// for (int r=2*first_virtual; r<2*norbs; r++) {
// int ind = cumNumCoeffs[4] + 2*numVirt*i + (r - 2*schd.nciCore - 2*schd.nciAct);
// cout << "i: " << i << " r: " << r << " norm: " << setprecision(12) << norm(ind) / norm(0) << endl;
// }
// }
// cout << "Class CCAA: " << endl;
// for (int i=1; i<2*schd.nciCore; i++) {
// for (int j=0; j<i; j++) {
// int ind = cumNumCoeffs[6] + (i-1)*i/2 + j;
// cout << "i: " << i << " j: " << j << " norm: " << setprecision(12) << norm(ind) / norm(0) << endl;
// }
// }
//}
std::vector<int> largeNormIndices;
int counter = 0;
for (int i = 0; i < coeffs.size(); i++) {
if (norm(i) > 1.e-16) {
largeNormIndices.push_back(i);
}
}
Map<VectorXi> largeNormSlice(&largeNormIndices[0], largeNormIndices.size());
VectorXd largeNorms;
igl::slice(norm, largeNormSlice, largeNorms);
VectorXd largeHam;
igl::slice(ham, largeNormSlice, largeHam);
VectorXd ene = (largeHam.array() / largeNorms.array()).matrix();
double ene2 = 0.;
for (int i = 1; i < largeNorms.size(); i++) {
ene2 += largeNorms(i) / largeNorms(0) / (ene(0) - ene(i));
}
if (commrank == 0) {
cout << "ref energy " << setprecision(12) << ene(0) << endl;
cout << "waveEne " << waveEne << endl;
cout << "nevpt2 energy " << ene(0) + ene2 << endl;
}
}
template<typename Wfn>
double SCPT<Wfn>::get_ccvv_energy() {
double energy_ccvv = 0.0;
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
for (int j=1; j<2*schd.nciCore; j++) {
for (int i=0; i<j; i++) {
for (int s=2*first_virtual+1; s<2*norbs; s++) {
for (int r=2*first_virtual; r<s; r++) {
energy_ccvv -= pow( I2(r, j, s, i) - I2(r, i, s, j), 2) / ( moEne(r/2) + moEne(s/2) - moEne(i/2) - moEne(j/2) );
}
}
}
}
return energy_ccvv;
}
template<typename Wfn>
void SCPT<Wfn>::readSpinRDM(Eigen::MatrixXd& oneRDM, Eigen::MatrixXd& twoRDM) {
// Read a 2-RDM from the spin-RDM text file output by Dice
// Also construct the 1-RDM at the same time
int nSpinOrbsAct = 2*schd.nciAct;
int nPairs = nSpinOrbsAct * nSpinOrbsAct;
oneRDM = MatrixXd::Zero(nSpinOrbsAct, nSpinOrbsAct);
twoRDM = MatrixXd::Zero(nPairs, nPairs);
ifstream RDMFile("spinRDM.0.0.txt");
string lineStr;
while (getline(RDMFile, lineStr)) {
string buf;
stringstream ss(lineStr);
vector<string> words;
while (ss >> buf) words.push_back(buf);
int a = stoi(words[0]);
int b = stoi(words[1]);
int c = stoi(words[2]);
int d = stoi(words[3]);
double elem = stod(words[4]);
int ind1 = a * nSpinOrbsAct + b;
int ind2 = c * nSpinOrbsAct + d;
int ind3 = b * nSpinOrbsAct + a;
int ind4 = d * nSpinOrbsAct + c;
twoRDM(ind1, ind2) = elem;
twoRDM(ind3, ind2) = -elem;
twoRDM(ind1, ind4) = -elem;
twoRDM(ind3, ind4) = elem;
if (b == d) oneRDM(a,c) += elem;
if (b == c) oneRDM(a,d) += -elem;
if (a == d) oneRDM(b,c) += -elem;
if (a == c) oneRDM(b,d) += elem;
}
int nelec_act = Determinant::nalpha + Determinant::nbeta - 2*schd.nciCore;
// Normalize the 1-RDM
for (int a = 0; a < nSpinOrbsAct; a++) {
for (int b = 0; b < nSpinOrbsAct; b++) {
oneRDM(a,b) /= nelec_act-1;
}
}
}
template<typename Wfn>
void SCPT<Wfn>::calc_AAVV_NormsFromRDMs(Eigen::MatrixXd& twoRDM, Eigen::VectorXd& norms) {
if (commrank == 0) cout << "Calculating AAVV norms..." << endl;
double timeIn = getTime();
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
int nSpinOrbs = 2*norbs;
int nSpinOrbsCore = 2*schd.nciCore;
int nSpinOrbsAct = 2*schd.nciAct;
VectorXd normsLocal = 0. * norms;
size_t numTerms = (nSpinOrbs - 2*first_virtual) * (nSpinOrbs - 2*first_virtual + 1) / 2;
for (int r = 2*first_virtual+1; r < nSpinOrbs; r++) {
for (int s = 2*first_virtual; s < r; s++) {
int R = r - 2*first_virtual - 1;
int S = s - 2*first_virtual;
if ((R*(R+1)/2+S) % commsize != commrank) continue;
double norm_rs = 0.0;
for (int a = nSpinOrbsCore+1; a < 2*first_virtual; a++) {
for (int b = nSpinOrbsCore; b < a; b++) {
double int_ab = I2(r,a,s,b) - I2(r,b,s,a);
for (int c = nSpinOrbsCore+1; c < 2*first_virtual; c++) {
for (int d = nSpinOrbsCore; d < c; d++) {
int ind1 = (a - nSpinOrbsCore) * nSpinOrbsAct + (b - nSpinOrbsCore);
int ind2 = (c - nSpinOrbsCore) * nSpinOrbsAct + (d - nSpinOrbsCore);
norm_rs += int_ab * twoRDM(ind1,ind2) * (I2(r,c,s,d) - I2(r,d,s,c));
}
}
}
}
size_t ind = cumNumCoeffs[2] + R*(R+1)/2 + S;
//double norm_old = norms(ind);
normsLocal(ind) = norm_rs;
//cout << r << " " << s << " " << setprecision(12) << norm_old << " " << norm_rs << endl;
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, normsLocal.data(), normsLocal.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
for (int r = 2*first_virtual+1; r < nSpinOrbs; r++) {
for (int s = 2*first_virtual; s < r; s++) {
int R = r - 2*first_virtual - 1;
int S = s - 2*first_virtual;
size_t ind = cumNumCoeffs[2] + R*(R+1)/2 + S;
norms(ind) = normsLocal(ind);
}
}
double timeOut = getTime();
if (commrank == 0) cout << "AAVV norms calculated. Time taken: " << timeOut - timeIn << endl;
}
template<typename Wfn>
void SCPT<Wfn>::calc_CAAV_NormsFromRDMs(Eigen::MatrixXd& oneRDM, Eigen::MatrixXd& twoRDM, Eigen::VectorXd& norms) {
double timeIn = getTime();
if (commrank == 0) cout << "Calculating CAAV norms..." << endl;
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
int nSpinOrbs = 2*norbs;
int nSpinOrbsCore = 2*schd.nciCore;
int nSpinVirtOrbs = 2*(norbs - schd.nciCore - schd.nciAct);
int nSpinOrbsAct = 2*schd.nciAct;
VectorXd normsLocal = 0. * norms;
for (int i = commrank; i < nSpinOrbsCore; i+=commsize) {
for (int r = 2*first_virtual; r < nSpinOrbs; r++) {
double core_contrib = 0.0;
for (int j = 0; j < nSpinOrbsCore; j++) {
core_contrib += I2(i,r,j,j) - I2(i,j,j,r);
}
double norm_ir = (I1(i,r) + core_contrib) * (I1(i,r) + core_contrib);
for (int a = nSpinOrbsCore; a < 2*first_virtual; a++) {
for (int b = nSpinOrbsCore; b < 2*first_virtual; b++) {
double int_ab = I2(i,r,b,a) - I2(i,a,b,r);
norm_ir += 2*int_ab * oneRDM(b-nSpinOrbsCore, a-nSpinOrbsCore) * core_contrib;
norm_ir += 2*int_ab * oneRDM(b-nSpinOrbsCore, a-nSpinOrbsCore) * I1(r,i);
for (int c = nSpinOrbsCore; c < 2*first_virtual; c++) {
norm_ir += int_ab * oneRDM(b-nSpinOrbsCore, c-nSpinOrbsCore) * (I2(r,i,a,c) - I2(r,c,a,i));
for (int d = nSpinOrbsCore; d < 2*first_virtual; d++) {
int ind1 = (b - nSpinOrbsCore) * nSpinOrbsAct + (c - nSpinOrbsCore);
int ind2 = (a - nSpinOrbsCore) * nSpinOrbsAct + (d - nSpinOrbsCore);
norm_ir += int_ab * twoRDM(ind1,ind2) * (I2(r,i,c,d) - I2(r,d,c,i));
}
}
}
}
size_t ind = cumNumCoeffs[4] + nSpinVirtOrbs*i + (r - nSpinOrbsCore - nSpinOrbsAct);
//double norm_old = norms(ind);
normsLocal(ind) = norm_ir;
//cout << i << " " << r << " " << setprecision(12) << norm_old << " " << norm_ir << endl;
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, normsLocal.data(), normsLocal.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
for (int i = 0; i < nSpinOrbsCore; i++) {
for (int r = 2*first_virtual; r < nSpinOrbs; r++) {
size_t ind = cumNumCoeffs[4] + nSpinVirtOrbs*i + (r - nSpinOrbsCore - nSpinOrbsAct);
norms(ind) = normsLocal(ind);
}
}
double timeOut = getTime();
if (commrank == 0) cout << "CAAV norms calculated. Time taken: " << timeOut - timeIn << endl;
}
template<typename Wfn>
void SCPT<Wfn>::calc_CCAA_NormsFromRDMs(Eigen::MatrixXd& oneRDM, Eigen::MatrixXd& twoRDM, Eigen::VectorXd& norms) {
double timeIn = getTime();
if (commrank == 0) cout << "Calculating CCAA norms..." << endl;
int norbs = Determinant::norbs;
int first_virtual = schd.nciCore + schd.nciAct;
int nSpinOrbs = 2*norbs;
int nSpinOrbsCore = 2*schd.nciCore;
int nSpinOrbsAct = 2*schd.nciAct;
int nPairs = nSpinOrbsAct * nSpinOrbsAct;
// Construct auxiliary 2-RDM for CCAA class
double *twoRDMAux = new double[(int)pow(nSpinOrbsAct, 4)];
for (int a = 0; a < nSpinOrbsAct; a++) {
for (int b = 0; b < nSpinOrbsAct; b++) {
for (int c = 0; c < nSpinOrbsAct; c++) {
for (int d = 0; d < nSpinOrbsAct; d++) {
int ind1 = c * nSpinOrbsAct + d;
int ind2 = a * nSpinOrbsAct + b;
int ind3 = ((a*nSpinOrbsAct + b)*nSpinOrbsAct + c)*nSpinOrbsAct + d;
twoRDMAux[ind3] = twoRDM(ind1, ind2);
if (b == c) twoRDMAux[ind3] += oneRDM(d,a);
if (a == d) twoRDMAux[ind3] += oneRDM(c,b);
if (a == c) twoRDMAux[ind3] += -oneRDM(d,b);
if (b == d) twoRDMAux[ind3] += -oneRDM(c,a);
if (b == d && a == c) twoRDMAux[ind3] += 1;
if (b == c && a == d) twoRDMAux[ind3] += -1;
}
}
}
}
for (int i = 1; i < nSpinOrbsCore; i++) {
for (int j = 0; j < i; j++) {
double norm_ij = 0.0;
for (int a = nSpinOrbsCore+1; a < 2*first_virtual; a++) {
int a_shift = a - nSpinOrbsCore;
for (int b = nSpinOrbsCore; b < a; b++) {
double int_ij = I2(j,a,i,b) - I2(j,b,i,a);
int b_shift = b - nSpinOrbsCore;
for (int c = nSpinOrbsCore+1; c < 2*first_virtual; c++) {
int c_shift = c - nSpinOrbsCore;
for (int d = nSpinOrbsCore; d < c; d++) {
int d_shift = d - nSpinOrbsCore;
int ind = ((a_shift*nSpinOrbsAct + b_shift)*nSpinOrbsAct + c_shift)*nSpinOrbsAct + d_shift;
norm_ij += int_ij * twoRDMAux[ind] * (I2(c,j,d,i) - I2(c,i,d,j));
}
}
}
}
int norm_ind = cumNumCoeffs[6] + (i-1)*i/2 + j;
norms(norm_ind) = norm_ij;
//cout << i << " " << j << " " << setprecision(12) << norm_old << " " << norm_ij << endl;
}
}
delete []twoRDMAux;
double timeOut = getTime();
if (commrank == 0) cout << "CCAA norms calculated. Time taken: " << timeOut - timeIn << endl;
}
template<typename Wfn>
string SCPT<Wfn>::getfileName() const {
return "scpt"+wave.getfileName();
}
template<typename Wfn>
void SCPT<Wfn>::writeWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
template<typename Wfn>
void SCPT<Wfn>::readWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
#endif
}
// This is a wrapper function which is called during initialization.
// This is where the main NEVPT2 functions are called from.
void initNEVPT_Wrapper()
{
schd.usingFOIS = true;
SCPT<SelectedCI> wave;
SimpleWalker walk;
wave.initWalker(walk);
if (schd.deterministic) {
wave.doNEVPT2_Deterministic(walk);
}
else if (schd.exactPerturber) {
wave.compareStochPerturberEnergy(walk, schd.perturberOrb1, schd.perturberOrb2,
schd.CASEnergy, schd.numSCSamples);
}
else {
bool new_NEVPT = schd.efficientNEVPT || schd.efficientNEVPT_2 || schd.exactE_NEVPT ||
schd.NEVPT_readE || schd.NEVPT_writeE;
if (new_NEVPT) {
wave.doNEVPT2_CT_Efficient(walk);
} else {
wave.doNEVPT2_CT(walk);
wave.doNEVPT2_CT(walk);
}
}
}
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MRCIWalker_HEADER_H
#define MRCIWalker_HEADER_H
#include "Determinants.h"
#include "Walker.h"
#include "integral.h"
#include <boost/serialization/serialization.hpp>
#include <Eigen/Dense>
#include "input.h"
#include <unordered_set>
#include <iterator>
using namespace Eigen;
/**
* Is essentially a single determinant used in the VMC/DMC simulation
* At each step in VMC one need to be able to calculate the following
* quantities
* a. The local energy = <walker|H|Psi>/<walker|Psi>
*
*/
template<typename Corr, typename Reference>
struct MRCIWalker
{
Determinant d; //The current determinant n
Walker<Corr, Reference> activeWalker; //n_0
unordered_set<int> excitedSpinOrbs; //redundant but useful
std::array<unordered_set<int>, 2> excitedOrbs; //spatial orbital indices of excited electrons (in virtual orbitals) in d
std::array<unordered_set<int>, 2> excitedHoles; //spatial orbital indices of excited holes w.r.t. activeWalker (in active orbitals) in d
std::array<VectorXd, 2> energyIntermediates; //would only be useful in lanczos
//double parity; //parity between n_0 and n
//constructors
//default
MRCIWalker() {}
//this is used in determinisitc calculations
MRCIWalker(Corr &corr, const Reference &ref, Determinant &pd): d(pd)
{
int norbs = Determinant::norbs;
Determinant activeDet = d;
excitedOrbs[0].clear();
excitedOrbs[1].clear();
excitedSpinOrbs.clear();
for (int i = schd.nciAct; i < Determinant::norbs; i++) {
if (d.getoccA(i)) {
excitedOrbs[0].insert(i);
excitedSpinOrbs.insert(2*i);
activeDet.setoccA(i, 0);
}
if (d.getoccB(i)) {
excitedOrbs[1].insert(i);
excitedSpinOrbs.insert(2*i + 1);
activeDet.setoccB(i, 0);
}
}
vector<int> open;
vector<int> closed;
d.getOpenClosed(0, open, closed);
excitedHoles[0].clear();
excitedHoles[1].clear();
for (int i = 0; i < excitedOrbs[0].size(); i++) {
excitedHoles[0].insert(open[i]);
activeDet.setoccA(open[i], 1);
}
open.clear(); closed.clear();
d.getOpenClosed(1, open, closed);
for (int i = 0; i < excitedOrbs[1].size(); i++) {
excitedHoles[1].insert(open[i]);
activeDet.setoccB(open[i], 1);
}
activeWalker = Walker<Corr, Reference>(corr, ref, activeDet);
//parity = 1.;
//for (int sz = 0; sz < 2; sz++) {//iterate over spins
// auto itFrom = excitedHoles[sz].begin();
// auto itTo = excitedOrbs[sz].begin();
// for (int n = 0; n < excitedHoles[sz].size(); n++) {//iterate over excitations
// int i = *itFrom, a = *itTo;
// parity *= activeDet.parity(a, i, sz);
// activeDet.setocc(i, sz, false);
// activeDet.setocc(a, sz, true);
// itFrom = std::next(itFrom); itTo = std::next(itTo);
// }
//}
//open.clear(); closed.clear()
//d.getOpenClosed(open, closed);
//energyIntermediates[0]= VectorXd::Zero(norbs);
//energyIntermediates[1]= VectorXd::Zero(norbs);
//for (int i = 0; i < norbs; i++) {
// for (int j = 0; j < closed.size(); j++) {
// energyIntermediates[0][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// energyIntermediates[1][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// energyIntermediates[closed[j] % 2][i] -= I2.Exchange(i, closed[j]/2);
// }
//}
}
//this is used in stochastic calculations
//it reads the best determinant (which should be in the CAS, so no excitedOrbs or holes) from a file
MRCIWalker(Corr &corr, const Reference &ref)
{
if (commrank == 0) {
//char file[5000];
//sprintf(file, "BestDeterminant.txt");
//std::ifstream ifs(file, std::ios::binary);
//boost::archive::binary_iarchive load(ifs);
//load >> d;
std::vector<Determinant> dets;
std::vector<double> ci;
readDeterminants(schd.determinantFile, dets, ci);
d = dets[0];
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
int norbs = Determinant::norbs;
activeWalker = Walker<Corr, Reference>(corr, ref, d);
excitedOrbs[0].clear();
excitedOrbs[1].clear();
excitedHoles[0].clear();
excitedHoles[1].clear();
excitedSpinOrbs.clear();
//parity = 1.;
//vector<int> open;
//vector<int> closed;
//d.getOpenClosed(open, closed);
//energyIntermediates[0]= VectorXd::Zero(norbs);
//energyIntermediates[1]= VectorXd::Zero(norbs);
//for (int i = 0; i < norbs; i++) {
// for (int j = 0; j < closed.size(); j++) {
// energyIntermediates[0][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// energyIntermediates[1][i] += I2.Direct(i, closed[j]/2) + I1(2*i, 2*i);
// energyIntermediates[closed[j] % 2][i] -= I2.Exchange(i, closed[j]/2);
// }
//}
}
//MRCIWalker(const MRCIWalker &w): d(w.d), excitedOrbs(w.excitedOrbs), excitedHoles(w.excitedHoles) {}
Determinant getDet() { return d; }
void update(int i, int a, bool sz, const Reference &ref, const Corr &corr) { return; }//to be defined for metropolis
void updateEnergyIntermediate(const oneInt& I1, const twoInt& I2, int I, int A)
{
int norbs = Determinant::norbs;
for (int n = 0; n < norbs; n++) {
energyIntermediates[0][n] += (I2.Direct(n, A/2) - I2.Direct(n, I/2));
energyIntermediates[1][n] += (I2.Direct(n, A/2) - I2.Direct(n, I/2));
energyIntermediates[I%2][n] -= (I2.Exchange(n, A/2) - I2.Exchange(n, I/2));
}
}
void updateEnergyIntermediate(const oneInt& I1, const twoInt& I2, int I, int A, int J, int B)
{
int norbs = Determinant::norbs;
for (int n = 0; n < norbs; n++) {
energyIntermediates[0][n] += (I2.Direct(n, A/2) - I2.Direct(n, I/2) + I2.Direct(n, B/2) - I2.Direct(n, J/2));
energyIntermediates[1][n] += (I2.Direct(n, A/2) - I2.Direct(n, I/2) + I2.Direct(n, B/2) - I2.Direct(n, J/2));
energyIntermediates[I%2][n] -= (I2.Exchange(n, A/2) - I2.Exchange(n, I/2));
energyIntermediates[J%2][n] -= (I2.Exchange(n, B/2) - I2.Exchange(n, J/2));
}
}
//i and a are spatial orbital indices
void updateDet(bool sz, int i, int a)
{
d.setocc(i, sz, false);
d.setocc(a, sz, true);
}
//this is used for n -> n' MC updates
//assumes valid excitations
//the energyIntermediates should only be updated for outer walker updates
void updateWalker(const Reference &ref, Corr &corr, int ex1, int ex2, bool updateIntermediates = true)
{
int norbs = Determinant::norbs;
//spatial orb excitations for n -> n'
std::array<std::vector<int>, 2> from, to;
from[0].clear(); from[1].clear(); to[0].clear(); to[1].clear();
int I = ex1 / (2 * norbs), A = ex1 % (2 * norbs);
from[I%2].push_back(I/2);
to[I%2].push_back(A/2);
//if (ex2 == 0) updateEnergyIntermediate(I1, I2, I, A);
//else {
if (ex2 != 0) {
int J = ex2 / (2 * norbs), B = ex2 % (2 * norbs);
from[J%2].push_back(J/2);
to[J%2].push_back(B/2);
//updateEnergyIntermediate(I1, I2, I, A, J, B);
}
//spatial orb excitations for n0 -> n0'
//std::array<std::vector<int>, 2> fromAct, toAct;
//fromAct[0].clear(); fromAct[1].clear(); toAct[0].clear(); toAct[1].clear();
std::vector<int> excAct;
excAct.clear();
for (int sz = 0; sz < 2; sz++) {// sz = 0, 1
for (int n = 0; n < from[sz].size(); n++) {//loop over excitations
int i = from[sz][n], a = to[sz][n];
updateDet(sz, i, a);
auto itOrbsi = excitedOrbs[sz].find(i);
auto itHolesa = excitedHoles[sz].find(a);
if (i < schd.nciAct) {//act ->
if (a >= schd.nciAct) {//act -> virt, n0' = n0
excitedOrbs[sz].insert(a);
excitedHoles[sz].insert(i);
excitedSpinOrbs.insert(2*a + sz);
}
else {//internal excitation, act -> act
if (itHolesa == excitedHoles[sz].end()) {//no changes to excitedOrbs or holes
//fromAct[sz].push_back(i);
//toAct[sz].push_back(a);
int exc = (2 * norbs) * (2 * i + sz) + (2 * a + sz);
excAct.push_back(exc);
}
else {//a is an excitedHole, n0' = n0
excitedHoles[sz].erase(itHolesa);
excitedHoles[sz].insert(i);
}
}
}
else {//virt ->
if (a >= schd.nciAct) {//virt -> virt, n0' = n0
excitedOrbs[sz].erase(itOrbsi);
excitedOrbs[sz].insert(a);
excitedSpinOrbs.erase(2*i + sz);
excitedSpinOrbs.insert(2*a + sz);
}
else {//external excitation, virt -> act
excitedOrbs[sz].erase(itOrbsi);
excitedSpinOrbs.erase(2*i + sz);
if (itHolesa == excitedHoles[sz].end()) {//one hole needs to be removed
int hole = *excitedHoles[sz].begin();
excitedHoles[sz].erase(excitedHoles[sz].begin());
//fromAct[sz].push_back(hole);
//toAct[sz].push_back(a);
int exc = (2 * norbs) * (2 * hole + sz) + (2 * a + sz);
excAct.push_back(exc);
}
else {//a is an excited hole, n0' = n0
excitedHoles[sz].erase(itHolesa);
}
}
}
}
}
if (excAct.size() == 1) activeWalker.updateWalker(ref, corr, excAct[0], 0);
else if (excAct.size() == 2) activeWalker.updateWalker(ref, corr, excAct[0], excAct[1]);
}
void exciteWalker(const Reference &ref, const Corr &corr, int excite1, int excite2, int norbs) { return; };//not used
bool operator<(const MRCIWalker &w) const
{
return d < w.d;
}
bool operator==(const MRCIWalker &w) const
{
return d == w.d;
}
friend ostream& operator<<(ostream& os, const MRCIWalker& w) {
os << w.d << endl;
//os << "excited Orbs " << w.excitedSpinOrbs << endl;
os << "excitedSpinOrbs ";
copy(w.excitedSpinOrbs.begin(), w.excitedSpinOrbs.end(), ostream_iterator<int>(os, " "));
os << endl << "excitedOrbs u ";
copy(w.excitedOrbs[0].begin(), w.excitedOrbs[0].end(), ostream_iterator<int>(os, " "));
os << endl << "excitedOrbs d ";
copy(w.excitedOrbs[1].begin(), w.excitedOrbs[1].end(), ostream_iterator<int>(os, " "));
os << endl << "excitedHoles u ";
copy(w.excitedHoles[0].begin(), w.excitedHoles[0].end(), ostream_iterator<int>(os, " "));
os << endl << "excitedHoles d ";
copy(w.excitedHoles[1].begin(), w.excitedHoles[1].end(), ostream_iterator<int>(os, " "));
os << endl << "activeWalker\n" << w.activeWalker << endl;
return os;
}
//template <typename Wfn>
//void exciteTo(Wfn& w, Determinant& dcopy) {
// d = dcopy;
//}
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Pfaffian_HEADER_H
#define Pfaffian_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
class Determinant;
class workingArray;
using namespace Eigen;
/**
* This is the wavefunction, it is a linear combination of
* slater determinants made of Hforbs
*/
class Pfaffian {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & pairMat;
}
public:
MatrixXcd pairMat; //pairing matrix, F_pq
/**
* constructor
*/
Pfaffian();
//variables are ordered as:
//cicoeffs of the reference multidet expansion, followed by hforbs (row major)
//in case of uhf all alpha first followed by beta
void getVariables(Eigen::VectorBlock<VectorXd> &v) const;
long getNumVariables() const;
void updateVariables(const Eigen::VectorBlock<VectorXd> &v);
void printVariables() const;
const MatrixXcd& getPairMat() const { return pairMat;}
string getfileName() const {return "Pfaffian";};
};
#endif
<file_sep>/* Copyright (c) 2012 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bfint (LICENSE). If not, see http://www.gnu.org/licenses/
*/
#include <stdexcept>
#include <sstream>
#include <new>
#include <algorithm> // for std::min
#include "CxMemoryStack.h"
//#include "CxDefs.h"
//#include "CxOpenMpProxy.h"
// extra function to allow overwriting from the outside, and to allow automatic GDB breakpoints.
void CxCrashAfterMemoryError(char const *pMsg)
{
// DEBUG_BREAK;
throw std::runtime_error(pMsg);
}
namespace ct {
// note: boundary must be size-of-2
inline char *AlignCharPtr(char *p, size_t Boundary) {
// size_t
// iPos = reinterpret_cast<size_t>(p),
// iNew = ((iPos - 1) | (Boundary - 1)) + 1;
// return reinterpret_cast<char*>(iNew);
return reinterpret_cast<char*>(AlignSizeT(reinterpret_cast<size_t>(p), Boundary));
}
inline void FMemoryStack2::PushTopMark() {
#ifdef _DEBUG
//assert(m_Pos < m_Size - 8);
*reinterpret_cast<size_t*>(&m_pDataAligned[m_Pos]) = 0xbadc0de;
m_Pos += sizeof(size_t);
#endif
}
inline void FMemoryStack2::PopTopMark() {
#ifdef _DEBUG
m_Pos -= sizeof(size_t);
//assert(m_Pos < m_Size - 8);
if ( *reinterpret_cast<size_t*>(&m_pDataAligned[m_Pos]) != 0xbadc0de ) {
printf("\n\n\n===================\nstack inconsistent!\n===================\n");
CxCrashAfterMemoryError("stack error");
}
#endif
}
void* FMemoryStack2::Alloc(size_t nSizeInBytes)
{
PopTopMark();
size_t OldPos = m_Pos;
m_Pos += AlignSizeT(nSizeInBytes, CX_DEFAULT_MEM_ALIGN);
PushTopMark();
if ( m_Pos >= m_Size )
CxCrashAfterMemoryError("FMemoryStack2: Stack size exceeded.");
return &m_pDataAligned[OldPos];
}
void FMemoryStack2::Free(void *p)
{
PopTopMark();
ptrdiff_t
n = &m_pDataAligned[m_Pos] - (char*)p;
if ( n < 0 )
CxCrashAfterMemoryError("FMemoryStack2: Release address too low!");
m_Pos -= n;
// note: new start of heap should be aligned automagically, since p is required to come out of a aligned Alloc() call.
PushTopMark();
}
size_t FMemoryStack2::MemoryLeft() {
return m_Size - m_Pos;
}
FMemoryStack2::FMemoryStack2(char *pBase, size_t nActualSize, size_t nNeededSize)
: m_pDataStart(0), m_pDataAligned(0)
{
if (pBase && nActualSize >= nNeededSize)
AssignMemory(pBase, nActualSize);
else
Create((nNeededSize != 0)? nNeededSize : nActualSize);
}
void FMemoryStack2::Create(size_t nSize)
{
//assert_rt(m_pDataStart == 0);
m_Size = nSize;
m_Pos = 0;
m_pDataStart = 0;
m_bOwnMemory = false;
if ( nSize != 0 ) {
m_pDataStart = new(std::nothrow) char[nSize];
m_bOwnMemory = true;
if ( m_pDataStart == 0 ) {
std::stringstream str; str.precision(2); str.setf(std::ios::fixed);
str << "FMemoryStack2: Sorry, failed to allocate " << (static_cast<double>(nSize)/static_cast<double>(1ul<<20)) << " MB of memory.";
CxCrashAfterMemoryError(str.str().c_str());
}
if (nSize < 2*CX_DEFAULT_MEM_ALIGN)
CxCrashAfterMemoryError("FMemoryStack2: assigned workspace is too small.");
m_pDataAligned = AlignCharPtr(m_pDataStart, CX_DEFAULT_MEM_ALIGN);
m_Size -= m_pDataAligned - m_pDataStart;
PushTopMark();
}
}
void FMemoryStack2::AssignMemory(char *pBase_, size_t nSize)
{
//assert(m_pDataStart == 0 && pBase_ != 0);
Create(0);
m_bOwnMemory = false;
m_pDataStart = pBase_;
m_Size = nSize;
m_Pos = 0;
if (nSize < 2*CX_DEFAULT_MEM_ALIGN)
CxCrashAfterMemoryError("FMemoryStack2: assigned workspace is too small.");
m_pDataAligned = AlignCharPtr(m_pDataStart, CX_DEFAULT_MEM_ALIGN);
m_Size -= m_pDataAligned - m_pDataStart;
PushTopMark();
}
void FMemoryStack2::Destroy()
{
#ifdef _DEBUG
if ( m_Size != 0 )
PopTopMark();
else
//assert(m_pDataStart == 0);
//assert(m_Pos == 0);
#endif // _DEBUG
if ( m_bOwnMemory )
delete []m_pDataStart;
m_pDataStart = 0;
m_pDataAligned = 0;
}
FMemoryStack::~FMemoryStack()
{
}
FMemoryStack2::~FMemoryStack2()
{
if ( m_bOwnMemory )
delete []m_pDataStart;
m_pDataStart = (char*)0xbadc0de;
m_pDataAligned = (char*)0xbadc0de;
}
void FMemoryStack2::Align(uint Boundary)
{
//assert(m_pDataAligned == AlignCharPtr(m_pDataAligned, CX_DEFAULT_MEM_ALIGN));
PopTopMark();
if (Boundary <= CX_DEFAULT_MEM_ALIGN) {
m_Pos = AlignSizeT(m_Pos, Boundary);
} else {
m_Pos = AlignCharPtr(&m_pDataAligned[m_Pos], Boundary) - m_pDataAligned;
}
PushTopMark();
}
void FMemoryStack::Align(uint Boundary)
{
size_t
iPos = reinterpret_cast<size_t>(Alloc(0)),
iNew = ((iPos - 1) | (Boundary - 1)) + 1;
Alloc(iNew - iPos);
}
#ifdef MOLPRO
void* FMemoryStackMolproCore::Alloc( size_t nSizeInBytes )
{
// return itf::MolproAlloc(nSizeInBytes);
void *p = itf::MolproAlloc(nSizeInBytes);
m_pPeak = std::max(m_pPeak, static_cast<char*>(p) + nSizeInBytes);
return p;
}
void FMemoryStackMolproCore::Free(void *p)
{
return itf::MolproFree(p);
}
size_t FMemoryStackMolproCore::MemoryLeft()
{
return itf::MolproGetFreeMemory();
}
FMemoryStackMolproCore::FMemoryStackMolproCore()
: m_pPeak(0)
{
m_pInitialTop = GetTop();
m_pPeak = m_pInitialTop;
}
FMemoryStackMolproCore::~FMemoryStackMolproCore()
{
}
#endif // MOLPRO
FMemoryStackArray::FMemoryStackArray( FMemoryStack &BaseStack )
: pBaseStack(&BaseStack)
{
nThreads = omp_get_max_threads();
pSubStacks = new FMemoryStack2[nThreads];
size_t
nSize = static_cast<size_t>(0.98 * static_cast<double>(pBaseStack->MemoryLeft() / nThreads));
pBaseStack->Alloc(pStackBase, nThreads * nSize);
for (size_t i = 0; i < nThreads; ++ i)
pSubStacks[i].AssignMemory(pStackBase + i * nSize, nSize);
}
void FMemoryStackArray::Release()
{
//assert(pBaseStack != 0);
delete []pSubStacks;
pBaseStack->Free(pStackBase);
pStackBase = 0;
pBaseStack = 0;
}
FMemoryStackArray::~FMemoryStackArray()
{
if (pBaseStack)
Release();
}
FMemoryStack2 &FMemoryStackArray::GetStackOfThread()
{
int iThread = omp_get_thread_num();
//assert(iThread < (int)nThreads);
return pSubStacks[iThread];
}
double *FOmpAccBlock::pTls() {
return &m_pTlsData[omp_get_thread_num() * m_nAlignedSize];
}
void FOmpAccBlock::Init(double *pTarget, size_t nSize, unsigned Flags, FMemoryStack &Mem)
{
//assert(m_nSize == 0);
if (pTarget == 0)
nSize = 0;
m_nSize = nSize;
m_nAlignedSize = AlignSizeT(nSize, CX_DEFAULT_MEM_ALIGN/sizeof(*m_pTarget));
m_Flags = Flags;
if (m_nSize != 0)
m_pTarget = pTarget;
else {
m_pTarget = 0;
m_nAlignedSize = 0;
m_pTlsData = 0;
}
if (!m_pTarget)
return;
m_nThreads = omp_get_max_threads();
Mem.Alloc(m_pTlsData, nTotalSize());
// clear thread-local data. Or should I align it with the thread ids? may be better for cache purposes.
#pragma omp parallel for
for (int iBlock = 0; iBlock < int(nScalarBlocks(nTotalSize())); ++ iBlock) {
double
*pBlock = &m_pTlsData[nScalarBlockSize() * size_t(iBlock)],
*pBlockEnd = std::min(pBlock + nScalarBlockSize(), m_pTlsData + nTotalSize());
memset(pBlock, 0, (pBlockEnd-pBlock)*sizeof(*pBlock));
}
}
static void Add2( double *r, double const *x, double f, std::size_t n )
{
std::size_t
i = 0;
// for ( ; i < (n & (~3)); i += 4 ) {
// r[i] += f * x[i];
// r[i+1] += f * x[i+1];
// r[i+2] += f * x[i+2];
// r[i+3] += f * x[i+3];
// }
for ( ; i < n; ++ i ) {
r[i] += f * x[i];
}
}
void FOmpAccBlock::Join()
{
if (!m_pTarget) return;
// horizontal sum. in this loop, each block is summed up across the previous processor dimension.
#pragma omp parallel for
for (int iBlock = 0; iBlock < int(nScalarBlocks(m_nSize)); ++ iBlock) {
size_t
iBlockOffs = nScalarBlockSize() * size_t(iBlock);
double
*pBlock = &m_pTlsData[iBlockOffs],
*pBlockEnd = std::min(pBlock + nScalarBlockSize(), m_pTlsData + m_nSize);
if (m_Flags & OMPACC_ClearTarget)
memset(&m_pTarget[iBlockOffs], 0, sizeof(*pBlock)*(pBlockEnd-pBlock));
for (size_t iAcc = 0; iAcc < m_nThreads; ++ iAcc)
Add2(&m_pTarget[iBlockOffs], &pBlock[iAcc * m_nAlignedSize], 1.0, pBlockEnd-pBlock);
}
}
} // namespace ct
// kate: indent-width 4
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SMW_HEADER_H
#define SMW_HEADER_H
#include <Eigen/Dense>
#include "igl/slice.h"
#include "igl/slice_into.h"
/**
* This takes an inverse and determinant of a matrix formed by a subset of
* columns and rows of Hforbs
* and generates the new inverse and determinant
* by replacing cols with incides des with those with indices cre
* RowVec is the set of row indices that are common to both in the
* incoming and outgoing matrices. ColIn are the column indices
* of the incoming matrix.
*/
void calculateInverseDeterminantWithColumnChange(const Eigen::MatrixXcd &inverseIn, const std::complex<double> &detValueIn, const Eigen::MatrixXcd &tableIn,
Eigen::MatrixXcd &inverseOut, std::complex<double> &detValueOut, Eigen::MatrixXcd &tableOut,
std::vector<int>& cre, std::vector<int>& des,
const Eigen::Map<Eigen::VectorXi> &RowVec,
std::vector<int> &ColIn, const Eigen::MatrixXcd &Hforbs);
/**
* This takes an inverse and determinant of a matrix formed by a subset of
* columns and rows of Hforbs
* and generates the new inverse and determinant
* by replacing rows with incides des with those with indices des
* ColVec is the set of col indices that are common to both in the
* incoming and outgoing matrices. RowIn are the column indices
* of the incoming matrix.
*/
void calculateInverseDeterminantWithRowChange(const Eigen::MatrixXcd &inverseIn, const std::complex<double> &detValueIn, const Eigen::MatrixXcd &tableIn,
Eigen::MatrixXcd &inverseOut, std::complex<double> &detValueOut, Eigen::MatrixXcd &tableOut,
std::vector<int>& cre, std::vector<int>& des,
const Eigen::Map<Eigen::VectorXi> &ColVec,
std::vector<int> &RowIn, const Eigen::MatrixXcd &Hforbs, const bool updateTable);
// determinant function specialized for small matrices
inline std::complex<double> calcDet(const Eigen::MatrixXcd &detSlice) {
if (detSlice.rows() == 1) return detSlice(0, 0);
else if (detSlice.rows() == 2) return detSlice(0, 0) * detSlice(1, 1)
- detSlice(0, 1) * detSlice(1, 0);
else if (detSlice.rows() == 3) return detSlice(0, 0) * detSlice(1, 1) * detSlice(2, 2)
- detSlice(0, 0) * detSlice(1, 2) * detSlice(2, 1)
- detSlice(0, 1) * detSlice(1, 0) * detSlice(2, 2)
+ detSlice(0, 1) * detSlice(1, 2) * detSlice(2, 0)
+ detSlice(0, 2) * detSlice(1, 0) * detSlice(2, 1)
- detSlice(0, 2) * detSlice(1, 1) * detSlice(2, 0);
else if (detSlice.rows() == 4) return detSlice(0,3) * detSlice(1,2) * detSlice(2,1) * detSlice(3,0) - detSlice(0,2) * detSlice(1,3) * detSlice(2,1) * detSlice(3,0) -
detSlice(0,3) * detSlice(1,1) * detSlice(2,2) * detSlice(3,0) + detSlice(0,1) * detSlice(1,3) * detSlice(2,2) * detSlice(3,0) +
detSlice(0,2) * detSlice(1,1) * detSlice(2,3) * detSlice(3,0) - detSlice(0,1) * detSlice(1,2) * detSlice(2,3) * detSlice(3,0) -
detSlice(0,3) * detSlice(1,2) * detSlice(2,0) * detSlice(3,1) + detSlice(0,2) * detSlice(1,3) * detSlice(2,0) * detSlice(3,1) +
detSlice(0,3) * detSlice(1,0) * detSlice(2,2) * detSlice(3,1) - detSlice(0,0) * detSlice(1,3) * detSlice(2,2) * detSlice(3,1) -
detSlice(0,2) * detSlice(1,0) * detSlice(2,3) * detSlice(3,1) + detSlice(0,0) * detSlice(1,2) * detSlice(2,3) * detSlice(3,1) +
detSlice(0,3) * detSlice(1,1) * detSlice(2,0) * detSlice(3,2) - detSlice(0,1) * detSlice(1,3) * detSlice(2,0) * detSlice(3,2) -
detSlice(0,3) * detSlice(1,0) * detSlice(2,1) * detSlice(3,2) + detSlice(0,0) * detSlice(1,3) * detSlice(2,1) * detSlice(3,2) +
detSlice(0,1) * detSlice(1,0) * detSlice(2,3) * detSlice(3,2) - detSlice(0,0) * detSlice(1,1) * detSlice(2,3) * detSlice(3,2) -
detSlice(0,2) * detSlice(1,1) * detSlice(2,0) * detSlice(3,3) + detSlice(0,1) * detSlice(1,2) * detSlice(2,0) * detSlice(3,3) +
detSlice(0,2) * detSlice(1,0) * detSlice(2,1) * detSlice(3,3) - detSlice(0,0) * detSlice(1,2) * detSlice(2,1) * detSlice(3,3) -
detSlice(0,1) * detSlice(1,0) * detSlice(2,2) * detSlice(3,3) + detSlice(0,0) * detSlice(1,1) * detSlice(2,2) * detSlice(3,3);
else if (detSlice.rows() == 5) return detSlice(0, 0) * detSlice(1, 1) * detSlice(2, 2) * detSlice(3, 3) * detSlice(4, 4)
- detSlice(0, 0) * detSlice(1, 1) * detSlice(2, 2) * detSlice(3, 4) * detSlice(4, 3)
- detSlice(0, 0) * detSlice(1, 1) * detSlice(2, 3) * detSlice(3, 2) * detSlice(4, 4)
+ detSlice(0, 0) * detSlice(1, 1) * detSlice(2, 3) * detSlice(3, 4) * detSlice(4, 2)
+ detSlice(0, 0) * detSlice(1, 1) * detSlice(2, 4) * detSlice(3, 2) * detSlice(4, 3)
- detSlice(0, 0) * detSlice(1, 1) * detSlice(2, 4) * detSlice(3, 3) * detSlice(4, 2)
- detSlice(0, 0) * detSlice(1, 2) * detSlice(2, 1) * detSlice(3, 3) * detSlice(4, 4)
+ detSlice(0, 0) * detSlice(1, 2) * detSlice(2, 1) * detSlice(3, 4) * detSlice(4, 3)
+ detSlice(0, 0) * detSlice(1, 2) * detSlice(2, 3) * detSlice(3, 1) * detSlice(4, 4)
- detSlice(0, 0) * detSlice(1, 2) * detSlice(2, 3) * detSlice(3, 4) * detSlice(4, 1)
- detSlice(0, 0) * detSlice(1, 2) * detSlice(2, 4) * detSlice(3, 1) * detSlice(4, 3)
+ detSlice(0, 0) * detSlice(1, 2) * detSlice(2, 4) * detSlice(3, 3) * detSlice(4, 1)
+ detSlice(0, 0) * detSlice(1, 3) * detSlice(2, 1) * detSlice(3, 2) * detSlice(4, 4)
- detSlice(0, 0) * detSlice(1, 3) * detSlice(2, 1) * detSlice(3, 4) * detSlice(4, 2)
- detSlice(0, 0) * detSlice(1, 3) * detSlice(2, 2) * detSlice(3, 1) * detSlice(4, 4)
+ detSlice(0, 0) * detSlice(1, 3) * detSlice(2, 2) * detSlice(3, 4) * detSlice(4, 1)
+ detSlice(0, 0) * detSlice(1, 3) * detSlice(2, 4) * detSlice(3, 1) * detSlice(4, 2)
- detSlice(0, 0) * detSlice(1, 3) * detSlice(2, 4) * detSlice(3, 2) * detSlice(4, 1)
- detSlice(0, 0) * detSlice(1, 4) * detSlice(2, 1) * detSlice(3, 2) * detSlice(4, 3)
+ detSlice(0, 0) * detSlice(1, 4) * detSlice(2, 1) * detSlice(3, 3) * detSlice(4, 2)
+ detSlice(0, 0) * detSlice(1, 4) * detSlice(2, 2) * detSlice(3, 1) * detSlice(4, 3)
- detSlice(0, 0) * detSlice(1, 4) * detSlice(2, 2) * detSlice(3, 3) * detSlice(4, 1)
- detSlice(0, 0) * detSlice(1, 4) * detSlice(2, 3) * detSlice(3, 1) * detSlice(4, 2)
+ detSlice(0, 0) * detSlice(1, 4) * detSlice(2, 3) * detSlice(3, 2) * detSlice(4, 1)
- detSlice(0, 1) * detSlice(1, 0) * detSlice(2, 2) * detSlice(3, 3) * detSlice(4, 4)
+ detSlice(0, 1) * detSlice(1, 0) * detSlice(2, 2) * detSlice(3, 4) * detSlice(4, 3)
+ detSlice(0, 1) * detSlice(1, 0) * detSlice(2, 3) * detSlice(3, 2) * detSlice(4, 4)
- detSlice(0, 1) * detSlice(1, 0) * detSlice(2, 3) * detSlice(3, 4) * detSlice(4, 2)
- detSlice(0, 1) * detSlice(1, 0) * detSlice(2, 4) * detSlice(3, 2) * detSlice(4, 3)
+ detSlice(0, 1) * detSlice(1, 0) * detSlice(2, 4) * detSlice(3, 3) * detSlice(4, 2)
+ detSlice(0, 1) * detSlice(1, 2) * detSlice(2, 0) * detSlice(3, 3) * detSlice(4, 4)
- detSlice(0, 1) * detSlice(1, 2) * detSlice(2, 0) * detSlice(3, 4) * detSlice(4, 3)
- detSlice(0, 1) * detSlice(1, 2) * detSlice(2, 3) * detSlice(3, 0) * detSlice(4, 4)
+ detSlice(0, 1) * detSlice(1, 2) * detSlice(2, 3) * detSlice(3, 4) * detSlice(4, 0)
+ detSlice(0, 1) * detSlice(1, 2) * detSlice(2, 4) * detSlice(3, 0) * detSlice(4, 3)
- detSlice(0, 1) * detSlice(1, 2) * detSlice(2, 4) * detSlice(3, 3) * detSlice(4, 0)
- detSlice(0, 1) * detSlice(1, 3) * detSlice(2, 0) * detSlice(3, 2) * detSlice(4, 4)
+ detSlice(0, 1) * detSlice(1, 3) * detSlice(2, 0) * detSlice(3, 4) * detSlice(4, 2)
+ detSlice(0, 1) * detSlice(1, 3) * detSlice(2, 2) * detSlice(3, 0) * detSlice(4, 4)
- detSlice(0, 1) * detSlice(1, 3) * detSlice(2, 2) * detSlice(3, 4) * detSlice(4, 0)
- detSlice(0, 1) * detSlice(1, 3) * detSlice(2, 4) * detSlice(3, 0) * detSlice(4, 2)
+ detSlice(0, 1) * detSlice(1, 3) * detSlice(2, 4) * detSlice(3, 2) * detSlice(4, 0)
+ detSlice(0, 1) * detSlice(1, 4) * detSlice(2, 0) * detSlice(3, 2) * detSlice(4, 3)
- detSlice(0, 1) * detSlice(1, 4) * detSlice(2, 0) * detSlice(3, 3) * detSlice(4, 2)
- detSlice(0, 1) * detSlice(1, 4) * detSlice(2, 2) * detSlice(3, 0) * detSlice(4, 3)
+ detSlice(0, 1) * detSlice(1, 4) * detSlice(2, 2) * detSlice(3, 3) * detSlice(4, 0)
+ detSlice(0, 1) * detSlice(1, 4) * detSlice(2, 3) * detSlice(3, 0) * detSlice(4, 2)
- detSlice(0, 1) * detSlice(1, 4) * detSlice(2, 3) * detSlice(3, 2) * detSlice(4, 0)
+ detSlice(0, 2) * detSlice(1, 0) * detSlice(2, 1) * detSlice(3, 3) * detSlice(4, 4)
- detSlice(0, 2) * detSlice(1, 0) * detSlice(2, 1) * detSlice(3, 4) * detSlice(4, 3)
- detSlice(0, 2) * detSlice(1, 0) * detSlice(2, 3) * detSlice(3, 1) * detSlice(4, 4)
+ detSlice(0, 2) * detSlice(1, 0) * detSlice(2, 3) * detSlice(3, 4) * detSlice(4, 1)
+ detSlice(0, 2) * detSlice(1, 0) * detSlice(2, 4) * detSlice(3, 1) * detSlice(4, 3)
- detSlice(0, 2) * detSlice(1, 0) * detSlice(2, 4) * detSlice(3, 3) * detSlice(4, 1)
- detSlice(0, 2) * detSlice(1, 1) * detSlice(2, 0) * detSlice(3, 3) * detSlice(4, 4)
+ detSlice(0, 2) * detSlice(1, 1) * detSlice(2, 0) * detSlice(3, 4) * detSlice(4, 3)
+ detSlice(0, 2) * detSlice(1, 1) * detSlice(2, 3) * detSlice(3, 0) * detSlice(4, 4)
- detSlice(0, 2) * detSlice(1, 1) * detSlice(2, 3) * detSlice(3, 4) * detSlice(4, 0)
- detSlice(0, 2) * detSlice(1, 1) * detSlice(2, 4) * detSlice(3, 0) * detSlice(4, 3)
+ detSlice(0, 2) * detSlice(1, 1) * detSlice(2, 4) * detSlice(3, 3) * detSlice(4, 0)
+ detSlice(0, 2) * detSlice(1, 3) * detSlice(2, 0) * detSlice(3, 1) * detSlice(4, 4)
- detSlice(0, 2) * detSlice(1, 3) * detSlice(2, 0) * detSlice(3, 4) * detSlice(4, 1)
- detSlice(0, 2) * detSlice(1, 3) * detSlice(2, 1) * detSlice(3, 0) * detSlice(4, 4)
+ detSlice(0, 2) * detSlice(1, 3) * detSlice(2, 1) * detSlice(3, 4) * detSlice(4, 0)
+ detSlice(0, 2) * detSlice(1, 3) * detSlice(2, 4) * detSlice(3, 0) * detSlice(4, 1)
- detSlice(0, 2) * detSlice(1, 3) * detSlice(2, 4) * detSlice(3, 1) * detSlice(4, 0)
- detSlice(0, 2) * detSlice(1, 4) * detSlice(2, 0) * detSlice(3, 1) * detSlice(4, 3)
+ detSlice(0, 2) * detSlice(1, 4) * detSlice(2, 0) * detSlice(3, 3) * detSlice(4, 1)
+ detSlice(0, 2) * detSlice(1, 4) * detSlice(2, 1) * detSlice(3, 0) * detSlice(4, 3)
- detSlice(0, 2) * detSlice(1, 4) * detSlice(2, 1) * detSlice(3, 3) * detSlice(4, 0)
- detSlice(0, 2) * detSlice(1, 4) * detSlice(2, 3) * detSlice(3, 0) * detSlice(4, 1)
+ detSlice(0, 2) * detSlice(1, 4) * detSlice(2, 3) * detSlice(3, 1) * detSlice(4, 0)
- detSlice(0, 3) * detSlice(1, 0) * detSlice(2, 1) * detSlice(3, 2) * detSlice(4, 4)
+ detSlice(0, 3) * detSlice(1, 0) * detSlice(2, 1) * detSlice(3, 4) * detSlice(4, 2)
+ detSlice(0, 3) * detSlice(1, 0) * detSlice(2, 2) * detSlice(3, 1) * detSlice(4, 4)
- detSlice(0, 3) * detSlice(1, 0) * detSlice(2, 2) * detSlice(3, 4) * detSlice(4, 1)
- detSlice(0, 3) * detSlice(1, 0) * detSlice(2, 4) * detSlice(3, 1) * detSlice(4, 2)
+ detSlice(0, 3) * detSlice(1, 0) * detSlice(2, 4) * detSlice(3, 2) * detSlice(4, 1)
+ detSlice(0, 3) * detSlice(1, 1) * detSlice(2, 0) * detSlice(3, 2) * detSlice(4, 4)
- detSlice(0, 3) * detSlice(1, 1) * detSlice(2, 0) * detSlice(3, 4) * detSlice(4, 2)
- detSlice(0, 3) * detSlice(1, 1) * detSlice(2, 2) * detSlice(3, 0) * detSlice(4, 4)
+ detSlice(0, 3) * detSlice(1, 1) * detSlice(2, 2) * detSlice(3, 4) * detSlice(4, 0)
+ detSlice(0, 3) * detSlice(1, 1) * detSlice(2, 4) * detSlice(3, 0) * detSlice(4, 2)
- detSlice(0, 3) * detSlice(1, 1) * detSlice(2, 4) * detSlice(3, 2) * detSlice(4, 0)
- detSlice(0, 3) * detSlice(1, 2) * detSlice(2, 0) * detSlice(3, 1) * detSlice(4, 4)
+ detSlice(0, 3) * detSlice(1, 2) * detSlice(2, 0) * detSlice(3, 4) * detSlice(4, 1)
+ detSlice(0, 3) * detSlice(1, 2) * detSlice(2, 1) * detSlice(3, 0) * detSlice(4, 4)
- detSlice(0, 3) * detSlice(1, 2) * detSlice(2, 1) * detSlice(3, 4) * detSlice(4, 0)
- detSlice(0, 3) * detSlice(1, 2) * detSlice(2, 4) * detSlice(3, 0) * detSlice(4, 1)
+ detSlice(0, 3) * detSlice(1, 2) * detSlice(2, 4) * detSlice(3, 1) * detSlice(4, 0)
+ detSlice(0, 3) * detSlice(1, 4) * detSlice(2, 0) * detSlice(3, 1) * detSlice(4, 2)
- detSlice(0, 3) * detSlice(1, 4) * detSlice(2, 0) * detSlice(3, 2) * detSlice(4, 1)
- detSlice(0, 3) * detSlice(1, 4) * detSlice(2, 1) * detSlice(3, 0) * detSlice(4, 2)
+ detSlice(0, 3) * detSlice(1, 4) * detSlice(2, 1) * detSlice(3, 2) * detSlice(4, 0)
+ detSlice(0, 3) * detSlice(1, 4) * detSlice(2, 2) * detSlice(3, 0) * detSlice(4, 1)
- detSlice(0, 3) * detSlice(1, 4) * detSlice(2, 2) * detSlice(3, 1) * detSlice(4, 0)
+ detSlice(0, 4) * detSlice(1, 0) * detSlice(2, 1) * detSlice(3, 2) * detSlice(4, 3)
- detSlice(0, 4) * detSlice(1, 0) * detSlice(2, 1) * detSlice(3, 3) * detSlice(4, 2)
- detSlice(0, 4) * detSlice(1, 0) * detSlice(2, 2) * detSlice(3, 1) * detSlice(4, 3)
+ detSlice(0, 4) * detSlice(1, 0) * detSlice(2, 2) * detSlice(3, 3) * detSlice(4, 1)
+ detSlice(0, 4) * detSlice(1, 0) * detSlice(2, 3) * detSlice(3, 1) * detSlice(4, 2)
- detSlice(0, 4) * detSlice(1, 0) * detSlice(2, 3) * detSlice(3, 2) * detSlice(4, 1)
- detSlice(0, 4) * detSlice(1, 1) * detSlice(2, 0) * detSlice(3, 2) * detSlice(4, 3)
+ detSlice(0, 4) * detSlice(1, 1) * detSlice(2, 0) * detSlice(3, 3) * detSlice(4, 2)
+ detSlice(0, 4) * detSlice(1, 1) * detSlice(2, 2) * detSlice(3, 0) * detSlice(4, 3)
- detSlice(0, 4) * detSlice(1, 1) * detSlice(2, 2) * detSlice(3, 3) * detSlice(4, 0)
- detSlice(0, 4) * detSlice(1, 1) * detSlice(2, 3) * detSlice(3, 0) * detSlice(4, 2)
+ detSlice(0, 4) * detSlice(1, 1) * detSlice(2, 3) * detSlice(3, 2) * detSlice(4, 0)
+ detSlice(0, 4) * detSlice(1, 2) * detSlice(2, 0) * detSlice(3, 1) * detSlice(4, 3)
- detSlice(0, 4) * detSlice(1, 2) * detSlice(2, 0) * detSlice(3, 3) * detSlice(4, 1)
- detSlice(0, 4) * detSlice(1, 2) * detSlice(2, 1) * detSlice(3, 0) * detSlice(4, 3)
+ detSlice(0, 4) * detSlice(1, 2) * detSlice(2, 1) * detSlice(3, 3) * detSlice(4, 0)
+ detSlice(0, 4) * detSlice(1, 2) * detSlice(2, 3) * detSlice(3, 0) * detSlice(4, 1)
- detSlice(0, 4) * detSlice(1, 2) * detSlice(2, 3) * detSlice(3, 1) * detSlice(4, 0)
- detSlice(0, 4) * detSlice(1, 3) * detSlice(2, 0) * detSlice(3, 1) * detSlice(4, 2)
+ detSlice(0, 4) * detSlice(1, 3) * detSlice(2, 0) * detSlice(3, 2) * detSlice(4, 1)
+ detSlice(0, 4) * detSlice(1, 3) * detSlice(2, 1) * detSlice(3, 0) * detSlice(4, 2)
- detSlice(0, 4) * detSlice(1, 3) * detSlice(2, 1) * detSlice(3, 2) * detSlice(4, 0)
- detSlice(0, 4) * detSlice(1, 3) * detSlice(2, 2) * detSlice(3, 0) * detSlice(4, 1)
+ detSlice(0, 4) * detSlice(1, 3) * detSlice(2, 2) * detSlice(3, 1) * detSlice(4, 0);
else return detSlice.determinant();
}
//pfaffian of a real matrix using Hessenberg decomposition
double calcPfaffianH(const Eigen::MatrixXd &mat);
//pfaffian of a complex matrix using Parlett-Reid algorithm
std::complex<double> calcPfaffian(const Eigen::MatrixXcd &mat);
#endif
<file_sep>import numpy
import math
from pyscf import gto, scf, ao2mo, mcscf, tools, fci, mp
#from pyscf.shciscf import shci, settings
from pyscf.lo import pipek, boys
import sys
UHF = False
bondlength = 2.2
r = bondlength*0.529177
n = 20
order = 2
atomstring = ""
for i in range(n):
atomstring += "H 0 0 %g\n"%(i*r)
mol = gto.M(
atom = atomstring,
basis = 'sto-6g',
verbose=4,
symmetry=0,
spin = 0)
myhf = scf.RHF(mol)
if (UHF) :
myhf = scf.UHF(mol)
print myhf.kernel()
if UHF :
mocoeff = myhf.mo_coeff[0]
else:
mocoeff = myhf.mo_coeff
lmo = pipek.PM(mol).kernel(mocoeff)
#print the atom with which the lmo is associated
orbitalOrder = []
for i in range(lmo.shape[1]):
orbitalOrder.append(numpy.argmax(numpy.absolute(lmo[:,i])) )
print orbitalOrder
norbs = len(orbitalOrder)
#f = open("correlators.txt", 'w')
#print sorted(orbitalOrder)
reorder = []
for i in range(norbs):
reorder.append(orbitalOrder.index(i))
for i in range(norbs-order+1):
l =[]
for j in range(order):
l.append(reorder[i+j])
l = sorted(l)
for j in range(order):
f.write("%d "%(l[j]))
f.write("\n")
f.close()
#this gives the mo coeffficients in terms of lmo
S = myhf.get_ovlp(mol)
uc = reduce(numpy.dot, (mocoeff.T, S, lmo)).T
if UHF :
uc2 = reduce(numpy.dot, (myhf.mo_coeff[1].T, S, lmo)).T
else:
uc2 = uc
norbs = mocoeff.shape[0]
print norbs
#write the UC(lmo, mo) to disk
#fileHF = open("hf.txt", 'w')
#for i in range(norbs):
# print i, norbs
# for j in range(norbs):
# fileHF.write('%16.10e '%(uc[i,j]))
# if (UHF) :
# for j in range(norbs):
# fileHF.write('%16.10e '%(uc2[i,j]))
# fileHF.write('\n')
#
##start a casci calculation for printing FCIDUMP file
#mc = mcscf.CASCI(myhf, mocoeff.shape[0], n)
#mc.fcisolver = shci.SHCI(mol)
#mc.fcisolver.sweep_iter =[0]
#mc.fcisolver.sweep_epsilon=[10]
#mc.kernel(lmo)
<file_sep>import numpy as np
norb = 18
matr = np.full((norb, norb), 0.)
mati = np.full((norb, norb), 0.)
row = 0
fileh = open("pairMatAGP.txt", 'r')
for line in fileh:
col = 0
for coeff in line.split():
m = coeff.strip()[1:-1]
matr[row, col], mati[row, col] = [float(x) for x in m.split(',')]
col = col + 1
row = row + 1
fileh.close()
rmat = (np.random.rand(norb,norb) + 1j * np.random.rand(norb,norb))/50
rmat = rmat - rmat.T
fileHF = open("pairMat.txt", 'w')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(rmat[i,j].real))
for j in range(norb):
fileHF.write('%16.10e '%(matr[i,j]))
fileHF.write('\n')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(-matr[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(rmat[i,j].real))
fileHF.write('\n')
fileHF.close()
fileHF = open("pairMati.txt", 'w')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(rmat[i,j].imag))
for j in range(norb):
fileHF.write('%16.10e '%(mati[i,j]))
fileHF.write('\n')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(-mati[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(rmat[i,j].imag))
fileHF.write('\n')
fileHF.close()
<file_sep>import numpy
import math
from pyscf import gto, scf, ao2mo, mcscf, tools, fci
from pyscf.shciscf import shci, settings
from pyscf.lo import pipek
r = 0.529177
atomstring = ""
for i in range(20):
atomstring += "H 0 0 %g\n"%(i*r)
mol = gto.M(
atom = atomstring,
basis = 'sto-6g',
verbose=2,
symmetry=0,
spin = 0)
myhf = scf.RHF(mol)
myhf.kernel()
print myhf.e_tot
#localized orbitals
lmo = pipek.PM(mol).kernel(myhf.mo_coeff)
#print the atom with which the lmo is associated
for i in range(lmo.shape[1]):
print numpy.argmax(numpy.absolute(lmo[:,i])),
print
#this gives the mo coeffficients in terms of lmo
S = myhf.get_ovlp(mol)
uc = reduce(numpy.dot, (myhf.mo_coeff.T, S, lmo)).T
#write the UC(lmo, mo) to disk
norbs = myhf.mo_coeff.shape[0]
fileHF = open("hf.txt", 'w')
for i in range(norbs):
for j in range(norbs):
fileHF.write('%16.10e '%(uc[i,j]))
fileHF.write('\n')
#start a casci calculation for printing FCIDUMP file
mc = mcscf.CASCI(myhf, myhf.mo_coeff.shape[0], 20)
mc.fcisolver = shci.SHCI(mol)
mc.kernel(lmo)
<file_sep>#pragma once
#include "CxMemoryStack.h"
#include "Kernel.h"
class BasisShell;
class LatticeSum;
double calcCoulombIntegralPeriodic_Boys(int n1, double Ax, double Ay, double Az,
double expA, double normA,
int n2, double Bx, double By, double Bz,
double expB, double normB,
double Lx, double Ly, double Lz,
double* IntOut);
void Int2e2c_EvalCoKernels(double *pCoFmT, uint TotalL,
BasisShell *pA, BasisShell *pC,
double Tx, double Ty, double Tz,
double PrefactorExt, double* pInv2Alpha, double* pInv2Gamma,
Kernel* kernel,
LatticeSum& latsum, ct::FMemoryStack &Mem);
void Int2e2c_EvalCoShY(double *&pOutR, unsigned &TotalCo, BasisShell *pA,
BasisShell *pC, double Tx, double Ty, double Tz,
double Prefactor, unsigned TotalLab,
double* pInv2Alpha, double* pInv2Gamma,
Kernel* kernel,
LatticeSum& latsum, ct::FMemoryStack& Mem);
void EvalInt2e2c( double *pOut, size_t StrideA, size_t StrideC,
BasisShell *pA, BasisShell *pC,
double Prefactor, bool Add,
Kernel* kernel,
LatticeSum& latsum, ct::FMemoryStack &Mem );
void makeReciprocalSummation(double *&pOutR, unsigned &TotalCo, BasisShell *pA,
BasisShell *pC, double Tx, double Ty, double Tz,
double Prefactor, unsigned TotalLab, double* pInv2Alpha,
double* pInv2Gamma, Kernel* kernel, LatticeSum& latsum,
ct::FMemoryStack& Mem);
void makeRealSummation(double *&pOutR, unsigned &TotalCo, BasisShell *pA,
BasisShell *pC, double Tx, double Ty, double Tz,
double Prefactor, unsigned TotalLab, double* pInv2Alpha,
double* pInv2Gamma, Kernel* kernel, LatticeSum& latsum,
ct::FMemoryStack& Mem);
void Add2(double * pOut, double const * pIn, double f, size_t n);
void Scatter2e2c(double * pOut, size_t StrideA, size_t StrideC,
double const * pIn, size_t la, size_t lc, size_t nComp,
size_t nCoA, size_t nCoC, bool Add);
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace NEVPT2_CAAV {
FTensorDecl TensorDecls[47] = {
/* 0*/{"t", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "cAae", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"f", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"f", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 6*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 7*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 8*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 9*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 13*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 14*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S1", "AaAa", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"T", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 18*/{"p1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 19*/{"p2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"Ap1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"Ap2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"b1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"b2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"b", "", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"P", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 26*/{"AP", "cAae", "",USAGE_Amplitude, STORAGE_Memory},
/* 27*/{"B1", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 28*/{"B2", "caae", "",USAGE_Amplitude, STORAGE_Memory},
/* 29*/{"B", "", "",USAGE_Amplitude, STORAGE_Memory},
/* 30*/{"W", "eaca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 31*/{"W", "aeca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 32*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 33*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 34*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 35*/{"p", "", "",USAGE_Amplitude, STORAGE_Memory},
/* 36*/{"Ap", "", "",USAGE_Amplitude, STORAGE_Memory},
/* 37*/{"f", "ec", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 38*/{"I0", "ec", "",USAGE_PlaceHolder, STORAGE_Memory},
/* 39*/{"I1", "ce", "", USAGE_PlaceHolder, STORAGE_Memory}, //21 SB
/* 40*/{"I2", "aaaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //16 S
/* 41*/{"I3", "aaaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //16 notused
/* 42*/{"I4", "ceaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //10 b
/* 43*/{"I5", "ceaa", "", USAGE_PlaceHolder, STORAGE_Memory}, //22 SB
/* 44*/{"I6", "ce", "", USAGE_PlaceHolder, STORAGE_Memory}, //19 B
/* 45*/{"I7", "caa", "", USAGE_PlaceHolder, STORAGE_Memory}, //20 B
/* 46*/{"I8", "aea", "", USAGE_PlaceHolder, STORAGE_Memory}, //9 B
};
//Number of terms : 8
FEqInfo EqsHandCode[6] = {
{"JB,Pabc,caQb,JPQB", 2.0 , 4, {39,12,40,18}}, //Ap1[JRSB] += 2.0 W[Pabc] E3[SabRcQ] p1[JPQB]
{"JB,Qabc,bPca,JPQB", -2.0 , 4, {39,12,40,18}}, //Ap1[JRSB] += -2.0 W[Qabc] E3[PSabRc] p1[JPQB]
//
{"JB,Pabc,caQb,JPQB", -1.0 , 4, {39,12,40,19}}, //Ap1[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p2[JPQB]
{"JB,Qabc,bPca,JPQB", 1.0 , 4, {39,12,40,19}}, //Ap1[JRSB] += 1.0 W[Qabc] E3[PSabRc] p2[JPQB]
//
{"JB,Pabc,caQb,JPQB", -1.0 , 4, {44,12,40,18}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p1[JPQB]
{"JB,Qabc,bPca,JPQB", 1.0 , 4, {44,12,40,18}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSabRc] p1[JPQB]
//
};
//Number of terms : 8
FEqInfo EqsHandCode2[2] = {
{"JB,Qabc,Pcab,JPQB", 1.0 , 4, {44,12,41,19}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSaRbc] p2[JPQB]
{"JB,Pabc,bcaQ,JPQB", -1.0 , 4, {44,12,41,19}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabQcR] p2[JPQB]
};
//Number of terms : 56
FEqInfo EqsRes[48] = {
{"JRSB,PR,SQ,JPQB", 2.0 , 4, {20,3,13,18}}, //Ap1[JRSB] += 2.0 f[PR] E1[SQ] p1[JPQB]
{"JRSB,IJ,SQ,IRQB", -2.0 , 4, {20,2,13,18}}, //Ap1[JRSB] += -2.0 f[IJ] E1[SQ] p1[IRQB]
{"JRSB,AB,SQ,JRQA", 2.0 , 4, {20,4,13,18}}, //Ap1[JRSB] += 2.0 f[AB] E1[SQ] p1[JRQA]
{"JRSB,Qa,Sa,JRQB", -2.0 , 4, {20,3,13,18}}, //Ap1[JRSB] += -2.0 f[Qa] E1[Sa] p1[JRQB]
{"JRSB,IJ,PSQR,IPQB", -2.0 , 4, {20,2,14,18}}, //Ap1[JRSB] += -2.0 f[IJ] E2[PSQR] p1[IPQB]
{"JRSB,AB,PSQR,JPQA", 2.0 , 4, {20,4,14,18}}, //Ap1[JRSB] += 2.0 f[AB] E2[PSQR] p1[JPQA]
{"JRSB,Pa,SaRQ,JPQB", 2.0 , 4, {20,3,14,18}}, //Ap1[JRSB] += 2.0 f[Pa] E2[SaRQ] p1[JPQB]
{"JRSB,Qa,PSaR,JPQB", -2.0 , 4, {20,3,14,18}}, //Ap1[JRSB] += -2.0 f[Qa] E2[PSaR] p1[JPQB]
{"JRSB,PRab,SabQ,JPQB", 2.0 , 4, {20,12,14,18}}, //Ap1[JRSB] += 2.0 W[PRab] E2[SabQ] p1[JPQB]
{"JRSB,PaRb,SaQb,JPQB", 2.0 , 4, {20,12,14,18}}, //Ap1[JRSB] += 2.0 W[PaRb] E2[SaQb] p1[JPQB]
{"JRSB,QRab,PSab,JPQB", -2.0 , 4, {20,12,14,18}}, //Ap1[JRSB] += -2.0 W[QRab] E2[PSab] p1[JPQB]
{"JRSB,Qabc,Sabc,JRQB", -2.0 , 4, {20,12,14,18}}, //Ap1[JRSB] += -2.0 W[Qabc] E2[Sabc] p1[JRQB]
//{"JRSB,Pabc,SabRcQ,JPQB", 2.0 , 4, {20,12,15,18}}, //Ap1[JRSB] += 2.0 W[Pabc] E3[SabRcQ] p1[JPQB]
//{"JRSB,Qabc,PSabRc,JPQB", -2.0 , 4, {20,12,15,18}}, //Ap1[JRSB] += -2.0 W[Qabc] E3[PSabRc] p1[JPQB]
//
{"JRSB,PR,SQ,JPQB", -1.0 , 4, {21,3,13,18}}, //Ap2[JRSB] += -1.0 f[PR] E1[SQ] p1[JPQB]
{"JRSB,IJ,SQ,IRQB", 1.0 , 4, {21,2,13,18}}, //Ap2[JRSB] += 1.0 f[IJ] E1[SQ] p1[IRQB]
{"JRSB,AB,SQ,JRQA", -1.0 , 4, {21,4,13,18}}, //Ap2[JRSB] += -1.0 f[AB] E1[SQ] p1[JRQA]
{"JRSB,Qa,Sa,JRQB", 1.0 , 4, {21,3,13,18}}, //Ap2[JRSB] += 1.0 f[Qa] E1[Sa] p1[JRQB]
{"JRSB,IJ,PSQR,IPQB", 1.0 , 4, {21,2,14,18}}, //Ap2[JRSB] += 1.0 f[IJ] E2[PSQR] p1[IPQB]
{"JRSB,AB,PSQR,JPQA", -1.0 , 4, {21,4,14,18}}, //Ap2[JRSB] += -1.0 f[AB] E2[PSQR] p1[JPQA]
{"JRSB,Pa,SaRQ,JPQB", -1.0 , 4, {21,3,14,18}}, //Ap2[JRSB] += -1.0 f[Pa] E2[SaRQ] p1[JPQB]
{"JRSB,Qa,PSaR,JPQB", 1.0 , 4, {21,3,14,18}}, //Ap2[JRSB] += 1.0 f[Qa] E2[PSaR] p1[JPQB]
{"JRSB,PRab,SabQ,JPQB", -1.0 , 4, {21,12,14,18}}, //Ap2[JRSB] += -1.0 W[PRab] E2[SabQ] p1[JPQB]
{"JRSB,PaRb,SaQb,JPQB", -1.0 , 4, {21,12,14,18}}, //Ap2[JRSB] += -1.0 W[PaRb] E2[SaQb] p1[JPQB]
{"JRSB,QRab,PSab,JPQB", 1.0 , 4, {21,12,14,18}}, //Ap2[JRSB] += 1.0 W[QRab] E2[PSab] p1[JPQB]
{"JRSB,Qabc,Sabc,JRQB", 1.0 , 4, {21,12,14,18}}, //Ap2[JRSB] += 1.0 W[Qabc] E2[Sabc] p1[JRQB]
//{"JRSB,Pabc,SabRcQ,JPQB", -1.0 , 4, {21,12,15,18}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p1[JPQB]
//{"JRSB,Qabc,PSabRc,JPQB", 1.0 , 4, {21,12,15,18}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSabRc] p1[JPQB]
//
{"JRSB,PR,SQ,JPQB", -1.0 , 4, {20,3,13,19}}, //Ap1[JRSB] += -1.0 f[PR] E1[SQ] p2[JPQB]
{"JRSB,IJ,SQ,IRQB", 1.0 , 4, {20,2,13,19}}, //Ap1[JRSB] += 1.0 f[IJ] E1[SQ] p2[IRQB]
{"JRSB,AB,SQ,JRQA", -1.0 , 4, {20,4,13,19}}, //Ap1[JRSB] += -1.0 f[AB] E1[SQ] p2[JRQA]
{"JRSB,Qa,Sa,JRQB", 1.0 , 4, {20,3,13,19}}, //Ap1[JRSB] += 1.0 f[Qa] E1[Sa] p2[JRQB]
{"JRSB,IJ,PSQR,IPQB", 1.0 , 4, {20,2,14,19}}, //Ap1[JRSB] += 1.0 f[IJ] E2[PSQR] p2[IPQB]
{"JRSB,AB,PSQR,JPQA", -1.0 , 4, {20,4,14,19}}, //Ap1[JRSB] += -1.0 f[AB] E2[PSQR] p2[JPQA]
{"JRSB,Pa,SaRQ,JPQB", -1.0 , 4, {20,3,14,19}}, //Ap1[JRSB] += -1.0 f[Pa] E2[SaRQ] p2[JPQB]
{"JRSB,Qa,PSaR,JPQB", 1.0 , 4, {20,3,14,19}}, //Ap1[JRSB] += 1.0 f[Qa] E2[PSaR] p2[JPQB]
{"JRSB,PRab,SabQ,JPQB", -1.0 , 4, {20,12,14,19}}, //Ap1[JRSB] += -1.0 W[PRab] E2[SabQ] p2[JPQB]
{"JRSB,PaRb,SaQb,JPQB", -1.0 , 4, {20,12,14,19}}, //Ap1[JRSB] += -1.0 W[PaRb] E2[SaQb] p2[JPQB]
{"JRSB,QRab,PSab,JPQB", 1.0 , 4, {20,12,14,19}}, //Ap1[JRSB] += 1.0 W[QRab] E2[PSab] p2[JPQB]
{"JRSB,Qabc,Sabc,JRQB", 1.0 , 4, {20,12,14,19}}, //Ap1[JRSB] += 1.0 W[Qabc] E2[Sabc] p2[JRQB]
//{"JRSB,Pabc,SabRcQ,JPQB", -1.0 , 4, {20,12,15,19}}, //Ap1[JRSB] += -1.0 W[Pabc] E3[SabRcQ] p2[JPQB]
//{"JRSB,Qabc,PSabRc,JPQB", 1.0 , 4, {20,12,15,19}}, //Ap1[JRSB] += 1.0 W[Qabc] E3[PSabRc] p2[JPQB]
//
{"JRSB,PR,SQ,JPQB", 2.0 , 4, {21,3,13,19}}, //Ap2[JRSB] += 2.0 f[PR] E1[SQ] p2[JPQB]
{"JRSB,IJ,SQ,IRQB", -2.0 , 4, {21,2,13,19}}, //Ap2[JRSB] += -2.0 f[IJ] E1[SQ] p2[IRQB]
{"JRSB,AB,SQ,JRQA", 2.0 , 4, {21,4,13,19}}, //Ap2[JRSB] += 2.0 f[AB] E1[SQ] p2[JRQA]
{"JRSB,Qa,Sa,JRQB", -2.0 , 4, {21,3,13,19}}, //Ap2[JRSB] += -2.0 f[Qa] E1[Sa] p2[JRQB]
{"JRSB,IJ,PSRQ,IPQB", 1.0 , 4, {21,2,14,19}}, //Ap2[JRSB] += 1.0 f[IJ] E2[PSRQ] p2[IPQB]
{"JRSB,AB,PSRQ,JPQA", -1.0 , 4, {21,4,14,19}}, //Ap2[JRSB] += -1.0 f[AB] E2[PSRQ] p2[JPQA]
{"JRSB,Pa,SaQR,JPQB", -1.0 , 4, {21,3,14,19}}, //Ap2[JRSB] += -1.0 f[Pa] E2[SaQR] p2[JPQB]
{"JRSB,Qa,PSRa,JPQB", 1.0 , 4, {21,3,14,19}}, //Ap2[JRSB] += 1.0 f[Qa] E2[PSRa] p2[JPQB]
{"JRSB,PRab,SaQb,JPQB", -1.0 , 4, {21,12,14,19}}, //Ap2[JRSB] += -1.0 W[PRab] E2[SaQb] p2[JPQB]
{"JRSB,PaRb,SaQb,JPQB", 2.0 , 4, {21,12,14,19}}, //Ap2[JRSB] += 2.0 W[PaRb] E2[SaQb] p2[JPQB]
{"JRSB,QRab,PSba,JPQB", 1.0 , 4, {21,12,14,19}}, //Ap2[JRSB] += 1.0 W[QRab] E2[PSba] p2[JPQB]
{"JRSB,Qabc,Sabc,JRQB", -2.0 , 4, {21,12,14,19}}, //Ap2[JRSB] += -2.0 W[Qabc] E2[Sabc] p2[JRQB]
//{"JRSB,Pabc,SabQcR,JPQB", -1.0 , 4, {21,12,15,19}}, //Ap2[JRSB] += -1.0 W[Pabc] E3[SabQcR] p2[JPQB]
//{"JRSB,Qabc,PSaRbc,JPQB", 1.0 , 4, {21,12,15,19}}, //Ap2[JRSB] += 1.0 W[Qabc] E3[PSaRbc] p2[JPQB]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[8] = {
{"IPSA,QS,APIQ", 2.0, 3, {22, 13, 30}},
{"IRSA,PSQR,APIQ", 2.0, 3, {22, 14, 30}},
{"IPSA,QS,APIQ", -1.0, 3, {23, 13, 30}},
{"IRSA,PSQR,APIQ",-1.0, 3, {23, 14, 30}},
{"IPSA,QS,PAIQ", -1.0, 3, {22, 13, 31}},
{"IRSA,PSQR,PAIQ",-1.0, 3, {22, 14, 31}},
{"IPSA,QS,PAIQ", 2.0, 3, {23, 13, 31}},
{"IRSA,PSRQ,PAIQ",-1.0, 3, {23, 14, 31}},
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "NEVPT2_CAAV";
Out.perturberClass = "CAAV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 47;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsHandCode = FEqSet(&EqsHandCode[0], 6, "MRLCC_CAAV/Res");
Out.EqsHandCode2 = FEqSet(&EqsHandCode2[0], 2, "MRLCC_CAAV/Res");
Out.EqsRes = FEqSet(&EqsRes[0], 48, "NEVPT2_CAAV/Res");
Out.Overlap = FEqSet(&Overlap[0], 8, "NEVPT2_CAAV/Overlap");
};
};
<file_sep>#ifndef MET_HEADER_H
#define MET_HEADER_H
#include <Eigen/Dense>
#include <vector>
#include "Determinants.h"
#include "workingArray.h"
#include "statistics.h"
#include "sr.h"
#include "global.h"
#include "evaluateE.h"
#include <iostream>
#include <fstream>
#include <boost/serialization/serialization.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <algorithm>
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace Eigen;
using namespace std;
using namespace boost;
enum Move
{
Amove,
Bmove,
Dmove
};
class DetMoves
{
public:
int norbs;
vector<int> a, b; //all occ alpha/beta orbs of cdet
vector<int> sa, sb; //all singly occ alpha/beta orbs of cdet
vector<int> ua, ub; //all unocc alpha/beta orbs of cdet
DetMoves(Determinant &d)
{
norbs = Determinant::norbs;
for (int i = 0; i < norbs; i++)
{
bool alpha = d.getoccA(i);
bool beta = d.getoccB(i);
if (alpha)
a.push_back(i);
else
ua.push_back(i);
if (beta)
b.push_back(i);
else
ub.push_back(i);
if (alpha && !beta)
sa.push_back(i);
if (beta && !alpha)
sb.push_back(i);
}
}
double TotalMoves()
{
return (double) (a.size() * ua.size() + b.size() * ub.size() + sa.size() * sb.size());
}
double AlphaMoves()
{
return (double) (a.size() * ua.size());
}
double BetaMoves()
{
return (double) (b.size() * ub.size());
}
double DoubleMoves()
{
return (double) (sa.size() * sb.size());
}
};
template<typename Wfn, typename Walker>
class Metropolis
{
public:
Wfn *w;
Walker *walk;
long numVars;
int norbs, nalpha, nbeta;
workingArray work;
double Eloc, ovlp;
double S1, oldEnergy;
VectorXd grad_ratio;
int nsample;
Statistics Stats; //this is only used to calculate autocorrelation length
//auto random = bind(uniform_real_distribution<double>dist(0,1), ref(generator));
Determinant bestDet;
double bestOvlp;
bool calcEloc;
double fracAmoves, n, nAMoves;
// Data for Metropolis in FOIS calculations (SCCI and SCPT)
workingArray morework, morework_new;
int nFOISExcit;
std::vector<int> validInds;
double random()
{
uniform_real_distribution<double> dist(0,1);
return dist(generator);
}
Metropolis(Wfn &_w, Walker &_walk, int niter) : w(&_w), walk(&_walk)
{
nsample = min(niter, 200000);
numVars = w->getNumVariables();
norbs = Determinant::norbs;
nalpha = Determinant::nalpha;
nbeta = Determinant::nbeta;
bestDet = walk->getDet();
S1 = 0.0, oldEnergy = 0.0, bestOvlp = 0.0, nAMoves = 0.0, n = 0.0;
calcEloc = true;
}
void LocalEnergy()
{
if (calcEloc)
{
Eloc = 0.0, ovlp = 0.0;
w->HamAndOvlp(*walk, ovlp, Eloc, work);
}
}
void MakeMove()
{
if (abs(ovlp) > bestOvlp)
{
bestOvlp = abs(ovlp);
bestDet = walk->getDet();
}
Determinant cdet = walk->getDet();
Determinant pdet = cdet;
Move move;
DetMoves C(cdet);
double P_a = C.AlphaMoves() / C.TotalMoves();
double P_b = C.BetaMoves() / C.TotalMoves();
double P_d = C.DoubleMoves() / C.TotalMoves();
double rand = random();
int orb1, orb2;
double pdetOvercdet;
if (rand < P_a)
{
move = Amove;
orb1 = C.a[(int) (random() * C.a.size())];
orb2 = C.ua[(int) (random() * C.ua.size())];
pdet.setoccA(orb1, false);
pdet.setoccA(orb2, true);
pdetOvercdet = w->getOverlapFactor(2*orb1, 0, 2*orb2, 0, *walk, false);
}
else if (rand < (P_b + P_a))
{
move = Bmove;
orb1 = C.b[(int) (random() * C.b.size())];
orb2 = C.ub[(int) (random() * C.ub.size())];
pdet.setoccB(orb1, false);
pdet.setoccB(orb2, true);
pdetOvercdet = w->getOverlapFactor(2*orb1+1, 0, 2*orb2+1, 0, *walk, false);
}
else if (rand < (P_d + P_a + P_b))
{
move = Dmove;
orb1 = C.sa[(int) (random() * C.sa.size())];
orb2 = C.sb[(int) (random() * C.sb.size())];
pdet.setoccA(orb1, false);
pdet.setoccB(orb2, false);
pdet.setoccB(orb1, true);
pdet.setoccA(orb2, true);
pdetOvercdet = w->getOverlapFactor(2*orb1, 2*orb2+1, 2*orb2, 2*orb1+1, *walk, false);
}
DetMoves P(pdet);
double T_C = 1.0 / C.TotalMoves();
double T_P = 1.0 / P.TotalMoves();
double P_pdetOvercdet = pdetOvercdet * pdetOvercdet;
double accept = min(1.0, (T_P * P_pdetOvercdet) / T_C);
if (random() < accept)
{
/*
e.push_back(Eloc);
t.push_back(weight);
weight = 1.0;
*/
nAMoves += 1.0;
calcEloc = true;
if (move == Amove)
{
walk->update(orb1, orb2, 0, w->getRef(), w->getCorr());
}
else if (move == Bmove)
{
walk->update(orb1, orb2, 1, w->getRef(), w->getCorr());
}
else if (move == Dmove)
{
walk->update(orb1, orb2, 0, w->getRef(), w->getCorr());
walk->update(orb2, orb1, 1, w->getRef(), w->getCorr());
}
}
else
{
calcEloc = false;
//weight += 1.0;
}
n += 1.0;
}
//void MakeMoveFOIS()
//{
// // If the previous move was accepted (if not then the following is stored already)
// if (calcEloc)
// {
// if (abs(ovlp) > bestOvlp)
// {
// bestOvlp = abs(ovlp);
// bestDet = walk->getDet();
// }
// nFOISExcit = 0;
// validInds.clear();
// // -- Count the number of valid excitations within the FOIS from the current determinant ----
// morework.setCounterToZero();
// generateAllScreenedSingleExcitation(walk->d, schd.epsilon, schd.screen, morework, false);
// generateAllScreenedDoubleExcitation(walk->d, schd.epsilon, schd.screen, morework, false);
// // loop over all the screened excitations
// for (int i=0; i<morework.nExcitations; i++) {
// int ex1 = morework.excitation1[i], ex2 = morework.excitation2[i];
// int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
// int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
// auto walkCopy = *walk;
// walkCopy.updateWalker(w->getRef(), w->getCorr(),
// morework.excitation1[i], morework.excitation2[i], false);
// // Is this excitation class being used? If not, then move to the next excitation.
// if (w->checkWalkerExcitationClass(walkCopy)) {
// validInds.push_back(i);
// nFOISExcit += 1;
// }
// }
// }
// // Choose the next determinant uniformly
// int nextDet = random() * nFOISExcit;
// int nextDetInd = validInds[nextDet];
// int ex1 = morework.excitation1[nextDetInd], ex2 = morework.excitation2[nextDetInd];
// int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
// int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
// double pdetOvercdet = w->getOverlapFactor(I, J, A, B, *walk, false);
// if (pdetOvercdet == 0.0)
// {
// calcEloc = false;
// n += 1.0;
// return;
// }
// // -- Count the number of valid excitations within the FOIS from the new determinant ----
// int nFOISExcit_new = 0;
// auto walkCopy = *walk;
// walkCopy.updateWalker(w->getRef(), w->getCorr(),
// morework.excitation1[nextDetInd], morework.excitation2[nextDetInd], false);
// morework_new.setCounterToZero();
// generateAllScreenedSingleExcitation(walkCopy.d, schd.epsilon, schd.screen, morework_new, false);
// generateAllScreenedDoubleExcitation(walkCopy.d, schd.epsilon, schd.screen, morework_new, false);
// //loop over all the screened excitations
// for (int i=0; i<morework_new.nExcitations; i++) {
// int ex1 = morework_new.excitation1[i], ex2 = morework_new.excitation2[i];
// int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
// int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
// auto walkCopy_new = walkCopy;
// walkCopy_new.updateWalker(w->getRef(), w->getCorr(),
// morework_new.excitation1[i], morework_new.excitation2[i], false);
// // Is this excitation class being used? If not, then move to the next excitation.
// if (w->checkWalkerExcitationClass(walkCopy_new)) {
// nFOISExcit_new += 1;
// }
// }
// double T_C = 1.0 / nFOISExcit;
// double T_P = 1.0 / nFOISExcit_new;
// double P_pdetOvercdet = pdetOvercdet * pdetOvercdet;
// double accept = min(1.0, (T_P * P_pdetOvercdet) / T_C);
// if (random() < accept)
// {
// nAMoves += 1.0;
// calcEloc = true;
// walk->updateWalker(w->getRef(), w->getCorr(),
// morework.excitation1[nextDetInd], morework.excitation2[nextDetInd], false);
// }
// else
// {
// calcEloc = false;
// }
// n += 1.0;
//}
void UpdateEnergy(double &Energy)
{
oldEnergy = Energy;
Energy += (Eloc - Energy) / n;
S1 += (Eloc - oldEnergy) * (Eloc - Energy);
if (Stats.X.size() < nsample)
{
Stats.push_back(Eloc);
}
}
void FinishEnergy(double &Energy, double &stddev, double &rk)
{
Stats.Block();
rk = Stats.BlockCorrTime();
if (commrank == 0)
{
Stats.WriteBlock();
}
S1 /= n;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &Energy, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &S1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &rk, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &nAMoves, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
Energy /= commsize;
S1 /= commsize;
rk /= commsize;
#endif
n *= (double) commsize;
stddev = sqrt(rk * S1 / n);
fracAmoves = nAMoves / n;
if (commrank == 0)
{
cout << "Fraction of accepted moves:\t" << fracAmoves << endl;
char file[50];
sprintf(file, "BestDeterminant.txt");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << bestDet;
}
}
void LocalGradient()
{
if (calcEloc)
{
grad_ratio.setZero(numVars);
w->OverlapWithGradient(*walk, ovlp, grad_ratio);
}
}
void UpdateGradient(VectorXd &grad, VectorXd &grad_ratio_bar)
{
grad_ratio_bar += grad_ratio;
grad += grad_ratio * Eloc;
}
void FinishGradient(VectorXd &grad, VectorXd &grad_ratio_bar, const double &Energy)
{
grad /= n;
grad_ratio_bar /= n;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, (grad_ratio_bar.data()), grad_ratio_bar.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, (grad.data()), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
grad /= commsize;
grad_ratio_bar /= commsize;
#endif
grad = (grad - Energy * grad_ratio_bar);
}
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef utilsFCIQMC_HEADER_H
#define utilsFCIQMC_HEADER_H
#include "Determinants.h"
#include "global.h"
// This is hash_combine closely based on that used in boost. We use this
// instead of boost::hash_combined directly, because the latter is
// inconsistent across different versions of boost, meaning that tests fail
// depending on the boost version used.
template <class T>
inline void hash_combine_proc(std::size_t& seed, const T& v);
// Get unique processor label for this determinant
int getProc(const Determinant& d, int DetLenLocal);
#endif
<file_sep>##########################
# User Specific Settings #
##########################
CXX = mpiicpc
PYSCF=/home/sash2458/newApps/pyscf/
EIGEN=/projects/sash2458/newApps/eigen/
PVFMM=/projects/sash2458/newApps/FMM/pvfmm/
BOOST=/home/sash2458/newApps/boost_1_67_0/
MKL=/curc/sw/intel/17.4/mkl/
FINUFFT=/projects/sash2458/newApps/FFT/finufft
FLAGS = -O3 -qno-offload -Qoption,cpp,--extended_float_type -std=c++17 -g -fPIC -qopenmp -I$(PVFMM)/include -I${EIGEN} -I${BOOST} -I/opt/local/include/openmpi-mp/ -I${MKL}/include -I/home/sash2458/newApps/VMC/NumericPotential/ -I${FINUFFT}/src
OBJ = BeckeGrid/fittedFunctions.o BeckeGrid/CxLebedevGrid.o BeckeGrid/CalculateSphHarmonics.o BeckeGrid/beckeInterface.o pythonInterface.o FMM/fmmInterface.o FFT/fftInterface.o
%.o: %.cpp
$(CXX) $(FLAGS) $(OPT) -c $< -o $@
all: ../bin/libPeriodic.so
../bin/libPeriodic.so: $(OBJ)
$(CXX) $(FLAGS) -shared $(OBJ) -o libPeriodic.so -L${PYSCF}pyscf/lib/ -L${PYSCF}pyscf/lib/deps/lib -lcvhf -lcint -lcgto -lpbc -L$(PVFMM) -lpvfmm -lfftw3 -ldft -L${MKL}/lib/intel64 -lmkl_rt -lpthread -lm -ldl -L${FINUFFT}/lib -lfinufft
cp libPeriodic.so ../bin/.
cp libPeriodic.so /home/sash2458/newApps/pyscf/pyscf/lib
clean :
find . -name "*.o"|xargs rm 2>/dev/null
<file_sep>#ifndef DETERMINISTIC_HEADER_H
#define DETERMINISTIC_HEADER_H
#include <Eigen/Dense>
#include <vector>
#include "Determinants.h"
#include "workingArray.h"
#include "statistics.h"
#include "sr.h"
#include "evaluateE.h"
#include "global.h"
#include <iostream>
#include <fstream>
#include <boost/serialization/serialization.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <algorithm>
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace Eigen;
using namespace std;
using namespace boost;
template<typename Wfn, typename Walker>
class Deterministic
{
public:
Wfn w;
Walker walk;
long numVars;
int norbs, nalpha, nbeta;
vector<Determinant> allDets;
workingArray work;
double ovlp, Eloc, locNorm, avgNorm;
double Overlap;
VectorXd grad_ratio;
Deterministic(Wfn _w, Walker _walk) : w(_w), walk(_walk)
{
numVars = w.getNumVariables();
norbs = Determinant::norbs;
nalpha = Determinant::nalpha;
nbeta = Determinant::nbeta;
if (schd.nciCore > 0 || schd.nciAct > 0) {
generateAllDeterminantsFOIS(allDets, norbs, nalpha, nbeta);
}
else {
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
}
Overlap = 0.0, avgNorm = 0.0;
}
void LocalEnergy(Determinant &D)
{
ovlp = 0.0, Eloc = 0.0, locNorm = 0.0;
w.initWalker(walk, D);
if (schd.debug) cout << walk << endl;
w.HamAndOvlp(walk, ovlp, Eloc, work, false);
locNorm = work.locNorm * work.locNorm;
if (schd.debug) cout << "ham " << Eloc << " locNorm " << locNorm << " ovlp " << ovlp << endl << endl;
}
void UpdateEnergy(double &Energy)
{
Overlap += ovlp * ovlp;
Energy += Eloc * ovlp * ovlp;
avgNorm += locNorm * ovlp * ovlp;
}
void FinishEnergy(double &Energy)
{
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(Overlap), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Energy), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(avgNorm), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
Energy /= avgNorm;
avgNorm /= Overlap;
}
void LocalGradient()
{
grad_ratio.setZero(numVars);
w.OverlapWithGradient(walk, ovlp, grad_ratio);
}
void UpdateGradient(VectorXd &grad, VectorXd &grad_ratio_bar)
{
grad += grad_ratio * Eloc * ovlp * ovlp / work.locNorm;
grad_ratio_bar += grad_ratio * ovlp * ovlp * work.locNorm;
}
void FinishGradient(VectorXd &grad, VectorXd &grad_ratio_bar, const double &Energy)
{
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, (grad_ratio_bar.data()), grad_ratio_bar.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, (grad.data()), grad_ratio.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
grad = (grad - Energy * grad_ratio_bar) / Overlap;
grad /= avgNorm;
}
void UpdateSR(DirectMetric &S)
{
VectorXd appended(numVars+1);
appended << 1.0, grad_ratio;
S.Vectors.push_back(appended);
S.T.push_back(ovlp * ovlp);
}
void FinishSR(const VectorXd &grad, const VectorXd &grad_ratio_bar, VectorXd &H)
{
H.setZero(numVars + 1);
VectorXd appended(numVars);
appended = grad_ratio_bar - schd.stepsize * grad;
H << 1.0, appended;
}
};
#endif
<file_sep>//#include "mkl.h"
#include "tensor.h"
int contract_IJK_IJL_LK(tensor *O, tensor *C, tensor *S, double scale, double beta) {
/*
int m = O->dimensions[0]*O->dimensions[1],
n = S->dimensions[1],
k = S->dimensions[0];
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k,
scale, C->vals, k, S->vals, n, beta, O->vals, n);
*/
int O1_dimension = (int)(O->dimensions[0]);
int O2_dimension = (int)(O->dimensions[1]);
int O3_dimension = (int)(O->dimensions[2]);
double* O_vals = (double*)(O->vals);
int C1_dimension = (int)(C->dimensions[0]);
int C2_dimension = (int)(C->dimensions[1]);
int C3_dimension = (int)(C->dimensions[2]);
double* C_vals = (double*)(C->vals);
int S1_dimension = (int)(S->dimensions[0]);
int S2_dimension = (int)(S->dimensions[1]);
double* S_vals = (double*)(S->vals);
//#pragma omp parallel for schedule(static)
for (int pO = 0; pO < ((O1_dimension * O2_dimension) * O3_dimension); pO++) {
O_vals[pO] *= beta;
}
//#pragma omp parallel for schedule(runtime)
for (int i = 0; i < C1_dimension; i++) {
for (int j = 0; j < C2_dimension; j++) {
int jO = i * O2_dimension + j;
int jC = i * C2_dimension + j;
for (int l = 0; l < S1_dimension; l++) {
int lC = jC * C3_dimension + l;
for (int k = 0; k < S2_dimension; k++) {
int kO = jO * O3_dimension + k;
int kS = l * S2_dimension + k;
O_vals[kO] = O_vals[kO] + scale * C_vals[lC] * S_vals[kS];
}
}
}
}
return 0;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPTIMIZER_HEADER_H
#define OPTIMIZER_HEADER_H
#include <Eigen/Dense>
#include <boost/serialization/serialization.hpp>
#include "iowrapper.h"
#include "global.h"
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <math.h>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
using namespace Eigen;
using namespace boost;
class AMSGrad
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & iter
& mom1
& mom2;
}
public:
double stepsize;
double decay_mom1;
double decay_mom2;
int maxIter;
int iter;
int avgIter;
VectorXd mom1;
VectorXd mom2;
AMSGrad(double pstepsize=0.001,
double pdecay_mom1=0.1, double pdecay_mom2=0.001,
int pmaxIter=1000, int pavgIter=0) : stepsize(pstepsize), decay_mom1(pdecay_mom1), decay_mom2(pdecay_mom2), maxIter(pmaxIter), avgIter(pavgIter)
{
iter = 0;
}
void write(VectorXd& vars)
{
if (commrank == 0)
{
char file[5000];
sprintf(file, "amgrad.bkp");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << *this;
save << mom1;
save << mom2;
save << vars;
ofs.close();
}
}
void read(VectorXd& vars)
{
if (commrank == 0)
{
char file[5000];
sprintf(file, "amgrad.bkp");
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> *this;
load >> mom1;
load >> mom2;
load >> vars;
ifs.close();
}
}
template<typename Function>
void optimize(VectorXd &vars, Function& getGradient, bool restart)
{
if (restart || schd.fullRestart)
{
if (commrank == 0) {
read(vars);
if (schd.fullRestart) {
mom1 = VectorXd::Zero(vars.rows());
mom2 = VectorXd::Zero(vars.rows());
}
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
boost::mpi::broadcast(world, vars, 0);
#endif
}
else if (mom1.rows() == 0)
{
mom1 = VectorXd::Zero(vars.rows());
mom2 = VectorXd::Zero(vars.rows());
}
VectorXd grad = VectorXd::Zero(vars.rows());
VectorXd avgVars = VectorXd::Zero(vars.rows());
VectorXd deltaVars = VectorXd::Zero(vars.rows());
double stepNorm = 0., angle = 0.;
while (iter < maxIter)
{
double E0, stddev = 0.0, rt = 1.0;
getGradient(vars, grad, E0, stddev, rt);
if (commrank == 0 && schd.printGrad) {cout << "totalGrad" << endl; cout << grad << endl;}
if (std::isnan(grad.norm())) grad.setZero();
if (commrank == 0 && schd.printVars) cout << endl << "ci coeffs\n" << vars << endl;
write(vars);
double oldNorm = stepNorm, dotProduct = 0.;
stepNorm = 0.;
if (commrank == 0)
{
for (int i = 0; i < vars.rows(); i++)
{
mom1[i] = decay_mom1 * grad[i] + (1. - decay_mom1) * mom1[i];
mom2[i] = max(mom2[i], decay_mom2 * grad[i]*grad[i] + (1. - decay_mom2) * mom2[i]);
if (schd.method == amsgrad)
{
double delta = stepsize * mom1[i] / (pow(mom2[i], 0.5) + 1.e-8);
vars[i] -= delta;
stepNorm += delta * delta;
dotProduct += delta * deltaVars[i];
deltaVars[i] = delta;
}
else if(schd.method == amsgrad_sgd)
{
if (iter < schd._sgdIter)
{
vars[i] -= stepsize * grad[i];
}
else
{
vars[i] -= stepsize * mom1[i] / (pow(mom2[i], 0.5) + 1.e-8);
}
}
}
stepNorm = pow(stepNorm, 0.5);
if (oldNorm != 0) angle = acos(dotProduct/stepNorm/oldNorm) * 180 / 3.14159265;
}
#ifndef SERIAL
MPI_Bcast(&vars[0], vars.rows(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0)
std::cout << format("%5i %14.8f (%8.2e) %14.8f %8.1f %10i %6.6f %8.2f %8.2f\n") % iter % E0 % stddev % (grad.norm()) % (rt) % (schd.stochasticIter) % (stepNorm) % (angle) % ((getTime() - startofCalc));
if (maxIter - iter <= avgIter) avgVars += vars;
iter++;
}
if (avgIter != 0) {
avgVars = avgVars/avgIter;
write(avgVars);
double E0, stddev = 0.0, rt = 1.0;
getGradient(avgVars, grad, E0, stddev, rt);
if (commrank == 0) {
std::cout << "Average over last " << avgIter << " iterations" << endl;
std::cout << format("0 %14.8f (%8.2e) %14.8f %8.1f %10i %8.2f\n") % E0 % stddev % (grad.norm()) % (rt) % (schd.stochasticIter) % ((getTime() - startofCalc));
}
}
}
};
#endif
<file_sep>import numpy as np
import math
from pyscf import gto, scf, ao2mo, mcscf, tools, fci, mp
from pyscf.lo import pipek, boys
import sys
from scipy.linalg import fractional_matrix_power
from scipy.stats import ortho_group
UHF = False
r = float(sys.argv[1])*0.529177
n = 10
order = 2
sqrt2 = 2**0.5
atomstring = ""
for i in range(n):
atomstring += "H 0 0 %g\n"%(i*r)
mol = gto.M(
atom = atomstring,
basis = 'ccpvdz',
verbose=4,
symmetry=0,
spin = 0)
mf = scf.RHF(mol)
print mf.kernel()
mocoeff = mf.mo_coeff
lowdin = fractional_matrix_power(mf.get_ovlp(mol), -0.5).T
pm = pipek.PM(mol).kernel(lowdin)
lmo = np.full((50, 50), 0.)
orth = ortho_group.rvs(dim=5)
for i in range(10):
lmo[::,5*i:5*(i+1)] = pm[::,5*i:5*(i+1)].dot(orth)
norb = mf.mo_coeff.shape[0]
h1 = lmo.T.dot(mf.get_hcore()).dot(lmo)
eri = ao2mo.kernel(mol, lmo)
tools.fcidump.from_integrals('FCIDUMP', h1, eri, norb, n, mf.energy_nuc())
print mf.mo_coeff
print "local"
print lmo
#print the atom with which the lmo is associated
orbitalOrder = []
for i in range(lmo.shape[1]):
orbitalOrder.append(np.argmax(np.absolute(lmo[:,i])) )
print orbitalOrder
ovlp = mf.get_ovlp(mol)
gmf = scf.GHF(mol)
dm = gmf.get_init_guess()
print dm.shape
dm = dm + np.random.rand(2*norb, 2*norb) / 5
print gmf.kernel(dm0 = dm)
ovlp = mf.get_ovlp(mol)
uc1 = (gmf.mo_coeff[:norb, :norb].T.dot(ovlp).dot(lmo)).T
uc2 = (gmf.mo_coeff[:norb, norb:].T.dot(ovlp).dot(lmo)).T
uc3 = (gmf.mo_coeff[norb:, :norb].T.dot(ovlp).dot(lmo)).T
uc4 = (gmf.mo_coeff[norb:, norb:].T.dot(ovlp).dot(lmo)).T
fileHF = open("ghf.txt", 'w')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(uc1[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(uc2[i,j]))
fileHF.write('\n')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(uc3[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(uc4[i,j]))
fileHF.write('\n')
fileHF.close()
<file_sep>#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <chrono>
#include "primitives.h"
#include "workArray.h"
using namespace std;
using namespace std::chrono;
void initArraySize(vector<int> coeffSize, vector<int> S2size,
vector<int> Ssize) {
Coeffx_3d.dimensions = coeffSize; Coeffy_3d.dimensions = coeffSize; Coeffz_3d.dimensions = coeffSize;
Sx_3d.dimensions = S2size; Sy_3d.dimensions = S2size; Sz_3d.dimensions = S2size;
Sx2_3d.dimensions = S2size; Sy2_3d.dimensions = S2size; Sz2_3d.dimensions = S2size;
Sx_2d.dimensions = Ssize; Sy_2d.dimensions = Ssize; Sz_2d.dimensions = Ssize;
Sx2_2d.dimensions = Ssize; Sy2_2d.dimensions = Ssize; Sz2_2d.dimensions = Ssize;
}
void generateCoefficientMatrix(int LA, int LB, double expA, double expB,
double ABx, double p, tensor& Coeff_3d) {
expaPow[0] = 1.;
for (int i=1; i<= LB; i++)
expaPow[i] = expaPow[i-1] * expA * ABx/p;
expbPow[0] = 1.;
for (int i=1; i<= LA; i++)
expbPow[i] = expbPow[i-1] * expB * ABx/p;
std::fill(Coeff_3d.vals, Coeff_3d.vals+(LA+1)*(LB+1)*(LA+LB+1), 0.0);
//these are the 3d coefficients that take you from xP^{i+j} -> xA^i xB^j
for (int i=0; i<=LA; i++)
for (int j=0; j<=LB; j++) {
for (int m=0; m<=i; m++)
for (int l=0; l<=j; l++) {
//double prefactor = pow(-1, i-m) * nChoosek(i, m) * nChoosek(j, l);
double prefactor = ((i-m)%2 == 0 ? 1. : -1.) * nChoosek(i, m) * nChoosek(j, l);
Coeff_3d(i, j, m+l) += prefactor * expbPow[i-m] * expaPow[j-l];
//Coeff_3d(i, j, m+l) += prefactor * pow(expB * ABx/p, i-m) * pow(expA * ABx/p, j-l);
}
}
}
double calc1DOvlpPeriodicSumB(int LA, double Ax, double expA,
int LB, double Bx, double expB,
int LC, double Cx, double expC,
double expG, int AdditionalDeriv,
double Lx, tensor& Sx_3d, tensor& Sx2_3d,
tensor& powPIOverLx)
{
//THREE CASES
if ( expA > 0.3/Lx/Lx && expB > 0.3/Lx/Lx) { //then explicit sums have to be performed
double p = expA + expB;
double t = expG * p * expC / (expG*p + expG*expC + p*expC);
double mu = expA * expB / (expA + expB);
double beta = 0.0;
for (int nx = 0; nx < 30; nx++) {
{
double Px = (expA * Ax + expB * (Bx+nx*Lx))/(expA + expB);
double ABx = Ax - (Bx + nx * Lx);
double productfactor = exp(-mu * ABx * ABx);
generateCoefficientMatrix(LA, LB, expA, expB, ABx, p, Coeffx_3d);
calc1DOvlpPeriodic(LA+LB, Px, p, LC, Cx, expC, t, 0, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpAPlusExpB, powExpC);
calc1DOvlpPeriodic(LA+LB, Px, p, LC, Cx, expC, 0, 0, Lx, Sx2_2d, &workArray[0], powPIOverLx, powExpAPlusExpB, powExpC);
contract_IJK_IJL_LK( &Sx_3d, &Coeffx_3d, &Sx_2d, productfactor, beta);
contract_IJK_IJL_LK(&Sx2_3d, &Coeffx_3d, &Sx2_2d, productfactor, beta);
}
if (nx != 0)
{
double Px = (expA * Ax + expB * (Bx-nx*Lx))/(expA + expB);
double ABx = Ax - (Bx - nx * Lx);
double productfactor = exp(-mu * ABx * ABx);
generateCoefficientMatrix(LA, LB, expA, expB, ABx, p, Coeffx_3d);
calc1DOvlpPeriodic(LA+LB, Px, p, LC, Cx, expC, t, 0, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpAPlusExpB, powExpC);
calc1DOvlpPeriodic(LA+LB, Px, p, LC, Cx, expC, 0, 0, Lx, Sx2_2d, &workArray[0], powPIOverLx, powExpAPlusExpB, powExpC);
contract_IJK_IJL_LK(&Sx_3d, &Coeffx_3d, &Sx_2d, productfactor, 1.0);
contract_IJK_IJL_LK(&Sx2_3d, &Coeffx_3d, &Sx2_2d, productfactor, 1.0);
}
else
beta = 1.0;
double max = min (abs(Ax - (Bx + (nx+1) * Lx)), abs(Ax - (Bx - (nx+1) * Lx )));
if (exp(-mu*max*max) < 1.e-10) break;
}
}
else if (expB <= 0.3/Lx/Lx) {//then theta function A is just a constant
double t = expG * expA * expC / (expG*expA + expG*expC + expA*expC);
calc1DOvlpPeriodic(LA, Ax, expA, LC, Cx, expC, t, 0, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpA, powExpC);
calc1DOvlpPeriodic(LA, Ax, expA, LC, Cx, expC, 0, 0, Lx, Sx2_2d, &workArray[0], powPIOverLx, powExpA, powExpC);
double Bfactor = sqrt(M_PI/(expB*Lx*Lx) * ((expA+expB)/expA));
for (int j=0; j<= (LB+1)*(LB+2)/2; j++) {
double factor = DerivativeToPolynomial(j, 0) * powExpB(j/2);
for (int i=0; i<= (LA+1)*(LA+2)/2; i++)
for (int k=0; k<= (LC+1)*(LC+2)/2; k++) {
Sx_3d(i,j,k) = Bfactor * factor * Sx_2d(i,k) ;
Sx2_3d(i,j,k) = Bfactor * factor * Sx2_2d(i,k) ;
}
}
}
else if (expA <= 0.3/Lx/Lx) {//then theta function A is just a constant
double t = expG * expB * expC / (expG*expB + expG*expC + expB*expC);
calc1DOvlpPeriodic(LB, Bx, expB, LC, Cx, expC, t, 0, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpB, powExpC);
calc1DOvlpPeriodic(LB, Bx, expB, LC, Cx, expC, 0, 0, Lx, Sx2_2d, &workArray[0], powPIOverLx, powExpB, powExpC);
double Afactor = sqrt( (M_PI/expA/Lx/Lx) * ((expA+expB)/expB) );
for (int i=0; i<= (LA+1)*(LA+2)/2; i++) {
double factor = DerivativeToPolynomial(i, 0) * powExpA(i/2);
for (int j=0; j<= (LB+1)*(LB+2)/2; j++)
for (int k=0; k<= (LC+1)*(LC+2)/2; k++) {
Sx_3d(i,j,k) = Afactor * factor * Sx_2d(j,k) ;
Sx2_3d(i,j,k) = Afactor * factor * Sx2_2d(j,k) ;
}
}
}
}
//calculate primitive cartesian integrals with no A,B, C translations
//assuming periodized coulomb kernel
void calcCoulombIntegralPeriodic_noTranslations(
int LA, double Ax, double Ay, double Az,
double expA, double normA,
int LB, double Bx, double By, double Bz,
double expB, double normB,
int LC, double Cx, double Cy, double Cz,
double expC, double normC,
double Lx, double Ly, double Lz,
tensor& Int3d, Coulomb& coulomb,
bool normalize) {
if (normalize) {
normA *= 1.0/sqrt( doubleFact(2*LA-1)/pow(4*expA, LA))
/ pow(M_PI/2./expA, 0.75);// * sqrt(4* M_PI/ (2*LA+1));
if (LA >=2) normA = normA * sqrt(4* M_PI/ (2*LA+1));
normB *= 1.0/sqrt( doubleFact(2*LB-1)/pow(4*expB, LB))
/ pow(M_PI/2./expB, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LB >=2) normB = normB * sqrt(4 * M_PI / (2*LB+1));
normC *= 1.0/sqrt( doubleFact(2*LC-1)/pow(4*expC, LC))
/ pow(M_PI/2./expC, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LC >=2) normC = normC * sqrt(4 * M_PI / (2*LC+1));
}
double Px = (expA * Ax + expB * Bx)/(expA + expB),
Py = (expA * Ay + expB * By)/(expA + expB),
Pz = (expA * Az + expB * Bz)/(expA + expB);
double p = (expA + expB), ABx = Ax-Bx, ABy = Ay-By, ABz = Az-Bz;
double mu = expA * expB / (expA + expB);
double productfactor = exp(-mu *(ABx*ABx + ABy*ABy + ABz*ABz)) * normA * normB;
initArraySize({LA+1, LB+1, LA+LB+1}, {LA+1, LB+1, LC+1}, {LA+LB+1, LC+1});
generateCoefficientMatrix(LA, LB, expA, expB, ABx, p, Coeffx_3d);
generateCoefficientMatrix(LA, LB, expA, expB, ABy, p, Coeffy_3d);
generateCoefficientMatrix(LA, LB, expA, expB, ABz, p, Coeffz_3d);
powExpAPlusExpB.dimensions = {LA+LB+1}; powExpC.dimensions = {LC+1}; powExpA.dimensions = {LA+1}; powExpB.dimensions = {LB+1};
powPIOverLx.dimensions = {LA+LB+1}; powPIOverLy.dimensions = {LA+LB+1}; powPIOverLz.dimensions = {LA+LB+1};
for (int i=0; i<=LA+LB; i++)
powExpAPlusExpB(i) = pow(1./p, i);
for (int i=0; i<=LA; i++)
powExpA(i) = pow(1./expA, i);
for (int i=0; i<=LB; i++)
powExpB(i) = pow(1./expB, i);
for (int j=0; j<=LC; j++)
powExpC(j) = pow(1./expC, j);
for (int k=0; k<=LA+LB; k++) {
powPIOverLx(k) = pow(M_PI/Lx, k);
powPIOverLy(k) = pow(M_PI/Ly, k);
powPIOverLz(k) = pow(M_PI/Lz, k);
}
int IA0 = (LA)*(LA+1)*(LA+2)/6;
int IB0 = (LB)*(LB+1)*(LB+2)/6;
int IC0 = (LC)*(LC+1)*(LC+2)/6;
double prevt = -1.0;
for (int i=0; i<coulomb.exponents.size(); i++) {
double expG = coulomb.exponents[i], wtG = coulomb.weights[i];
//assume that LA and LB = 0
double t = expG * p * expC / (expG*p + expG*expC + p*expC);
double prefactor = pow(M_PI*M_PI*M_PI/(expG*p*expC), 1.5) * normC / (Lx * Ly * Lz);
if (abs(prevt - t) > 1.e-6) {
calc1DOvlpPeriodic(LA+LB, Px, p, LC, Cx, expC, t, 0, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpAPlusExpB, powExpC);
calc1DOvlpPeriodic(LA+LB, Py, p, LC, Cy, expC, t, 0, Ly, Sy_2d, &workArray[0], powPIOverLy, powExpAPlusExpB, powExpC);
calc1DOvlpPeriodic(LA+LB, Pz, p, LC, Cz, expC, t, 0, Lz, Sz_2d, &workArray[0], powPIOverLz, powExpAPlusExpB, powExpC);
//bkground terms
calc1DOvlpPeriodic(LA+LB, Px, p, LC, Cx, expC, 0, 0, Lx, Sx2_2d, &workArray[0], powPIOverLx, powExpAPlusExpB, powExpC);
calc1DOvlpPeriodic(LA+LB, Py, p, LC, Cy, expC, 0, 0, Ly, Sy2_2d, &workArray[0], powPIOverLy, powExpAPlusExpB, powExpC);
calc1DOvlpPeriodic(LA+LB, Pz, p, LC, Cz, expC, 0, 0, Lz, Sz2_2d, &workArray[0], powPIOverLz, powExpAPlusExpB, powExpC);
}
prevt = t;
contract_IJK_IJL_LK(&Sx_3d, &Coeffx_3d, &Sx_2d);
contract_IJK_IJL_LK(&Sy_3d, &Coeffy_3d, &Sy_2d);
contract_IJK_IJL_LK(&Sz_3d, &Coeffz_3d, &Sz_2d);
contract_IJK_IJL_LK(&Sx2_3d, &Coeffx_3d, &Sx2_2d);
contract_IJK_IJL_LK(&Sy2_3d, &Coeffy_3d, &Sy2_2d);
contract_IJK_IJL_LK(&Sz2_3d, &Coeffz_3d, &Sz2_2d);
for (int a = 0; a< (LA+1)*(LA+2)/2; a++)
for (int b = 0; b< (LB+1)*(LB+2)/2; b++)
for (int c = 0; c< (LC+1)*(LC+2)/2; c++)
{
vector<int>& apow = CartOrder[IA0 + a];
vector<int>& bpow = CartOrder[IB0 + b];
vector<int>& cpow = CartOrder[IC0 + c];
Int3d(a,b,c) += productfactor * prefactor * wtG *
(Sx_3d(apow[0],bpow[0],cpow[0]) * Sy_3d(apow[1],bpow[1],cpow[1]) * Sz_3d(apow[2],bpow[2],cpow[2]) -
Sx2_3d(apow[0],bpow[0],cpow[0]) * Sy2_3d(apow[1],bpow[1],cpow[1]) * Sz2_3d(apow[2],bpow[2],cpow[2]));
}
}
}
//calculate primitive cartesian integrals with no B translations
void calcCoulombIntegralPeriodic_BTranslations(
int LA, double Ax, double Ay, double Az,
double expA, double normA,
int LB, double Bx, double By, double Bz,
double expB, double normB,
int LC, double Cx, double Cy, double Cz,
double expC, double normC,
double Lx, double Ly, double Lz,
tensor& Int3d, Coulomb& coulomb,
bool normalize) {
if (normalize) {
normA *= 1.0/sqrt( doubleFact(2*LA-1)/pow(4*expA, LA))
/ pow(M_PI/2./expA, 0.75);// * sqrt(4* M_PI/ (2*LA+1));
if (LA >=2) normA = normA * sqrt(4* M_PI/ (2*LA+1));
normB *= 1.0/sqrt( doubleFact(2*LB-1)/pow(4*expB, LB))
/ pow(M_PI/2./expB, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LB >=2) normB = normB * sqrt(4 * M_PI / (2*LB+1));
normC *= 1.0/sqrt( doubleFact(2*LC-1)/pow(4*expC, LC))
/ pow(M_PI/2./expC, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LC >=2) normC = normC * sqrt(4 * M_PI / (2*LC+1));
}
powExpAPlusExpB.dimensions = {LA+LB+1}; powExpC.dimensions = {LC+1}; powExpA.dimensions = {LA+1}; powExpB.dimensions = {LB+1};
powPIOverLx.dimensions = {LA+LB+1}; powPIOverLy.dimensions = {LA+LB+1}; powPIOverLz.dimensions = {LA+LB+1};
for (int i=0; i<=LA+LB; i++)
powExpAPlusExpB(i) = pow(1./(expA+expB), i);
for (int j=0; j<=LC; j++)
powExpC(j) = pow(1./expC, j);
for (int j=0; j<=LA; j++)
powExpA(j) = pow(1./expA, j);
for (int j=0; j<=LB; j++)
powExpB(j) = pow(1./expB, j);
for (int k=0; k<=LA+LB; k++) {
powPIOverLx(k) = pow(M_PI/Lx, k);
powPIOverLy(k) = pow(M_PI/Ly, k);
powPIOverLz(k) = pow(M_PI/Lz, k);
}
initArraySize({LA+1, LB+1, LA+LB+1}, {LA+1, LB+1, LC+1}, {LA+LB+1, LC+1});
Sx_3d.setZero(); Sy_3d.setZero(); Sz_3d.setZero();
//cout << (LA+1)*(LA+2)/2<<" "<< (LB+1)*(LB+2)/2<<" "<< (LC+1)*(LC+2)/2<<" "<<(LA+1)*(LA+2)*(LB+1)*(LB+2) * (LC+1)*(LC+2)/8<<" "<<endl;
double prevt = -1.0;
int nterms = 0;
//for (int i=155; i<156; i++) {
for (int i=0; i<coulomb.exponents.size(); i++) {
double expG = coulomb.exponents[i], wtG = coulomb.weights[i];
double p = (expA + expB); //ABx = Ax-Bx, ABy = Ay-By, ABz = Az-Bz;
double mu = expA * expB / (expA + expB);
double t = expG * p * expC / (expG*p + expG*expC + p*expC);
double prefactor = pow(M_PI*M_PI*M_PI/(expG*p*expC), 1.5) * normA * normB * normC / (Lx * Ly * Lz);
if (t < 0.4/Lx/Lx && t < 0.4/Ly/Ly && t < 0.4/Lz/Lz) continue;
//if (abs(prefactor*wtG) < 1.e-10) continue;
if ( abs(prevt - t) > 1.e-6) {
//generate summation over x-traslations
calc1DOvlpPeriodicSumB(LA, Ax, expA, LB, Bx, expB, LC, Cx, expC, expG, 0, Lx, Sx_3d, Sx2_3d, powPIOverLx);
calc1DOvlpPeriodicSumB(LA, Ay, expA, LB, By, expB, LC, Cy, expC, expG, 0, Ly, Sy_3d, Sy2_3d, powPIOverLy);
calc1DOvlpPeriodicSumB(LA, Az, expA, LB, Bz, expB, LC, Cz, expC, expG, 0, Lz, Sz_3d, Sz2_3d, powPIOverLz);
}
if (abs(prefactor * wtG) < 1.e-12) break;
prevt = t;
int IA0 = (LA)*(LA+1)*(LA+2)/6;
int IB0 = (LB)*(LB+1)*(LB+2)/6;
int IC0 = (LC)*(LC+1)*(LC+2)/6;
//double maxInt = 0.0;
for (int a = 0; a< (LA+1)*(LA+2)/2; a++)
for (int b = 0; b< (LB+1)*(LB+2)/2; b++)
for (int c = 0; c< (LC+1)*(LC+2)/2; c++)
{
vector<int>& apow = CartOrder[IA0 + a];
vector<int>& bpow = CartOrder[IB0 + b];
vector<int>& cpow = CartOrder[IC0 + c];
Int3d(a,b,c) += prefactor * wtG *
(Sx_3d (apow[0],bpow[0],cpow[0]) * Sy_3d (apow[1],bpow[1],cpow[1]) * Sz_3d (apow[2],bpow[2],cpow[2]) -
Sx2_3d(apow[0],bpow[0],cpow[0]) * Sy2_3d(apow[1],bpow[1],cpow[1]) * Sz2_3d(apow[2],bpow[2],cpow[2]));
}
nterms++;
//cout << i<<" "<<prefactor<<" "<<wtG<<" "<<prefactor*wtG<<" "<<t<<" "<<Int3d(0,0,0)<<endl;
}
//cout << nterms<<" "<<coulomb.exponents.size()<<endl;
//exit(0);
}
void calcShellIntegral(double* integrals, int sh1, int sh2, int sh3, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
double Lx = Lattice[0], Ly = Lattice[4], Lz = Lattice[8];
int nbas1 = bas[8* sh1 + 3], nbas2 = bas[8*sh2 +3], nbas3 = bas[8*sh3 +3];
int LA = bas[8 * sh1 +1], LB = bas[8 * sh2 +1], LC = bas[8 * sh3 +1];
int nLA = (LA+1)*(LA+2)/2, nLB = (LB+1)*(LB+2)/2, nLC = (LC+1)*(LC+2)/2;
int Dim1 = nbas1 * nLA,
Dim2 = nbas2 * nLB,
Dim3 = nbas3 * nLC;
int stride1 = Dim2 * Dim3;
int stride2 = Dim3;
int stride3 = 1;
teri.dimensions = {nLA, nLB, nLC};
std::fill(integrals, integrals+Dim1*Dim2*Dim3, 0.0);
double scaleLA = LA < 2 ? sqrt( (2*LA+1)/(4*M_PI)) : 1.0;
double scaleLB = LB < 2 ? sqrt( (2*LB+1)/(4*M_PI)) : 1.0;
double scaleLC = LC < 2 ? sqrt( (2*LC+1)/(4*M_PI)) : 1.0;
double scaleLz = scaleLA * scaleLB * scaleLC;
int start1 = bas[8 * sh1 + 5], end1 = bas[8 * sh1 + 6];
int sz1 = end1 - start1;
for (int ia = start1; ia<end1; ia++) {
int atmIndex = bas[8*sh1];
int LA = bas[8 * sh1 +1], pos = atm[6*atmIndex + 1];//20 + 4*bas[8*sh1];
double Ax = env[pos], Ay = env[pos + 1], Az = env[pos + 2];
double expA = env[ ia ];
int start2 = bas[8 * sh2 + 5], end2 = bas[8 * sh2 + 6];
int sz2 = end2 - start2;
for (int ja = start2; ja<end2; ja++) {
int atmIndex = bas[8*sh2];
int LB = bas[8 * sh2 +1], pos = atm[6*atmIndex + 1];//20 + 4*bas[8*sh2];
double Bx = env[pos], By = env[pos + 1], Bz = env[pos + 2];
double expB = env[ ja ];
int start3 = bas[8 * sh3 + 5], end3 = bas[8 * sh3 + 6];
int sz3 = end3 - start3;
for (int ka = start3; ka<end3; ka++) {
int atmIndex = bas[8*sh3];
int LC = bas[8 * sh3 +1], pos = atm[6*atmIndex + 1];
double Cx = env[pos], Cy = env[pos + 1], Cz = env[pos + 2];
double expC = env[ ka ];
teri.setZero();
calcCoulombIntegralPeriodic_BTranslations(
LA, Ax, Ay, Az, expA, 1.0,
LB, Bx, By, Bz, expB, 1.0,
LC, Cx, Cy, Cz, expC, 1.0,
Lx, Ly, Lz, teri, coulomb_14_14_8, false);
//now put teri in the correct location in the integrals
for (int ii = 0; ii<nbas1; ii++)
for (int jj = 0; jj<nbas2; jj++)
for (int kk = 0; kk<nbas3; kk++)
{
double scale = env[bas[8* sh1 +5] + (ii+1)*sz1 + (ia-start1)] *
env[bas[8* sh2 +5] + (jj+1)*sz2 + (ja-start2)] *
env[bas[8* sh3 +5] + (kk+1)*sz3 + (ka-start3)];
for (int i=0; i<nLA; i++)
for (int j=0; j<nLB; j++)
for (int k=0; k<nLC; k++) {
integrals[ (ii * nLA + i)*stride1 +
(jj * nLB + j)*stride2 +
(kk * nLC + k)*stride3 ] += teri(i, j, k) * scale * scaleLz;
}
}
} //ka
} //ja
}//ia
}
void calcIntegral_3c(double* integrals, int* shls, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
int dim = 0;
for (int i=0; i<nbas; i++)
if (ao_loc[i+1] - ao_loc[i] > dim)
dim = ao_loc[i+1] - ao_loc[i];
tensor teri( {dim, dim, dim});
int n1 = ao_loc[shls[1]] - ao_loc[shls[0]],
n2 = ao_loc[shls[3]] - ao_loc[shls[2]],
n3 = ao_loc[shls[5]] - ao_loc[shls[4]];
for(int sh1 = shls[0]; sh1 < shls[1]; sh1++) {
cout << sh1<<" "<<shls[1]<<endl;
for(int sh2 = shls[2]; sh2 <= sh1; sh2++)
//for(int sh2 = shls[2]; sh2 < shls[3]; sh2++)
for(int sh3 = shls[4]; sh3 < shls[5]; sh3++) {
//cout << sh1<<" "<<shls[1]<<" "<<sh2<<" "<<shls[3]<<" "<<sh3<<" "<<shls[5]<<endl;
calcShellIntegral(teri.vals, sh1, sh2, sh3, ao_loc, atm, natm, bas, nbas, env, Lattice);
teri.dimensions = {ao_loc[sh1+1] - ao_loc[sh1],
ao_loc[sh2+1] - ao_loc[sh2],
ao_loc[sh3+1] - ao_loc[sh3]};
for (int i = ao_loc[sh1] - ao_loc[shls[0]]; i < ao_loc[sh1+1] - ao_loc[shls[0]]; i++)
for (int j = ao_loc[sh2] - ao_loc[shls[2]]; j < ao_loc[sh2+1] - ao_loc[shls[2]]; j++)
for (int k = ao_loc[sh3] - ao_loc[shls[4]]; k < ao_loc[sh3+1] - ao_loc[shls[4]]; k++) {
integrals[i*n2*n3 + j*n3 + k] = teri(i - (ao_loc[sh1] - ao_loc[shls[0]]),
j - (ao_loc[sh2] - ao_loc[shls[2]]),
k - (ao_loc[sh3] - ao_loc[shls[4]]));
}
}//sh
}
}
void calcShellNuclearIntegral(double* integrals, int sh1, int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
double Lx = Lattice[0], Ly = Lattice[4], Lz = Lattice[8];
int nbas1 = bas[8* sh1 + 3], nbas2 = bas[8*sh2 +3];
int LA = bas[8 * sh1 +1], LB = bas[8 * sh2 +1];
int nLA = (LA+1)*(LA+2)/2, nLB = (LB+1)*(LB+2)/2;
int Dim1 = nbas1 * nLA,
Dim2 = nbas2 * nLB;
int stride1 = Dim2;
int stride2 = 1;
teri.dimensions = {nLA, nLB, 1};
std::fill(integrals, integrals+Dim1*Dim2, 0.0);
//double scaleLz = sqrt( (2*LA+1) * (2*LB+1))/(4*M_PI);
double scaleLA = LA < 2 ? sqrt( (2*LA+1)/(4*M_PI)) : 1.0;
double scaleLB = LB < 2 ? sqrt( (2*LB+1)/(4*M_PI)) : 1.0;
double scaleLz = scaleLA * scaleLB ;
int start1 = bas[8 * sh1 + 5], end1 = bas[8 * sh1 + 6];
int sz1 = end1 - start1;
for (int ia = start1; ia<end1; ia++) {
int atmIndex = bas[8*sh1];
int LA = bas[8 * sh1 +1], pos = atm[6*atmIndex + 1];//20 + 4*bas[8*sh1];
//int LA = bas[8 * sh1 +1], pos = 20 + 4*bas[8*sh1];
double Ax = env[pos], Ay = env[pos + 1], Az = env[pos + 2];
double expA = env[ ia ];
int start2 = bas[8 * sh2 + 5], end2 = bas[8 * sh2 + 6];
int sz2 = end2 - start2;
for (int ja = start2; ja<end2; ja++) {
int atmIndex = bas[8*sh2];
int LB = bas[8 * sh2 +1], pos = atm[6*atmIndex + 1];//20 + 4*bas[8*sh2];
//int LB = bas[8 * sh2 +1], pos = 20 + 4*bas[8*sh2];
double Bx = env[pos], By = env[pos + 1], Bz = env[pos + 2];
double expB = env[ ja ];
teri.setZero();
for (int ka = 0; ka<natm; ka++) {
//int atmIndex = bas[8*sh3];
int LC = 0, pos = atm[6*ka + 1];
double Cx = env[pos], Cy = env[pos + 1], Cz = env[pos + 2];
double zEta = 1.e11, Z = -atm[6*ka];
//teri(0,0,0) = 0.0;
calcCoulombIntegralPeriodic_BTranslations(
LA, Ax, Ay, Az, expA, 1.0,
LB, Bx, By, Bz, expB, 1.0,
LC, Cx, Cy, Cz, zEta, Z*pow(zEta/M_PI, 1.5), //it uses sqrt(norm)
Lx, Ly, Lz, teri, coulomb_14_14_8, false);
}
//now put teri in the correct location in the integrals
for (int ii = 0; ii<nbas1; ii++)
for (int jj = 0; jj<nbas2; jj++)
{
double scale = env[bas[8* sh1 +5] + (ii+1)*sz1 + (ia-start1)] *
env[bas[8* sh2 +5] + (jj+1)*sz2 + (ja-start2)] ;
for (int i=0; i<nLA; i++)
for (int j=0; j<nLB; j++)
integrals[ (ii * nLA + i)*stride1 +
(jj * nLB + j)*stride2 ] += teri(i, j, 0)*scale * scaleLz;
}
} //ja
}//ia
}
void calcNuclearIntegral(double* integrals, int* shls, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
int dim = 0;
for (int i=0; i<nbas; i++)
if (ao_loc[i+1] - ao_loc[i] > dim)
dim = ao_loc[i+1] - ao_loc[i];
tensor teri( {dim, dim, 1});
int n1 = ao_loc[shls[1]] - ao_loc[shls[0]],
n2 = ao_loc[shls[3]] - ao_loc[shls[2]];
for(int sh1 = shls[0]; sh1 < shls[1]; sh1++)
for(int sh2 = shls[2]; sh2 < shls[3]; sh2++) {
calcShellNuclearIntegral(teri.vals, sh1, sh2, ao_loc, atm, natm, bas, nbas, env, Lattice);
teri.dimensions = {ao_loc[sh1+1] - ao_loc[sh1], ao_loc[sh2+1]-ao_loc[sh2], 1};
for (int i = ao_loc[sh1] - ao_loc[shls[0]]; i < ao_loc[sh1+1] - ao_loc[shls[0]]; i++)
for (int j = ao_loc[sh2] - ao_loc[shls[2]]; j < ao_loc[sh2+1] - ao_loc[shls[2]]; j++) {
int I = i - (ao_loc[sh1] - ao_loc[shls[0]]), J = j - (ao_loc[sh2] - ao_loc[shls[2]]);
integrals[i*n2 + j] = teri(I, J, 0);
}
}//sh2
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SCPT_HEADER_H
#define SCPT_HEADER_H
#include <unordered_map>
#include <iomanip>
#include "Determinants.h"
#include "workingArray.h"
#include <boost/filesystem.hpp>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi.hpp>
#endif
#ifndef SERIAL
#include "mpi.h"
#endif
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
template<typename Wfn>
class SCPT
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & wave;
ar & coeffs;
ar & moEne;
}
public:
Eigen::VectorXd coeffs;
Eigen::VectorXd moEne;
Wfn wave; // reference wavefunction
workingArray morework;
double ovlp_current;
static const int NUM_EXCIT_CLASSES = 9;
// the number of coefficients in each excitation class
int numCoeffsPerClass[NUM_EXCIT_CLASSES];
// the cumulative sum of numCoeffsPerClass
int cumNumCoeffs[NUM_EXCIT_CLASSES];
// the total number of strongly contracted states (including the CASCI space itself)
int numCoeffs;
// a list of the excitation classes being considered stochastically
std::array<bool, NUM_EXCIT_CLASSES> classesUsed = { false };
// a list of the excitation classes being considered deterministically
std::array<bool, NUM_EXCIT_CLASSES> classesUsedDeterm = { false };
// a list of classes for which the perturber norms are calculated deterministically
std::array<bool, NUM_EXCIT_CLASSES> normsDeterm = { false };
std::unordered_map<std::array<int,3>, int, boost::hash<std::array<int,3>> > class_1h2p_ind;
std::unordered_map<std::array<int,3>, int, boost::hash<std::array<int,3>> > class_2h1p_ind;
std::unordered_map<std::array<int,4>, int, boost::hash<std::array<int,4>> > class_2h2p_ind;
// the names of each of the 9 classes
string classNames[NUM_EXCIT_CLASSES] = {"CASCI", "AAAV", "AAVV", "CAAA", "CAAV", "CAVV", "CCAA", "CCAV", "CCVV"};
string classNames2[NUM_EXCIT_CLASSES] = {"CASCI", " V", " VV", " C", " CV", " CVV", " CC", " CCV", "CCVV"};
SCPT();
void createClassIndMap(int& numStates_1h2p, int& numStates_2h1p, int& numStates_2h2p);
typename Wfn::ReferenceType& getRef();
typename Wfn::CorrType& getCorr();
template<typename Walker>
void initWalker(Walker& walk);
template<typename Walker>
void initWalker(Walker& walk, Determinant& d);
//void initWalker(Walker& walk);
void getVariables(Eigen::VectorXd& vars);
void printVariables();
void updateVariables(Eigen::VectorXd& vars);
long getNumVariables();
template<typename Walker>
int coeffsIndex(Walker& walk);
// This perform the inverse of the coeffsIndex function: given the
// index of a perturber, return the external (non-active) orbtials
// involved. This only works for the main perturber types used -
// V, VV, C, CV, CC. These only have one or two external orbitals,
// which this function will return.
void getOrbsFromIndex(const int index, int& i, int& j);
// Take two orbital indices i and j, and convert them to a string.
// This is intended for use with two orbital obtained from the
// getOrbsFromIndex function, which are then to be output to
// pt2_energies files.
string formatOrbString(const int i, const int j);
template<typename Walker>
double getOverlapFactor(int i, int a, const Walker& walk, bool doparity) const;
template<typename Walker>
double getOverlapFactor(int I, int J, int A, int B, const Walker& walk, bool doparity) const;
template<typename Walker>
bool checkWalkerExcitationClass(Walker &walk);
// ham is a sample of the diagonal element of the Dyall ham
template<typename Walker>
void HamAndOvlp(Walker &walk,
double &ovlp, double &locEne, double &ham, double &norm, int coeffsIndex,
workingArray& work, bool fillExcitations=true);
// ham is a sample of the diagonal element of the Dyall ham
template<typename Walker>
void FastHamAndOvlp(Walker &walk, double &ovlp, double &ham, workingArray& work, bool fillExcitations=true);
template<typename Walker>
void HamAndSCNorms(Walker &walk, double &ovlp, double &ham, Eigen::VectorXd &normSamples,
vector<Determinant>& initDets, vector<double>& largestCoeffs,
workingArray& work, bool calcExtraNorms);
template<typename Walker>
void AddSCNormsContrib(Walker &walk, double &ovlp, double &ham, Eigen::VectorXd &normSamples,
vector<Determinant>& initDets, vector<double>& largestCoeffs,
workingArray& work, bool calcExtraNorms, int& ex1, int& ex2,
double& tia, size_t& nExcitationsCASCI);
// this is a version of HamAndSCNorms, optimized for the case where only
// classes AAAV (class 1) and CAAA (class 3) are needed
template<typename Walker>
void HamAndSCNormsCAAA_AAAV(Walker &walk, double &ovlp, double &ham, Eigen::VectorXd &normSamples,
vector<Determinant>& initDets, vector<double>& largestCoeffs,
workingArray& work, bool calcExtraNorms);
template<typename Walker>
double doNEVPT2_CT(Walker& walk);
// Output the header for the "norms" file, which will output the norms of
// the strongly contracted (SC) states, divided by the norm of the CASCI
// state (squared)
double outputNormFileHeader(FILE* out_norms);
// Create directories where the norm files will be stored
void createDirForSCNorms();
// Create directories where the init_dets files will be stored
void createDirForInitDets();
// Create directories where the norm files will be stored
void createDirForNormsBinary();
// Print norms to output files.
// If determClasses is true, only print the norms from classes where the
// norms are being found exactly.
// Otherwise, print the norms calculated stochastically, summed up until
// the current iteration. Also print the current estimate of the the
// CASCI energy, and the residence time.
void printSCNorms(int& iter, double& deltaT_Tot, double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, bool determClasses);
void readStochNorms(double& deltaT_Tot, double& energyCAS_Tot, Eigen::VectorXd& norms_Tot);
void readDetermNorms(Eigen::VectorXd& norms_Tot);
// Print initial determinants to output files
// We only need to print out the occupations in the active spaces
// The occupations of the core and virtual orbitals are determined
// from the label of the SC state, which is fixed by the deterministic
// ordering (the same as used in coeffsIndex).
void printInitDets(vector<Determinant>& initDets, vector<double>& largestCoeffs);
// read determinants in to the initDets array from previously output files
void readInitDets(vector<Determinant>& initDets, vector<double>& largestCoeffs);
// From a given line of an output file, containing only the occupations of
// orbitals within the active space, construct the corresponding determinant
// (with all core obritals occupied, all virtual orbitals unocuppied).
// This is specifically used by for readInitDets
void readDetActive(string& line, Determinant& det, double& coeff);
void printNormDataBinary(vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, double& deltaT_Tot);
void readNormDataBinary(vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, double& deltaT_Tot, bool readDeltaT);
void readNormDataText(vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, double& deltaT_Tot);
template<typename Walker>
double doNEVPT2_CT_Efficient(Walker& walk);
template<typename Walker>
double sampleSCEnergies(Walker& walk, vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, workingArray& work);
template<typename Walker>
void doSCEnergyCTMC(Walker& walk, workingArray& work, double& final_ham, double& var, int& samplingIters);
// Estimate the variance of the weighted mean used to estimate E_l^k
double SCEnergyVar(vector<double>& x, vector<double>& w);
template<typename Walker>
double doSCEnergyCTMCPrint(Walker& walk, workingArray& work, int sampleIter, int nWalk);
// Wrapper function for calling doSCEnergyCTMC, which estimates E_l^k,
// given the appropriate input information, and then to print this info
// to the provded pt2_out file.
// This is designed to be called by sampleAllSCEnergies.
template<typename Walker>
double SCEnergyWrapper(Walker& walk, int iter, FILE * pt2_out, Determinant& det,
double& energyCAS_Tot, double norm, int orbi, int orbj,
bool exactCalc, bool exactRead, double& SCHam, workingArray& work);
// Loop over *all* S_l^k subspaces (for the classes AAAV, AAVV, CAAA,
// CAAV and CCAA) for which the calculated norm is above the threshold,
// and sample E_l^k for each. The final PT2 energy is then output as a
// sum over all of these spaces.
template<typename Walker>
double sampleAllSCEnergies(Walker& walk, vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, workingArray& work);
// Loop over *all* S_l^k subspaces (for the classes AAAV, AAVV, CAAA,
// CAAV and CCAA), and either exactly calculate of read in E_l^k for each.
// The final PT2 energy is then output as a sum over all of these spaces.
//
// The difference between this and sampleAllSCEnergies is that *all*
// S_l^k are considered, even if the norm was calculated as zero, if run
// in write mode, and all E_l^k are then written out. If run in read mode,
// then all E_l^k are read in from this file instead, for quick calculation.
template<typename Walker>
double calcAllSCEnergiesExact(Walker& walk, vector<Determinant>& initDets, vector<double>& largestCoeffs,
double& energyCAS_Tot, Eigen::VectorXd& norms_Tot, workingArray& work);
template<typename Walker>
double doSCEnergyCTMCSync(Walker& walk, int& ind, workingArray& work, string& outputFile);
template<typename Walker>
void doSCEnergyExact(Walker& walk, workingArray& work, double& SCHam, double& SCHamVar, int& samplingIters);
Determinant generateInitDet(int orb1, int orb2);
template<typename Walker>
double compareStochPerturberEnergy(Walker& walk, int orb1, int orb2, double CASEnergy, int nsamples);
template<typename Walker>
double doNEVPT2_Deterministic(Walker& walk);
double get_ccvv_energy();
void readSpinRDM(Eigen::MatrixXd& oneRDM, Eigen::MatrixXd& twoRDM);
void calc_AAVV_NormsFromRDMs(Eigen::MatrixXd& twoRDM, Eigen::VectorXd& norms);
void calc_CAAV_NormsFromRDMs(Eigen::MatrixXd& oneRDM, Eigen::MatrixXd& twoRDM, Eigen::VectorXd& norms);
void calc_CCAA_NormsFromRDMs(Eigen::MatrixXd& oneRDM, Eigen::MatrixXd& twoRDM, Eigen::VectorXd& norms);
string getfileName() const;
void writeWave();
void readWave();
};
// This is a wrapper function which is called during initialization.
// This is where the main NEVPT2 functions are called from.
void initNEVPT_Wrapper();
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef workingArray_HEADER_H
#define workingArray_HEADER_H
#include <vector>
//this is a simple class that just stores the set of
//overlaps and hij matix elements whenever local energy is
//calculated
struct workingArray {
vector<double> ovlpRatio;
vector<size_t> excitation1;
vector<size_t> excitation2;
vector<double> HijElement;
double locNorm; // adding this for multiSlater sampling, this is bad jailbreaking, needs to be changed
int nExcitations;
workingArray(size_t initialSize = 1000000) {
nExcitations = 0;
locNorm = 1.0;
ovlpRatio.resize(initialSize);
excitation1.resize(initialSize);
excitation2.resize(initialSize);
HijElement.resize(initialSize);
}
void incrementSize(size_t size) {
size_t newSize = ovlpRatio.size()+size;
ovlpRatio.resize(newSize);
excitation1.resize(newSize);
excitation2.resize(newSize);
HijElement.resize(newSize);
}
void appendValue(double ovlp, size_t ex1, size_t ex2, double hij) {
int ovlpsize = ovlpRatio.size();
if (ovlpsize <= nExcitations)
incrementSize(1000000);
ovlpRatio[nExcitations] = ovlp;
excitation1[nExcitations] = ex1;
excitation2[nExcitations] = ex2;
HijElement[nExcitations] = hij;
nExcitations++;
}
void setCounterToZero() {
nExcitations = 0;
}
void clear() {
ovlpRatio.clear();
excitation1.clear();
excitation2.clear();
HijElement.clear();
nExcitations = 0;
locNorm = 1.;
}
};
#endif
<file_sep>#ifndef CTMC_HEADER_H
#define CTMC_HEADER_H
#include <Eigen/Dense>
#include <vector>
#include "Determinants.h"
#include "workingArray.h"
#include "statistics.h"
#include "sr.h"
#include "global.h"
#include "evaluateE.h"
#include <iostream>
#include <fstream>
#include <boost/serialization/serialization.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <algorithm>
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace Eigen;
using namespace std;
using namespace boost;
template<typename Wfn, typename Walker>
class ContinuousTime
{
public:
Wfn *w;
Walker *walk;
long numVars;
int norbs, nalpha, nbeta;
workingArray work;
double T, Eloc, ovlp, locNorm;
double S1, S2, oldEnergy, avgNorm; // need to keep track of avgNorm here because getGradient doesn't know about it
double cumT, cumT2;
VectorXd grad_ratio;
int nsample;
Statistics Stats, Stats2, multiEloc; //this is only used to calculate autocorrelation length
Determinant bestDet;
double bestOvlp;
bool multiSlater;
double random()
{
uniform_real_distribution<double> dist(0,1);
return dist(generator);
}
ContinuousTime(Wfn &_w, Walker &_walk, int niter) : w(&_w), walk(&_walk)
{
nsample = min(niter, 200000);
numVars = w->getNumVariables();
norbs = Determinant::norbs;
nalpha = Determinant::nalpha;
nbeta = Determinant::nbeta;
bestDet = walk->getDet();
cumT = 0.0, cumT2 = 0.0, S1 = 0.0, S2 = 0.0, avgNorm = 0.0, oldEnergy = 0.0, bestOvlp = 0.0;
}
void LocalEnergy()
{
Eloc = 0.0, ovlp = 0.0, locNorm = 0.0;
if (schd.debug) {
cout << *walk << endl;
}
w->HamAndOvlp(*walk, ovlp, Eloc, work);
locNorm= work.locNorm * work.locNorm;
if (schd.debug) {
//cout << *walk << endl;
cout << "ham " << Eloc << " locNorm " << locNorm << " ovlp " << ovlp << endl << endl;
}
}
void MakeMove()
{
double cumOvlp = 0.0;
for (int i = 0; i < work.nExcitations; i++)
{
cumOvlp += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumOvlp;
}
if (locNorm < schd.normSampleThreshold) T = 1.0 / cumOvlp;
else T = 0.;
double nextDetRand = random() * cumOvlp;
int nextDet = lower_bound(work.ovlpRatio.begin(), work.ovlpRatio.begin() + work.nExcitations, nextDetRand) - work.ovlpRatio.begin();
cumT += T;
cumT2 += T * T;
multiEloc.push_back(Eloc, locNorm, ovlp, walk->getDet(), T);
walk->updateWalker(w->getRef(), w->getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
}
void UpdateBestDet()
{
if (abs(ovlp) > bestOvlp)
{
bestOvlp = abs(ovlp);
bestDet = walk->getDet();
}
}
void FinishBestDet()
{
if (commrank == 0)
{
char file[50];
sprintf(file, "BestDeterminant.txt");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << bestDet;
if (schd.printLevel > 7) cout << bestDet << endl;
}
}
void UpdateEnergy(double &Energy)
{
oldEnergy = Energy;
double oldNorm = avgNorm;
Energy += T * (Eloc - Energy) / cumT;
avgNorm += T * (locNorm - oldNorm) / cumT;
S1 += T * (Eloc - oldEnergy) * (Eloc - Energy);
S2 += T * (locNorm - oldNorm) * (locNorm - avgNorm);
if (Stats.X.size() < nsample)
{
Stats.push_back(Eloc, T);
Stats2.push_back(locNorm, T);
}
}
void FinishEnergy(double &Energy, double &stddev, double &rk)
{
Stats.Block();
Stats2.Block();
rk = Stats.BlockCorrTime();
double rk2 = Stats2.BlockCorrTime();
S1 /= cumT;
S2 /= cumT;
#ifndef SERIAL
if (commsize < 21) {
MPI_Allreduce(MPI_IN_PLACE, &Energy, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &avgNorm, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &S1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &S2, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &rk, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &rk2, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &cumT, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &cumT2, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
Energy /= commsize;
avgNorm /= commsize;
Energy /= avgNorm;
S1 /= commsize;
S2 /= commsize;
rk /= commsize;
rk2 /= commsize;
cumT /= commsize;
cumT2 /= commsize;
double neff = commsize * (cumT * cumT) / cumT2;
stddev = sqrt(rk * S1 / neff);
}
else {
double energyTotAll[commsize];
double energyProc = Energy / avgNorm;
MPI_Gather(&(energyProc), 1, MPI_DOUBLE, &(energyTotAll), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
Energy *= cumT;
avgNorm *= cumT;
cumT2 = cumT; // this is being done to preserve cumT for the gradient average
MPI_Allreduce(MPI_IN_PLACE, &Energy, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &avgNorm, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &cumT, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
Energy /= cumT;
avgNorm /= cumT;
Energy /= avgNorm;
stddev = 0.;
for (int i = 0; i < commsize; i++) stddev += pow(energyTotAll[i] - Energy, 2);
stddev /= (commsize - 1);
stddev = sqrt(stddev / commsize);
}
#else
double neff = commsize * (cumT * cumT) / cumT2;
stddev = sqrt(rk * S1 / neff);
#endif
if (schd.printLevel > 10) multiEloc.writeSamples(Energy, stddev, avgNorm);
}
void LocalGradient()
{
grad_ratio.setZero(numVars);
w->OverlapWithGradient(*walk, ovlp, grad_ratio);
}
void UpdateGradient(VectorXd &grad, VectorXd &grad_ratio_bar)
{
grad_ratio_bar += T * (grad_ratio * work.locNorm - grad_ratio_bar) / cumT;
grad += T * (grad_ratio * Eloc / work.locNorm - grad) / cumT;
}
// this function is tangled with the finisgenergy function, need to be called in sequence, should be combined
void FinishGradient(VectorXd &grad, VectorXd &grad_ratio_bar, const double &Energy)
{
#ifndef SERIAL
if (commsize < 21) {
MPI_Allreduce(MPI_IN_PLACE, (grad_ratio_bar.data()), grad_ratio_bar.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, (grad.data()), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
grad /= commsize;
grad_ratio_bar /= commsize;
}
else {
grad *= cumT2;
grad_ratio_bar *= cumT2;
MPI_Allreduce(MPI_IN_PLACE, (grad_ratio_bar.data()), grad_ratio_bar.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, (grad.data()), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
grad /= cumT;
grad_ratio_bar /= cumT;
}
#endif
grad = (grad - Energy * grad_ratio_bar);
grad /= avgNorm;
}
void UpdateSR(DirectMetric &S)
{
VectorXd appended(numVars + 1);
appended << 1.0, grad_ratio;
S.Vectors.push_back(appended);
S.T.push_back(T);
}
void FinishSR(const VectorXd &grad, const VectorXd &grad_ratio_bar, VectorXd &H)
{
H.setZero(grad.rows() + 1);
VectorXd appended(grad.rows());
appended = grad_ratio_bar - schd.stepsize * grad;
H << 1.0, appended;
}
};
#endif
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
#include "CxNumpyArray.h"
#include "CxAlgebra.h"
#include "CxMemoryStack.h"
#include "CxPodArray.h"
#include "BlockContract.h"
#include "icpt.h"
#include "CxDiis.h"
#include <fstream>
#include "boost/format.hpp"
#include "E_NEV_aavv.inl"
#include "E_NEV_ccav.inl"
#include "E_NEV_ccvv.inl"
#include "E_NEV_acvv.inl"
#include "E_NEV_ccaa.inl"
#include "E_NEV_caav.inl"
#include "E_LCC_aavv.inl"
#include "E_LCC_acvv.inl"
#include "E_LCC_ccvv.inl"
#include "E_LCC_ccaa.inl"
#include "E_LCC_ccav.inl"
#include "E_LCC_caav.inl"
using ct::TArray;
using ct::FMemoryStack2;
using boost::format;
using namespace std;
void IrPrintMatrixGen(std::ostream &xout, FScalar *pData, unsigned nRows, unsigned iRowSt, unsigned nCols, unsigned iColSt, std::string const &Caption);
FNdArrayView ViewFromNpy(ct::FArrayNpy &A);
void SplitStackmem(ct::FMemoryStack2 *Mem)
{
//now we have to distribute remaining memory equally among different threads
long originalSize = Mem[0].m_Size;
long remainingMem = Mem[0].m_Size - Mem[0].m_Pos;
long memPerThrd = remainingMem/numthrds;
Mem[0].m_Size = Mem[0].m_Pos+memPerThrd;
for (int i=1; i<numthrds; i++) {
Mem[i].m_pData = Mem[i-1].m_pData+Mem[i-1].m_Size;
Mem[i].m_Pos = 0;
Mem[i].m_Size = memPerThrd;
}
Mem[numthrds-1].m_Size += remainingMem%numthrds;
}
void MergeStackmem(ct::FMemoryStack2 *Mem)
{
//put all the memory again in the zeroth thrd
for (int i=1; i<numthrds; i++) {
Mem[0].m_Size += Mem[i].m_Size;
Mem[i].m_pData = 0;
Mem[i].m_Pos = 0;
Mem[i].m_Size = 0;
}
}
namespace srci {
#define NO_RT_LIB
double GetTime() {
#ifdef NO_RT_LIB
timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + 1e-6 * tv.tv_usec;
#else
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
// ^- interesting trivia: CLOCK_MONOTONIC is not guaranteed
// to actually be monotonic.
return ts.tv_sec + 1e-9 * ts.tv_nsec;
#endif // NO_RT_LIB
}
};
FJobData::FJobData()
: WfDecl(FWfDecl()), RefEnergy(0.), ThrTrun(1e-4), ThrDen(1e-6), ThrVar(1e-14), resultOut(""), guessInput(""),
LevelShift(0.), nOrb(0), MaxIt(100), WorkSpaceMb(1024), nMaxDiis(6), MethodClass(METHOD_MinE)
{}
void FJobData::ReadInputFile(char const *pArgFile)
{
// maybe I should use boost program options for this? it can deal with files
// and stuff. But it might be helpful to keep the ci program completely
// dependency free for inclusion in molpro and stuff.
std::ifstream
inpf(pArgFile);
while (inpf.good()) {
// behold the most marvellous elegance of C++ I/O handling.
std::string
Line, ArgName, ArgValue;
std::getline(inpf, Line);
std::stringstream
inp(Line);
inp >> ArgName >> ArgValue;
// ^- this won't work if spaces are in the file name...
if (inpf.eof())
break;
if (!ArgName.empty() and ArgName[0] == '#')
// comment. skip.
continue;
// std::cout << format("arg: '%s' val: '%s'") % ArgName % ArgValue << std::endl;
if (ArgName == "method")
MethodName = ArgValue;
else if (ArgName == "orb-type") {
if (ArgValue == "spatial/MO")
WfDecl.OrbType = ORBTYPE_Spatial;
else if (ArgValue == "spinorb/MO")
WfDecl.OrbType = ORBTYPE_SpinOrb;
else
throw std::runtime_error("orbital type '" + ArgValue + "' not recognized.");
} else if (ArgName == "nelec")
WfDecl.nElec = atoi(ArgValue.c_str());
else if (ArgName == "nact")
WfDecl.nActElec = atoi(ArgValue.c_str());
else if (ArgName == "nactorb")
WfDecl.nActOrb = atoi(ArgValue.c_str());
else if (ArgName == "ms2")
WfDecl.Ms2 = atoi(ArgValue.c_str());
else if (ArgName == "ref-energy")
RefEnergy = atof(ArgValue.c_str());
else if (ArgName == "thr-den")
ThrDen = atof(ArgValue.c_str());
else if (ArgName == "orbitalFile")
orbitalFile = ArgValue;
else if (ArgName == "thr-var")
ThrVar = atof(ArgValue.c_str());
else if (ArgName == "thr-trunc")
ThrTrun = atof(ArgValue.c_str());
else if (ArgName == "load")
guessInput = ArgValue;
else if (ArgName == "save")
resultOut = ArgValue;
else if (ArgName == "shift")
Shift = atof(ArgValue.c_str());
else if (ArgName == "level-shift")
LevelShift = atof(ArgValue.c_str());
else if (ArgName == "max-diis")
nMaxDiis = atof(ArgValue.c_str());
else if (ArgName == "max-iter")
MaxIt = atoi(ArgValue.c_str());
else if (ArgName == "int1e/fock")
ct::ReadNpy(Int1e_Fock, ArgValue);
else if (ArgName == "int1e/coreh")
ct::ReadNpy(Int1e_CoreH, ArgValue);
else if (ArgName == "work-space-mb")
WorkSpaceMb = atoi(ArgValue.c_str());
else
throw std::runtime_error("argument '" + ArgName + "' not recognized.");
}
if (Int1e_Fock.Rank() != 0) {
if (Int1e_Fock.Rank() != 2 || Int1e_Fock.Shape[0] != Int1e_Fock.Shape[1])
throw std::runtime_error("int1e/fock must specify a rank 2 square matrix.");
nOrb = Int1e_Fock.Shape[0];
MakeFockAfterIntegralTrafo = false;
} else {
if (Int1e_CoreH.Rank() != 2 || Int1e_CoreH.Shape[0] != Int1e_CoreH.Shape[1])
throw std::runtime_error("int1e/coreh must specify a rank 2 square matrix.");
nOrb = Int1e_CoreH.Shape[0];
MakeFockAfterIntegralTrafo = false;
}
/*
if (Int2e_4ix.Rank() != 0) {
if (Int2e_3ix.Rank() != 0)
throw std::runtime_error("int2e/3ix and int2e/4x interaction matrix elements cannot both be given.");
if (Int2e_4ix.Rank() != 4 || Int2e_4ix.Shape[0] != Int2e_4ix.Shape[1] ||
Int2e_4ix.Shape[0] != Int2e_4ix.Shape[2] || Int2e_4ix.Shape[0] != Int2e_4ix.Shape[3])
throw std::runtime_error("int2e-4ix must be a rank 4 tensor with equal dimensions.");
if (Int2e_4ix.Shape[0] != nOrb)
throw std::runtime_error("nOrb derived from int2e_4ix not compatible with nOrb derived from Fock matrix.");
// ^- I guess technically we might want to allow not specifying
// int2e_4ix at all.
} else {
if (Int2e_3ix.Rank() == 0)
throw std::runtime_error("either int2e/3ix or int2e/4x interaction matrix elements must be given.");
if (Int2e_4ix.Rank() != 3 || Int2e_4ix.Shape[1] != Int2e_4ix.Shape[2])
throw std::runtime_error("int2e-3ix must be a rank 3 tensor (F|rs) with r,s having equal dimensions.");
if (Int2e_3ix.Shape[1] != nOrb)
throw std::runtime_error("nOrb derived from int2e_3ix not compatible with nOrb derived from Fock matrix.");
}
*/
if (Orbs.Rank() != 0) {
if (Orbs.Rank() != 2 || Orbs.Shape[0] < Orbs.Shape[1])
throw std::runtime_error("Input orbital matrix must have rank 2 and have at least as many orbitals as there are basis functions.");
if (Int1e_Fock.Shape[0] != Orbs.Shape[0])
throw std::runtime_error("nOrb derived from Fock not compatible with number of rows in orbital matrix.");
nOrb = Orbs.Shape[1];
}
std::cout << format("*File '%s' nOrb = %i%s nElec = %i Ms2 = %i iWfSym = %i")
% pArgFile % nOrb % "(R)" % WfDecl.nElec % WfDecl.Ms2 % 0 << std::endl;
// % pArgFile % nOrb % (IntClass == INTCLASS_Spatial? " (R)": " (U)") % nElec % Ms2 % iWfSym << endl;
if (2*nOrb < WfDecl.nElec)
throw std::runtime_error("not enough orbitals for the given number of electrons.");
if ((uint)std::abs(WfDecl.Ms2) > WfDecl.nElec)
throw std::runtime_error("spin projection quantum number Ms2 lies outside of -nElec..+nElec");
if (((uint)std::abs(WfDecl.Ms2) % 2) != (WfDecl.nElec % 2))
throw std::runtime_error("Ms2 and nElec must have same parity.");
}
void FJobContext::Allocate(std::string op, FMemoryStack2 &Mem) {
size_t len = TND(op)->nValues();
double scale = 1.0;
double *data = Mem.AllocN(len, scale);
TND(op)->pData = data;
}
void FJobContext::DeAllocate(std::string op, FMemoryStack2 &Mem) {
Mem.Free(TND(op)->pData);
TND(op)->pData = NULL;
}
void FJobContext::SaveToDisk(std::string file, std::string op) {
FILE *File = fopen(file.c_str(), "wb");
fwrite(TND(op)->pData, sizeof(TND(op)->pData[0]), TND(op)->nValues(), File);
fclose(File);
}
void FJobContext::Run(FMemoryStack2 *Mem)
{
Init(Mem[0]);
InitAmplitudes(Mem[0]);
MakeOverlapAndOrthogonalBasis(Mem);
MakeOrthogonal(std::string("b"), std::string("B")); //b -> B
if (guessInput.compare("") == 0)
MakeOrthogonal(std::string("t"), std::string("T")); //t -> T
FScalar scale = 1.0;
bool
Converged = false,
NoSing = false; // if set, explicitly set all singles amplitudes to zero.
FScalar
Energy = 0, LastEnergy = 0, Var2 = 0, Nrm2 = 0,
tResid = 0, tRest = 0, tRold = 0;
double tStart = srci::GetTime(), tMain = -srci::GetTime();
Copy(*TN("P"), *TN("T")); //P <- T
//Allocate("p", Mem[0]);
BackToNonOrthogonal("p", "P"); //p<- P
TN("Ap")->ClearData(); //Ap clear
ExecEquationSet(Method.EqsRes, m_Tensors, Mem[0]); //Ap = A*p
ExecHandCoded(Mem);
//DeAllocate("p", Mem[0]);
MakeOrthogonal("Ap", "AP"); //Ap -> AP
ct::Add(TN("AP")->pData, TN("P")->pData, Shift, TN("AP")->nValues()); //AP = AP + shift * P
Copy(*TN("R"), *TN("AP")); //R <- AP
ct::Scale(TN("R")->pData, -scale, TN("R")->nValues()); //R = -1.0*R
ct::Add(TN("R")->pData, TN("B")->pData, scale, TN("R")->nValues()); //R = R+B
tRold = ct::Dot(TN("R")->pData, TN("R")->pData, TN("R")->nValues()); //<R|R>
Copy(*TN("P"), *TN("R")); // R = AP
std::cout << format("\n Convergence thresholds: THRDEN = %6.2e THRVAR = %6.2e\n") % ThrDen % ThrVar;
std::cout << "\n ITER. SQ.NORM ENERGY ENERGY CHANGE VAR TIME DIIS" << std::endl;
for (uint iIt = 0; iIt < MaxIt; ++ iIt)
{
//Allocate("p", Mem[0]);
BackToNonOrthogonal("p", "P"); //p <- P
TN("Ap")->ClearData(); // Ap->clear
tResid -= srci::GetTime();
ExecEquationSet(Method.EqsRes, m_Tensors, Mem[0]);
ExecHandCoded(Mem);
//DeAllocate("p", Mem[0]);
tResid += srci::GetTime();
MakeOrthogonal("Ap", "AP"); //Ap -> AP
ct::Add(TN("AP")->pData, TN("P")->pData, Shift, TN("AP")->nValues()); //AP = AP + shift * P
FScalar alpha = tRold / ct::Dot(TN("P")->pData, TN("AP")->pData, TN("P")->nValues()); //<P|AP>
ct::Add(TN("T")->pData, TN("P")->pData, alpha, TN("R")->nValues()); //T = T+alph*P
ct::Add(TN("R")->pData, TN("AP")->pData, -alpha, TN("R")->nValues()); //R = R-alph*AP
tResid = ct::Dot(TN("R")->pData, TN("R")->pData, TN("R")->nValues()); // <R|R>
Nrm2 = ct::Dot(TN("T")->pData, TN("T")->pData, TN("T")->nValues()); // <T|T>
Energy = -ct::Dot(TN("T")->pData, TN("B")->pData, TN("T")->nValues()) // -<T|B> - <T|R>
-ct::Dot(TN("T")->pData, TN("R")->pData, TN("T")->nValues());
std::cout << format("%4i %14.8f %14.8f %14.8f %8.2e%10.2f\n")
% (1+iIt) % Nrm2 % (Energy+RefEnergy) % (Energy-LastEnergy) % tResid
% (srci::GetTime() - tStart) ;
std::cout << std::flush;
tStart = srci::GetTime();
if (tResid < ThrVar) {
Converged = true;
break;
}
ct::Scale(TN("P")->pData, tResid/tRold, TN("P")->nValues()); //P = (rnew/rold)*P
ct::Add(TN("P")->pData, TN("R")->pData, scale, TN("R")->nValues()); //P = P+R
tRold = tResid;
LastEnergy = Energy;
}
if ( !Converged ) {
std::cout << format("\n*WARNING: No convergence for root %i."
" Stopped at NIT: %i DEN: %.2e VAR: %.2e")
% 0 % MaxIt % (Energy - LastEnergy) % Var2 << std::endl;
}
std::cout << "\n";
tMain += srci::GetTime();
tRest = tMain - tResid;
PrintTiming("main loop", tMain);
PrintTiming("residual", tResid);
PrintTiming("rest", tRest);
FScalar c0 = 1./std::sqrt(Nrm2);
std::cout << "\n";
PrintResult("Coefficient of reference function", c0, -1);
PrintResult("Reference energy", RefEnergy, -1);
if (RefEnergy != 0.)
PrintResult("Correlation energy", Energy, -1);
std::cout << "\n";
PrintResult("ENERGY", RefEnergy + Energy, 0);
if (resultOut.compare("") != 0) {
PrintResult("Writing result to "+resultOut, 0, 0);
ct::FShapeNpy outshape = ct::MakeShape(TN("T")->Sizes[0], TN("T")->Sizes[1],TN("T")->Sizes[2],TN("T")->Sizes[3]);
ct::WriteNpy(resultOut, TN("T")->pData, outshape);
}
}
void FJobContext::CleanAmplitudes(std::string const &r_or_t)
{
}
void FJobContext::ExecEquationSet( FEqSet const &Set, std::vector<FSrciTensor>& m_Tensors, FMemoryStack2 &Mem)
{
// std::cout << "! EXEC: " << Set.pDesc << std::endl;
for (FEqInfo const *pEq = Set.pEqs; pEq != Set.pEqs + Set.nEqs; ++ pEq) {
//std::cout << "**** "<<pEq->pCoDecl<<std::endl;
if (pEq->nTerms != 3) {
// throw std::runtime_error("expected input equations to be in binary contraction form. One isn't.");
FNdArrayView
**pTs;
Mem.Alloc(pTs, pEq->nTerms);
for (uint i = 0; i < pEq->nTerms; ++i) {
pTs[i] = &m_Tensors[pEq->iTerms[i]];//TensorById(pEq->iTerms[i]);
if (Method.pTensorDecls[pEq->iTerms[i]].Storage == STORAGE_Disk) {
FillData(pEq->iTerms[i], Mem);
}
if (i != 0 && pTs[i] == pTs[0])
throw std::runtime_error(boost::str(format("contraction %i has overlapping dest and source tensors."
" Tensors may not contribute to contractions involving themselves.") % (pEq - Set.pEqs)));
}
ContractN(pTs, pEq->pCoDecl, pEq->Factor, true, Mem);
Mem.Free(pTs);
} else {
void
*pBaseOfMemory = Mem.Alloc(0);
FNdArrayView
*pD = &m_Tensors[pEq->iTerms[0]],
*pS = &m_Tensors[pEq->iTerms[1]],
*pT = &m_Tensors[pEq->iTerms[2]];//TensorById(pEq->iTerms[i]);
for (int j=0; j<3; j++)
if (Method.pTensorDecls[pEq->iTerms[j]].Storage == STORAGE_Disk) {
FillData(pEq->iTerms[j], Mem);
}
//*pD = TensorById(pEq->iTerms[0]),
//*pS = TensorById(pEq->iTerms[1]),
//*pT = TensorById(pEq->iTerms[2]);
if (pD == pS || pD == pT)
throw std::runtime_error(boost::str(format("contraction %i has overlapping dest and source tensors."
" Tensors may not contribute to contractions involving themselves.") % (pEq - Set.pEqs)));
ContractBinary(*pD, pEq->pCoDecl, *pS, *pT, pEq->Factor, true, Mem);
Mem.Free(pBaseOfMemory);
}
}
};
void FJobContext::ReadMethodFile()
{
if (MethodName == "NEVPT2_AAVV")
NEVPT2_AAVV::GetMethodInfo(Method);
else if (MethodName == "NEVPT2_ACVV")
NEVPT2_ACVV::GetMethodInfo(Method);
else if (MethodName == "NEVPT2_CCAV")
NEVPT2_CCAV::GetMethodInfo(Method);
else if (MethodName == "NEVPT2_CCVV")
NEVPT2_CCVV::GetMethodInfo(Method);
else if (MethodName == "NEVPT2_CCAA")
NEVPT2_CCAA::GetMethodInfo(Method);
else if (MethodName == "NEVPT2_CAAV")
NEVPT2_CAAV::GetMethodInfo(Method);
else if (MethodName == "MRLCC_AAVV")
MRLCC_AAVV::GetMethodInfo(Method);
else if (MethodName == "MRLCC_ACVV")
MRLCC_ACVV::GetMethodInfo(Method);
else if (MethodName == "MRLCC_CCVV")
MRLCC_CCVV::GetMethodInfo(Method);
else if (MethodName == "MRLCC_CCAA")
MRLCC_CCAA::GetMethodInfo(Method);
else if (MethodName == "MRLCC_CCAV")
MRLCC_CCAV::GetMethodInfo(Method);
else if (MethodName == "MRLCC_CAAV")
MRLCC_CAAV::GetMethodInfo(Method);
else
throw std::runtime_error("Method '" + MethodName + "' not recognized.");
}
void FJobContext::Init(ct::FMemoryStack2 &Mem)
{
ReadMethodFile();
std::cout << format(" Performing a %s %s calculation with %s orbitals.\n")
% Method.pSpinClass
% MethodName
% ((WfDecl.OrbType == ORBTYPE_Spatial)? "spatial" : "spin");
InitDomains();
CreateTensors(Mem);
InitAmpResPairs();
}
static void CopyEps(FDomainInfo &Dom, FScalar EpsFactor, ct::FArrayNpy const &Fock)
{
for (uint i = Dom.iBase; i != Dom.iBase + Dom.nSize; ++ i)
Dom.Eps.push_back(EpsFactor * Fock(i,i));
}
void FJobContext::InitDomains()
{
if (WfDecl.OrbType == ORBTYPE_Spatial) {
FDomainInfo
&Ext = m_Domains['e'],
&Act = m_Domains['a'],
&Clo = m_Domains['c'];
Clo.iBase = 0;
Clo.nSize = (WfDecl.nElec-WfDecl.nActElec)/2.;
//CopyEps(Clo, -1., Int1e_Fock);
Act.iBase = Clo.nSize;
Act.nSize = WfDecl.nActOrb;
//CopyEps(Act, -1., Int1e_Fock);
Ext.iBase = Clo.nSize+Act.nSize;
Ext.nSize = nOrb - Ext.iBase;
//CopyEps(Ext, +1., Int1e_Fock);
for (int d=0; d<Method.nDomainDecls; d++) {
FDomainInfo &d1 = m_Domains[Method.pDomainDecls[d].pName[0]];
FDomainInfo &Related = m_Domains[ Method.pDomainDecls[d].pRelatedTo[0]];
d1.iBase = Related.iBase;
d1.nSize = Method.pDomainDecls[d].f(Related.nSize);
}
}
}
void CreateTensorFromShape(FSrciTensor &Out, char const *pDomain, char const *pSymmetry, FDomainInfoMap const &DomainInfo)
{
Out.pData = 0;
FArrayOffset
Stride = 1;
for (char const *p = pDomain; *p != 0; ++ p) {
Out.Sizes.push_back(value(DomainInfo, *p).nSize);
Out.Strides.push_back(Stride);
Stride *= Out.Sizes.back();
}
}
void CopyDomianSubset(FSrciTensor &Out, FSrciTensor const &In, char const *pDomain, FDomainInfoMap &Domains)
{
assert(Out.Rank() == In.Rank());
FNdArrayView
// view into the subset of the input array we are to copy.
InSubset = In;
for (uint i = 0; i < In.Rank(); ++ i){
assert(pDomain[i] != 0);
FDomainInfo const &d = value(Domains, pDomain[i]);
InSubset.pData += InSubset.Strides[i] * d.iBase;
assert(InSubset.Sizes[i] >= d.iBase + d.nSize);
InSubset.Sizes[i] = d.nSize;
assert(InSubset.Sizes[i] == Out.Sizes[i]);
}
assert(pDomain[In.Rank()] == 0);
Copy(Out, InSubset);
}
// make a NdArrayView looking into an ArrayNpy object.
FNdArrayView ViewFromNpy(ct::FArrayNpy &A)
{
FNdArrayView
Out;
Out.pData = &A.Data[0];
for (uint i = 0; i < A.Rank(); ++i){
Out.Strides.push_back(A.Strides[i]);
Out.Sizes.push_back(A.Shape[i]);
}
return Out;
}
void FJobContext::FillData(int i, ct::FMemoryStack2 &Mem) {
FTensorDecl const
&Decl = Method.pTensorDecls[i];
char const
*pIntNames[] = {"f", "k"};
ct::FArrayNpy
*pIntArrays[] = {&Int1e_Fock, &Int1e_CoreH};
uint
nIntTerms = sizeof(pIntNames)/sizeof(pIntNames[0]);
double A = 1.0;
if (Decl.Usage != USAGE_PlaceHolder) {
double* tensorData = Mem.AllocN(m_Tensors[i].nValues(), A);
m_Tensors[i].pData = tensorData;
}
if (Decl.Usage == USAGE_Density) {
uint k;
const char *delta = "delta";
if (0 == strcmp(Decl.pName, delta)) {
m_Tensors[i].ClearData();
for (int i1=0; i1<m_Domains[Decl.pDomain[0]].nSize; i1++)
m_Tensors[i](i1,i1) = 1.0;
}
else if (Decl.pName[0] == 'S') {;}
else {
std::string filename = "int/"+string(Decl.pName)+".npy";
m_Tensors[i].Sizes.clear();
m_Tensors[i].Strides.clear();
ct::ReadNpyData(m_Tensors[i], filename);
}
}
else if (Decl.Usage == USAGE_Hamiltonian) {
if (0 == strcmp(Decl.pName, "W") ){// && 0==strcmp( string(Decl.pDomain).c_str(), "caca") ) {
std::string filename = "int/W:"+string(Decl.pDomain)+".npy";
m_Tensors[i].Sizes.clear();
m_Tensors[i].Strides.clear();
ct::ReadNpyData(m_Tensors[i], filename);
}
else {
uint k;
for (k = 0; k < nIntTerms; ++k)
if (0 == strcmp(Decl.pName, pIntNames[k])) {
CopyDomianSubset(m_Tensors[i], ViewFromNpy(*pIntArrays[k]), Decl.pDomain, m_Domains);
break;
}
if (k == nIntTerms)
throw std::runtime_error("Hamiltonian term '" + std::string(Decl.pName) + "' not recognized.");
}
}
}
void FJobContext::CreateTensors(ct::FMemoryStack2 &Mem)
{
m_Tensors.resize(Method.nTensorDecls);
// create meta-information: shapes & sizes.
size_t
TotalSize = 0;
for (uint i = 0; i != Method.nTensorDecls; ++i) {
FTensorDecl const
&Decl = Method.pTensorDecls[i];
CreateTensorFromShape(m_Tensors[i], Decl.pDomain, Decl.pSymmetry, m_Domains);
if (Decl.Usage != USAGE_PlaceHolder && Decl.Storage != STORAGE_Disk) //placeholders dont have their own data
TotalSize += m_Tensors[i].nValues();
// keep a link in case we need to look up the contents of
// individual tensors.
std::string NameAndDomain = boost::str(format("%s:%s") % Decl.pName % Decl.pDomain);
m_TensorsByNameAndDomain[NameAndDomain] = &m_Tensors[i];
m_TensorsByName[Decl.pName] = &m_Tensors[i];
}
// make actual data array and assign the tensors to their target position.
double A = 1.0;
//m_TensorData = Mem.AllocN(TotalSize, A);
//memset(&m_TensorData[0], 0, TotalSize*sizeof(FScalar));
//size_t
//iDataOff = 0;
for (uint i = 0; i != Method.nTensorDecls; ++i) {
if (Method.pTensorDecls[i].Storage != STORAGE_Disk)
FillData(i, Mem);
}
size_t nSizeVec;// = m_pResEnd - m_pRes;
std::cout << format("\n Size of working set: %12i mb\n"
" Size of Hamiltonian: %12i mb\n"
" Size of CI amplitude vector: %12i mb [%i entries/vec]")
% (TotalSize*sizeof(FScalar)/1048576)
% ((Int1e_Fock.Size() + Int2e_4ix.Size())*sizeof(FScalar)/1048576)
% (nSizeVec*sizeof(FScalar)/1048576)
% (nSizeVec)
<< std::endl;
}
FSrciTensor *FJobContext::TND(std::string const &NameAndDomain)
{
return value(m_TensorsByNameAndDomain, NameAndDomain);
}
FSrciTensor *FJobContext::TN(std::string const &Name)
{
return value(m_TensorsByName, Name);
}
FSrciTensor *FJobContext::TensorById(int iTensorRef) {
if (iTensorRef < 0 || (unsigned)iTensorRef >= m_Tensors.size())
throw std::runtime_error(boost::str(format("referenced tensor id %i does not exist.") % iTensorRef));
return &m_Tensors[(unsigned)iTensorRef];
}
void FJobContext::InitAmpResPairs()
{
for (uint i = 0; i != Method.nTensorDecls; ++ i) {
FTensorDecl const
&iDecl = Method.pTensorDecls[i];
if (iDecl.Usage != USAGE_Residual)
break; // through with the residuals. all should have been assigned by now.
for (uint j = i+1; j != Method.nTensorDecls; ++ j) {
FTensorDecl const
&jDecl = Method.pTensorDecls[j];
if (jDecl.Usage != USAGE_Amplitude)
continue;
if (0 != strcmp(iDecl.pDomain, jDecl.pDomain))
continue;
}
}
}
void FJobContext::DeleteData(ct::FMemoryStack2 &Mem) {
Mem.Free(m_TensorData);
m_Tensors.resize(0);
}
void FJobContext::ClearTensors(size_t UsageFlags)
{
for (uint i = 0; i != Method.nTensorDecls; ++ i) {
FTensorDecl const
&iDecl = Method.pTensorDecls[i];
if ((iDecl.Usage & UsageFlags) == 0)
// not supposed to touch this. Leave it alone.
continue;
// std::cout << "clear:" << UsageFlags << " wiping: iDecl i == " << i << ": " << iDecl.pName << std::endl;
m_Tensors[i].ClearData();
}
}
static void DenomScaleUpdateR(FScalar *pAmp, FScalar *pRes, FArrayOffset *pStride,
FArrayOffset *pSize, FArrayOffset RankLeft, FScalar const **ppEps, FScalar CurEps)
{
// note: this assumes that the strides for pAmp and pRes are equal.
// If we create the tensors ourselves (which we do), they are. But
// in general they might not be.
// if (RankLeft > 0)
// for (FArrayOffset i = 0; i < pSize[0]; ++ i)
// DenomScaleUpdateR(pAmp + i*pStride[0], pRes + i*pStride[0], pStride-1, pSize-1, RankLeft-1, ppEps-1, CurEps + ppEps[0][i]);
// else if (RankLeft == 2)
// for (FArrayOffset j = 0; j < pSize[ 0]; ++ j)
// for (FArrayOffset i = 0; i < pSize[-1]; ++ i) {
// FArrayOffset ij = j*pStride[0] + i*pStride[-1];
// pAmp[ij] -= pRes[ij] / (CurEps + ppEps[0][j] + ppEps[-1][i]);
// }
// // ^- note: this case is technically redundant.
// else
// pAmp[0] -= pRes[0] / CurEps;
if (RankLeft > 0)
for (FArrayOffset i = 0; i < pSize[0]; ++ i)
DenomScaleUpdateR(pAmp + i*pStride[0], pRes + i*pStride[0], pStride-1, pSize-1, RankLeft-1, ppEps-1, CurEps + ppEps[0][i]);
else if (RankLeft == 2)
for (FArrayOffset j = 0; j < pSize[ 0]; ++ j)
for (FArrayOffset i = 0; i < pSize[-1]; ++ i) {
pRes[j*pStride[0] + i*pStride[-1]] /= (CurEps + ppEps[0][j] + ppEps[-1][i]);
}
// ^- note: this case is technically redundant.
else
pRes[0] /= CurEps;
}
void FJobContext::PrintTiming(char const *p, FScalar t)
{
std::cout << format(" Time for %-35s%10.2f sec")
% (std::string(p) + ":") % t << std::endl;
}
void FJobContext::PrintTimingT0(char const *p, FScalar t0)
{
PrintTiming(p, srci::GetTime() - t0);
}
void FJobContext::PrintResult(std::string const &s, FScalar v, int iState, char const *pAnnotation)
{
std::stringstream
Caption;
if ( iState >= 0 ) {
Caption << format("!%s STATE %i %s") % MethodName % (iState + 1) % s;
} else {
Caption << " " + s;
}
// std::cout << format("%-23s%20.14f") % Caption.str() % v << std::endl;
std::cout << format("%-35s%20.14f") % Caption.str() % v;
if (pAnnotation)
std::cout << " " << pAnnotation;
std::cout << std::endl;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "Determinants.h"
#include "input.h"
#include "integral.h"
#include "excitGen.h"
heatBathFCIQMC::heatBathFCIQMC(int norbs, const twoInt& I2) {
createArrays(norbs, I2);
}
// Set up arrays used by the heat bath excitation generator
void heatBathFCIQMC::createArrays(int norbs, const twoInt& I2) {
int nSpinOrbs = 2*norbs;
// Size of the D_pq array
int size_1 = nSpinOrbs*(nSpinOrbs-1)/2;
// Size of the P_same_r_pq array
int size_2 = norbs * norbs*(norbs-1)/2;
// Size of the P_opp_r_pq array
int size_3 = pow(norbs,3);
// Size of the P_same_s_pqr array
int size_4 = pow(norbs,2) * norbs*(norbs-1)/2;
// Size of the P_opp_s_pqr array
int size_5 = pow(norbs,4);
D_pq.resize(size_1, 0.0);
S_p.resize(nSpinOrbs, 0.0);
P_same_r_pq.resize(size_2, 0.0);
P_opp_r_pq.resize(size_3, 0.0);
P_same_r_pq_cum.resize(size_2, 0.0);
P_opp_r_pq_cum.resize(size_3, 0.0);
P_same_s_pqr.resize(size_4, 0.0);
P_opp_s_pqr.resize(size_5, 0.0);
P_same_s_pqr_cum.resize(size_4, 0.0);
P_opp_s_pqr_cum.resize(size_5, 0.0);
H_tot_same.resize(size_2, 0.0);
H_tot_opp.resize(size_3, 0.0);
// Set up D_pq
for (int p=1; p<nSpinOrbs; p++) {
for (int q=0; q<p; q++) {
int ind = p*(p-1)/2 + q;
D_pq.at(ind) = 0.0;
for (int r=0; r<nSpinOrbs; r++) {
if (r != p && r != q) {
for (int s=0; s<nSpinOrbs; s++) {
if (r != s && s != p && s != q) {
D_pq.at(ind) += fabs( I2(r, p, s, q) - I2(r, q, s, p) );
}
}
}
}
}
}
// Set up S_p
for (int p=0; p<nSpinOrbs; p++) {
S_p.at(p) = 0.0;
for (int q=0; q<nSpinOrbs; q++) {
if (p == q) continue;
int ind = triInd(p,q);
S_p.at(p) += D_pq.at(ind);
}
}
// Set up P_same_r_pq
for (int p=1; p<norbs; p++) {
for (int q=0; q<p; q++) {
int ind_pq = p*(p-1)/2 + q;
double tot = 0.0;
for (int r=0; r<norbs; r++) {
int ind = norbs*ind_pq + r;
P_same_r_pq.at(ind) = 0.0;
for (int s=0; s<norbs; s++) {
if (r == s) continue;
if (r != p && s != q && r != q && s != p) {
P_same_r_pq.at(ind) += fabs( I2(2*r, 2*p, 2*s, 2*q) - I2(2*r, 2*q, 2*s, 2*p) );
}
} // Loop over s
tot += P_same_r_pq.at(ind);
} // Loop over r
// Normalize probabilities
if (abs(tot) > 1.e-15) {
for (int r=0; r<norbs; r++) {
int ind = norbs*ind_pq + r;
P_same_r_pq.at(ind) /= tot;
}
}
} // Loop over q
} // Loop over p
// Set up the cumulative arrays for P_same_r_pq
for (int p=1; p<norbs; p++) {
for (int q=0; q<p; q++) {
int ind_pq = p*(p-1)/2 + q;
double tot = 0.0;
for (int r=0; r<norbs; r++) {
int ind = norbs*ind_pq + r;
tot += P_same_r_pq.at(ind);
P_same_r_pq_cum.at(ind) = tot;
} // Loop over r
} // Loop over q
} // Loop over p
// Set up P_opp_r_pq
for (int p=0; p<norbs; p++) {
for (int q=0; q<norbs; q++) {
int ind_pq = p*norbs + q;
double tot = 0.0;
for (int r=0; r<norbs; r++) {
int ind = norbs*ind_pq + r;
P_opp_r_pq.at(ind) = 0.0;
for (int s=0; s<norbs; s++) {
if (r != p && s != q) {
P_opp_r_pq.at(ind) += fabs( I2(2*r, 2*p, 2*s+1, 2*q+1) );
}
} // Loop over s
tot += P_opp_r_pq.at(ind);
} // Loop over r
// Normalize probabilities
if (abs(tot) > 1.e-15) {
for (int r=0; r<norbs; r++) {
int ind = norbs*ind_pq + r;
P_opp_r_pq.at(ind) /= tot;
}
}
} // Loop over q
} // Loop over p
// Set up the cumulative arrays for P_opp_r_pq
for (int p=0; p<norbs; p++) {
for (int q=0; q<norbs; q++) {
int ind_pq = p*norbs + q;
double tot = 0.0;
for (int r=0; r<norbs; r++) {
int ind = norbs*ind_pq + r;
tot += P_opp_r_pq.at(ind);
P_opp_r_pq_cum.at(ind) = tot;
} // Loop over r
} // Loop over q
} // Loop over p
// Set up P_same_s_pqr
for (int p=1; p<norbs; p++) {
for (int q=0; q<p; q++) {
int ind_pq = p*(p-1)/2 + q;
for (int r=0; r<norbs; r++) {
double tot_sum = 0.0;
for (int s=0; s<norbs; s++) {
if (r == s) continue;
int ind = pow(norbs,2) * ind_pq + norbs*r + s;
if (r != p && s != q && r != q && s != p) {
P_same_s_pqr.at(ind) = fabs( I2(2*r, 2*p, 2*s, 2*q) - I2(2*r, 2*q, 2*s, 2*p) );
tot_sum += fabs( I2(2*r, 2*p, 2*s, 2*q) - I2(2*r, 2*q, 2*s, 2*p) );
}
} // Loop over s
// Normalize probability
if (abs(tot_sum) > 1.e-15) {
for (int s=0; s<norbs; s++) {
int ind = pow(norbs,2) * ind_pq + norbs*r + s;
P_same_s_pqr.at(ind) /= tot_sum;
}
}
int ind_tot = norbs*ind_pq + r;
H_tot_same.at(ind_tot) = tot_sum;
} // Loop over r
} // Loop over q
} // Loop over p
// Set up the cumulative arrays for P_same_s_pqr
for (int p=1; p<norbs; p++) {
for (int q=0; q<p; q++) {
int ind_pq = p*(p-1)/2 + q;
for (int r=0; r<norbs; r++) {
double tot = 0.0;
for (int s=0; s<norbs; s++) {
int ind = pow(norbs,2) * ind_pq + norbs*r + s;
tot += P_same_s_pqr.at(ind);
P_same_s_pqr_cum.at(ind) = tot;
}
} // Loop over r
} // Loop over q
} // Loop over p
// Set up P_opp_s_pqr
for (int p=0; p<norbs; p++) {
for (int q=0; q<norbs; q++) {
int ind_pq = p*norbs + q;
for (int r=0; r<norbs; r++) {
double tot_sum = 0.0;
for (int s=0; s<norbs; s++) {
int ind = pow(norbs,2) * ind_pq + norbs*r + s;
if (r != p && s != q) {
P_opp_s_pqr.at(ind) = fabs( I2(2*r, 2*p, 2*s+1, 2*q+1) );
tot_sum += fabs( I2(2*r, 2*p, 2*s+1, 2*q+1) );
}
} // Loop over s
// Normalize probability
if (abs(tot_sum) > 1.e-15) {
for (int s=0; s<norbs; s++) {
int ind = pow(norbs,2) * ind_pq + norbs*r + s;
P_opp_s_pqr.at(ind) /= tot_sum;
}
}
int ind_tot = norbs*ind_pq + r;
H_tot_opp.at(ind_tot) = tot_sum;
} // Loop over r
} // Loop over q
} // Loop over p
// Set up the cumulative arrays for P_opp_s_pqr
for (int p=0; p<norbs; p++) {
for (int q=0; q<norbs; q++) {
int ind_pq = p*norbs + q;
for (int r=0; r<norbs; r++) {
double tot = 0.0;
for (int s=0; s<norbs; s++) {
int ind = pow(norbs,2) * ind_pq + norbs*r + s;
tot += P_opp_s_pqr.at(ind);
P_opp_s_pqr_cum.at(ind) = tot;
}
} // Loop over r
} // Loop over q
} // Loop over p
} // End of createArrays
// Wrapper function to call the appropriate excitation generator
void generateExcitation(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2, const Determinant& parentDet,
const int nel, Determinant& childDet, Determinant& childDet2, double& pGen, double& pGen2,
int& ex1, int& ex2)
{
if (schd.uniformExGen || schd.heatBathUniformSingExGen) {
generateExcitationSingDoub(hb, I1, I2, parentDet, nel, childDet, childDet2, pGen, pGen2, ex1, ex2);
} else if (schd.heatBathExGen) {
generateExcitHB(hb, I1, I2, parentDet, nel, childDet, childDet2, pGen, pGen2, ex1, ex2, true);
}
}
// Generate a random single or double excitation, and also return the
// probability that it was generated. A single excitation is returned using
// childDet and pgen. A double excitation is returned using chilDet2 and pGen2.
void generateExcitationSingDoub(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2,
const Determinant& parentDet, const int nel, Determinant& childDet,
Determinant& childDet2, double& pgen, double& pgen2,
int& ex1, int& ex2)
{
double pSingle = 0.05;
double pgen_ia, pgen_ijab;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
if (random() < pSingle) {
generateSingleExcit(parentDet, childDet, pgen_ia, ex1);
pgen = pSingle * pgen_ia;
// No double excitation is generated here:
pgen2 = 0.0;
ex2 = 0;
} else {
if (schd.uniformExGen) {
generateDoubleExcit(parentDet, childDet2, pgen_ijab, ex1, ex2);
} else if (schd.heatBathUniformSingExGen) {
// Pass in attemptSingleExcit = false to indicate that a double
// excitation must be generated. pgen will return as 0.
generateExcitHB(hb, I1, I2, parentDet, nel, childDet, childDet2, pgen, pgen_ijab, ex1, ex2, false);
}
pgen2 = (1.0 - pSingle) * pgen_ijab;
// No single excitation is generated here:
pgen = 0.0;
}
}
// Generate a random single excitation, and also return the probability that
// it was generated
void generateSingleExcit(const Determinant& parentDet, Determinant& childDet, double& pgen_ia, int& ex1)
{
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
vector<int> AlphaOpen;
vector<int> AlphaClosed;
vector<int> BetaOpen;
vector<int> BetaClosed;
parentDet.getOpenClosedAlphaBeta(AlphaOpen, AlphaClosed, BetaOpen, BetaClosed);
childDet = parentDet;
int nalpha = AlphaClosed.size();
int nbeta = BetaClosed.size();
int norbs = Determinant::norbs;
// Pick a random occupied orbital
int i = floor(random() * (nalpha + nbeta));
double pgen_i = 1.0/(nalpha + nbeta);
// Pick an unoccupied orbital
if (i < nalpha) // i is alpha
{
int a = floor(random() * (norbs - nalpha));
int I = AlphaClosed[i];
int A = AlphaOpen[a];
childDet.setoccA(I, false);
childDet.setoccA(A, true);
pgen_ia = pgen_i / (norbs - nalpha);
// for alpha, 2*I and 2*A are the spin orbital labels
ex1 = (2*I)*2*norbs + (2*A);
}
else // i is beta
{
i = i - nalpha;
int a = floor( random() * (norbs - nbeta));
int I = BetaClosed[i];
int A = BetaOpen[a];
childDet.setoccB(I, false);
childDet.setoccB(A, true);
pgen_ia = pgen_i / (norbs - nbeta);
// for beta, 2*I+1 and 2*A+1 are the spin orbital labels
ex1 = (2*I+1)*2*norbs + (2*A+1);
}
}
// Generate a random double excitation, and also return the probability that
// it was generated
void generateDoubleExcit(const Determinant& parentDet, Determinant& childDet, double& pgen_ijab,
int& ex1, int& ex2)
{
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
vector<int> AlphaOpen;
vector<int> AlphaClosed;
vector<int> BetaOpen;
vector<int> BetaClosed;
int i, j, a, b, I, J, A, B;
parentDet.getOpenClosedAlphaBeta(AlphaOpen, AlphaClosed, BetaOpen, BetaClosed);
childDet = parentDet;
int nalpha = AlphaClosed.size();
int nbeta = BetaClosed.size();
int norbs = Determinant::norbs;
int nel = nalpha + nbeta;
// Pick a combined ij index
int ij = floor( random() * (nel*(nel-1))/2 ) + 1;
// The probability of having picked this pair
double pgen_ij = 2.0 / (nel * (nel-1));
// Use triangular indexing scheme to obtain (i,j), with j>i
j = floor(1.5 + sqrt(2*ij - 1.75)) - 1;
i = ij - (j * (j - 1))/2 - 1;
bool iAlpha = i < nalpha;
bool jAlpha = j < nalpha;
bool sameSpin = iAlpha == jAlpha;
// Pick a and b
if (sameSpin) {
int nvirt;
if (iAlpha)
{
nvirt = norbs - nalpha;
// Pick a combined ab index
int ab = floor( random() * (nvirt*(nvirt-1))/2 ) + 1;
// Use triangular indexing scheme to obtain (a,b), with b>a
b = floor(1.5 + sqrt(2*ab - 1.75)) - 1;
a = ab - (b * (b - 1))/2 - 1;
I = AlphaClosed[i];
J = AlphaClosed[j];
A = AlphaOpen[a];
B = AlphaOpen[b];
}
else
{
i = i - nalpha;
j = j - nalpha;
nvirt = norbs - nbeta;
// Pick a combined ab index
int ab = floor( random() * (nvirt * (nvirt-1))/2 ) + 1;
// Use triangular indexing scheme to obtain (a,b), with b>a
b = floor(1.5 + sqrt(2*ab - 1.75)) - 1;
a = ab - (b * (b - 1))/2 - 1;
I = BetaClosed[i];
J = BetaClosed[j];
A = BetaOpen[a];
B = BetaOpen[b];
}
pgen_ijab = pgen_ij * 2.0 / (nvirt * (nvirt-1));
}
else
{ // Opposite spin
if (iAlpha) {
a = floor(random() * (norbs - nalpha));
I = AlphaClosed[i];
A = AlphaOpen[a];
j = j - nalpha;
b = floor( random() * (norbs - nbeta));
J = BetaClosed[j];
B = BetaOpen[b];
}
else
{
i = i - nalpha;
a = floor( random() * (norbs - nbeta));
I = BetaClosed[i];
A = BetaOpen[a];
b = floor(random() * (norbs - nalpha));
J = AlphaClosed[j];
B = AlphaOpen[b];
}
pgen_ijab = pgen_ij / ( (norbs - nalpha) * (norbs - nbeta) );
}
if (iAlpha) {
childDet.setoccA(I, false);
childDet.setoccA(A, true);
// for alpha, 2*I and 2*A are the spin orbital labels
ex1 = (2*I)*2*norbs + (2*A);
} else {
childDet.setoccB(I, false);
childDet.setoccB(A, true);
// for beta, 2*I+1 and 2*A+1 are the spin orbital labels
ex1 = (2*I+1)*2*norbs + (2*A+1);
}
if (jAlpha) {
childDet.setoccA(J, false);
childDet.setoccA(B, true);
// for alpha, 2*J and 2*B are the spin orbital labels
ex2 = (2*J)*2*norbs + (2*B);
} else {
childDet.setoccB(J, false);
childDet.setoccB(B, true);
// for beta, 2*J+1 and 2*B+1 are the spin orbital labels
ex2 = (2*J+1)*2*norbs + (2*B+1);
}
}
// Pick the 'r' orbital when using the heat bath excitation generator.
// This is the first unoccupied orbital, after both of the occupied orbitals
// (p and q) have been picked. Also, calculate a return the value H_tot_pqr,
// which is used to decide whether to generate a single or double excitation.
// This function also returns the probability that r was picked, given p and
// q were picked already, which is rProb.
void pickROrbitalHB(const heatBathFCIQMC& hb, const int norbs, const int p, const int q, int& r,
double& rProb, double& H_tot_pqr)
{
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
bool sameSpin = (p%2 == q%2);
int ind, ind_pq, rSpatial;
int pSpatial = p/2, qSpatial = q/2;
// Pick a spin-orbital r from P(r|pq), such that r and p have the same spin
if (sameSpin) {
ind_pq = triInd(pSpatial, qSpatial);
// The first index for pair (p,q)
int ind_pq_low = ind_pq*norbs;
// The last index for pair (p,q)
int ind_pq_high = ind_pq_low + norbs - 1;
double rRand = random();
rSpatial = std::lower_bound((hb.P_same_r_pq_cum.begin() + ind_pq_low),
(hb.P_same_r_pq_cum.begin() + ind_pq_high), rRand)
- hb.P_same_r_pq_cum.begin() - ind_pq_low;
// The probability that this electron was chosen
ind = norbs*ind_pq + rSpatial;
rProb = hb.P_same_r_pq.at(ind);
// For choosing single excitation
H_tot_pqr = hb.H_tot_same.at(ind);
} else {
ind_pq = pSpatial*norbs + qSpatial;
// The first index for pair (p,q)
int ind_pq_low = ind_pq*norbs;
// The last index for pair (p,q)
int ind_pq_high = ind_pq_low + norbs - 1;
double rRand = random();
rSpatial = std::lower_bound((hb.P_opp_r_pq_cum.begin() + ind_pq_low),
(hb.P_opp_r_pq_cum.begin() + ind_pq_high), rRand)
- hb.P_opp_r_pq_cum.begin() - ind_pq_low;
// The probability that this electron was chosen
ind = norbs*ind_pq + rSpatial;
rProb = hb.P_opp_r_pq.at(ind);
// For choosing single excitation
H_tot_pqr = hb.H_tot_opp.at(ind);
}
// Get the spin orbital index (r and p have the same spin)
r = 2*rSpatial + p%2;
}
// Pick the 's' orbital when using the heat bath excitation generator.
// This is the second unoccupied orbital, after both of the occupied orbitals
// (p and q) and the first unoccupied orbital (r) have been picked.
// This function also returns the probability that s was picked, given p, q
// and r were picked already, which is sProb.
void pickSOrbitalHB(const heatBathFCIQMC& hb, const int norbs, const int p, const int q, const int r,
int& s, double& sProb)
{
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
int ind, ind_pq, sSpatial;
bool sameSpin = (p%2 == q%2);
int pSpatial = p/2, qSpatial = q/2, rSpatial = r/2;
// Pick a spin-orbital r from P(r|pq), such that r and p have the same spin
if (sameSpin) {
ind_pq = triInd(pSpatial, qSpatial);
// The first index for triplet (p,q,r)
int ind_pqr_low = pow(norbs,2) * ind_pq + norbs*rSpatial;
// The last index for triplet (p,q,r)
int ind_pqr_high = ind_pqr_low + norbs - 1;
double sRand = random();
sSpatial = std::lower_bound((hb.P_same_s_pqr_cum.begin() + ind_pqr_low),
(hb.P_same_s_pqr_cum.begin() + ind_pqr_high), sRand)
- hb.P_same_s_pqr_cum.begin() - ind_pqr_low;
// The probability that this electron was chosen
ind = pow(norbs,2) * ind_pq + norbs*rSpatial + sSpatial;
sProb = hb.P_same_s_pqr.at(ind);
} else {
ind_pq = pSpatial*norbs + qSpatial;
// The first index for triplet (p,q,r)
int ind_pqr_low = pow(norbs,2) * ind_pq + norbs*rSpatial;
// The last index for triplet (p,q,r)
int ind_pqr_high = ind_pqr_low + norbs - 1;
double sRand = random();
sSpatial = std::lower_bound((hb.P_opp_s_pqr_cum.begin() + ind_pqr_low),
(hb.P_opp_s_pqr_cum.begin() + ind_pqr_high), sRand)
- hb.P_opp_s_pqr_cum.begin() - ind_pqr_low;
// The probability that this electron was chosen
ind = pow(norbs,2) * ind_pq + norbs*rSpatial + sSpatial;
sProb = hb.P_opp_s_pqr.at(ind);
}
// Get the spin orbital index (s and q have the same spin)
s = 2*sSpatial + q%2;
}
// Calculate the probability of choosing the excitation p to r, where p and r
// are both spin-orbital labels. pProb is the probability that p is chosen as
// the first electron. hSingAbs is the absolute value of the the Hamiltonian
// element between the original and singly excited determinants.
double calcSinglesProb(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2, const int norbs,
const vector<int>& closed, const double pProb, const double D_pq_tot,
const double hSingAbs, const int p, const int r)
{
int nel = closed.size();
int pSpatial = p/2, rSpatial = r/2;
double pGen = 0.0;
// Need to loop over all possible orbitals q that could have been chosen
// as the second electron
for (int q=0; q<nel; q++) {
int qOrb = closed.at(q);
int qSpatial = qOrb/2;
if (qOrb != p) {
int ind = triInd(p, qOrb);
double qProb = hb.D_pq.at(ind) / D_pq_tot;
double rProb, H_tot_pqr;
if (p%2 == qOrb%2) {
// Same spin
int ind_pq = triInd(pSpatial, qSpatial);
int ind_pqr = ind_pq*norbs + rSpatial;
rProb = hb.P_same_r_pq.at(ind_pqr);
H_tot_pqr = hb.H_tot_same.at(ind_pqr);
} else {
// Opposite spin
int ind_pq = pSpatial*norbs + qSpatial;
int ind_pqr = ind_pq*norbs + rSpatial;
rProb = hb.P_opp_r_pq.at(ind_pqr);
H_tot_pqr = hb.H_tot_opp.at(ind_pqr);
}
// The probability of generating a single excitation, rather than a
// double excitation
double singProb;
if (hSingAbs < H_tot_pqr) {
singProb = hSingAbs / ( H_tot_pqr + hSingAbs );
} else {
// If hSingAbs >= Htot_pqr, always attempt to generate both a
// single and double excitation
singProb = 1.0;
}
pGen += pProb * qProb * rProb * singProb;
}
}
return pGen;
}
// This function returns the probability of choosing a double rather than
// a single excitation, given that orbitals p and q have been chosen to
// excite from, and orbital r has been chosen to excite to
double calcProbDouble(const Determinant& parentDet, const oneInt& I1, const twoInt& I2,
const double H_tot_pqr, const int p, const int r) {
double hSing = parentDet.Hij_1Excite(p, r, I1, I2);
double hSingAbs = abs(hSing);
double doubleProb;
if (hSingAbs < H_tot_pqr) {
doubleProb = 1.0 - hSingAbs / ( H_tot_pqr + hSingAbs );
} else {
doubleProb = 1.0;
}
return doubleProb;
}
// Calculate and return the probabilities of selecting the final two orbitals
// (labelled r and s in our convention). These are the two unoccupied orbitals.
// Also, return the probability of choosing a double, in the case that p, q, r
// are the first three orbitals chosen. This is only calculated if calcDoubleProb
// is true.
void calcProbsForRAndS(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2, const int norbs,
const Determinant& parentDet, const int p, const int q, const int r, const int s,
double& rProb, double& sProb, double& doubleProb, const bool calcDoubleProb)
{
if (r%2 == p%2) {
double H_tot;
int pSpatial = p/2, qSpatial = q/2;
int rSpatial = r/2, sSpatial = s/2;
// Same spin for p and q:
if (p%2 == q%2) {
int ind1 = triInd(pSpatial, qSpatial);
int ind2 = norbs * ind1 + rSpatial;
// Probability of picking r first
rProb = hb.P_same_r_pq.at(ind2);
H_tot = hb.H_tot_same.at(ind2);
int ind3 = pow(norbs,2)*ind1 + norbs*rSpatial + sSpatial;
// Probability of picking s second, after picking r first
sProb = hb.P_same_s_pqr.at(ind3);
// Opposite spin for p and q:
} else {
int ind1 = pSpatial*norbs + qSpatial;
int ind2 = norbs * ind1 + rSpatial;
rProb = hb.P_opp_r_pq.at(ind2);
H_tot = hb.H_tot_opp.at(ind2);
int ind3 = pow(norbs,2)*ind1 + norbs*rSpatial + sSpatial;
sProb = hb.P_opp_s_pqr.at(ind3);
}
// The probability of generating a double, rather than a single,
// if s had been chosen first instead of r
if (calcDoubleProb) {
doubleProb = calcProbDouble(parentDet, I1, I2, H_tot, p, r);
}
} else {
rProb = 0.0;
sProb = 0.0;
doubleProb = 0.0;
}
}
// Use the heat bath algorithm to generate both the single and
// double excitations
void generateExcitHB(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2, const Determinant& parentDet,
const int nel, Determinant& childDet, Determinant& childDet2, double& pGen, double& pGen2,
int& ex1, int& ex2, const bool attemptSingleExcit)
{
int norbs = Determinant::norbs, ind;
int nSpinOrbs = 2*norbs;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1), std::ref(generator));
childDet = parentDet;
childDet2 = parentDet;
vector<int> closed(nel, 0);
parentDet.getClosedAllocated(closed);
// Pick the first electron with probability P(p) = S_p / sum_p' S_p'
// For this, we need to calculate the cumulative array, summed over
// occupied electrons only
// Set up the cumulative array
double S_p_tot = 0.0;
vector<double> S_p_cum(nel, 0.0);
for (int p=0; p<nel; p++) {
int orb = closed.at(p);
S_p_tot += hb.S_p.at(orb);
S_p_cum.at(p) = S_p_tot;
}
// Pick the first electron
double pRand = random() * S_p_tot;
int pInd = std::lower_bound(S_p_cum.begin(), (S_p_cum.begin() + nel), pRand) - S_p_cum.begin();
// The actual orbital being excited from:
int pFinal = closed.at(pInd);
// The probability that this electron was chosen
double pProb = hb.S_p.at(pFinal) / S_p_tot;
// Pick the second electron with probability D_pq / sum_q' D_pq'
// We again need the relevant cumulative array, summed over
// remaining occupied electrons, q'
// Set up the cumulative array
double D_pq_tot = 0.0;
vector<double> D_pq_cum(nel, 0.0);
for (int q=0; q<nel; q++) {
if (q == pInd) {
D_pq_cum.at(q) = D_pq_tot;
} else {
int orb = closed.at(q);
int ind_pq = triInd(pFinal, orb);
D_pq_tot += hb.D_pq.at(ind_pq);
D_pq_cum.at(q) = D_pq_tot;
}
}
// Pick the second electron
double qRand = random() * D_pq_tot;
int qInd = std::lower_bound(D_pq_cum.begin(), (D_pq_cum.begin() + nel), qRand) - D_pq_cum.begin();
// The actual orbital being excited from:
int qFinal = closed.at(qInd);
// The probability that this electron was chosen
ind = triInd(pFinal, qFinal);
double qProb_p = hb.D_pq.at(ind) / D_pq_tot;
if (pFinal == qFinal) cout << "ERROR: p = q in excitation generator";
// We also need to know the probability that the same two electrons were
// picked in the opposite order.
// The probability that q was picked first:
double qProb = hb.S_p.at(qFinal) / S_p_tot;
// The probability that p was picked second, given that p was picked first:
// Need to calculate the new normalizing factor in D_qp / sum_p' D_qp':
double D_qp_tot = 0.0;
for (int p=0; p<nel; p++) {
int orb = closed.at(p);
if (p != qInd) {
int ind_pq = triInd(orb, qFinal);
D_qp_tot += hb.D_pq.at(ind_pq);
}
}
ind = triInd(pFinal, qFinal);
double pProb_q = hb.D_pq.at(ind) / D_qp_tot;
// Pick spin-orbital r from P(r|pq), such that r and p have the same spin
int rFinal;
double rProb_pq, H_tot_pqr;
pickROrbitalHB(hb, norbs, pFinal, qFinal, rFinal, rProb_pq, H_tot_pqr);
// If the orbital r is already occupied, return null excitations
if (parentDet.getocc(rFinal)) {
pGen = 0.0;
pGen2 = 0.0;
ex1 = 0;
ex2 = 0;
return;
}
// If attemptSingleExcit, then decide whether to generate a single
// or double excitation. If a single excitation is chosen, then generate
// it here and then return.
double singProb_pqr, doubProb_pqr;
if (attemptSingleExcit) {
// Calculate the Hamiltonian element for a single excitation, p to r
double hSing = parentDet.Hij_1Excite(pFinal, rFinal, I1, I2);
double hSingAbs = abs(hSing);
// If this condition is met then we generate either a single or a double
// If it is not then, then we generate both a single and double excitation
if (hSingAbs < H_tot_pqr) {
singProb_pqr = hSingAbs / ( H_tot_pqr + hSingAbs );
doubProb_pqr = 1.0 - singProb_pqr;
double rand = random();
if (rand < singProb_pqr) {
// Generate a single excitation from p to r:
childDet.setocc(pFinal, false);
childDet.setocc(rFinal, true);
pGen = calcSinglesProb(hb, I1, I2, norbs, closed, pProb, D_pq_tot, hSingAbs, pFinal, rFinal);
ex1 = pFinal*2*norbs + rFinal;
// Return a null double excitation
pGen2 = 0.0;
ex2 = 0;
return;
}
// If here, then we generate a double excitation instead of a single
// Set pGen=0 to indicate that a single excitation is not generate
pGen = 0.0;
} else {
// In this case, generate both a single and double excitation
doubProb_pqr = 1.0;
// The single excitation:
childDet.setocc(pFinal, false);
childDet.setocc(rFinal, true);
pGen = calcSinglesProb(hb, I1, I2, norbs, closed, pProb, D_pq_tot, hSingAbs, pFinal, rFinal);
}
// If not attempting to generate a single:
} else {
pGen = 0.0;
doubProb_pqr = 1.0;
}
// Pick the final spin-orbital, s, with probability P(s|pqr), such
// that s and q have the same spin
int sFinal;
double sProb_pqr;
pickSOrbitalHB(hb, norbs, pFinal, qFinal, rFinal, sFinal, sProb_pqr);
if (rFinal == sFinal) cout << "ERROR: r = s in excitation generator";
// If the orbital s is already occupied, return a null excitation
if (parentDet.getocc(sFinal)) {
pGen = 0.0;
pGen2 = 0.0;
ex1 = 0;
ex2 = 0;
return;
}
// Above we chose p first, then q, then r, then s. In calculating the
// probability that this excited determinant was chosen, we need to
// consider the probability that p and q were chosen the opposite way
// around, and the same for r and s.
// Find the probabilities for choosing p first, then q, then s, then r
double rProb_pqs, sProb_pq, doubProb_pqs = 1.0;
calcProbsForRAndS(hb, I1, I2, norbs, parentDet, pFinal, qFinal, sFinal, rFinal,
sProb_pq, rProb_pqs, doubProb_pqs, attemptSingleExcit);
// Find the probabilities for choosing q first, then p, then r, then s
double rProb_qp, sProb_qpr, doubProb_qpr = 1.0;
calcProbsForRAndS(hb, I1, I2, norbs, parentDet, qFinal, pFinal, rFinal, sFinal,
rProb_qp, sProb_qpr, doubProb_qpr, attemptSingleExcit);
// Now calculate the probabilities for choosing q first, then p, then s, then r
double sProb_qp, rProb_qps, doubProb_qps = 1.0;
calcProbsForRAndS(hb, I1, I2, norbs, parentDet, qFinal, pFinal, sFinal, rFinal,
sProb_qp, rProb_qps, doubProb_qps, attemptSingleExcit);
// Generate the final doubly excited determinant...
childDet2.setocc(pFinal, false);
childDet2.setocc(qFinal, false);
childDet2.setocc(rFinal, true);
childDet2.setocc(sFinal, true);
// ...and the probability that it was generated.
pGen2 = pProb*qProb_p * ( doubProb_pqr*rProb_pq*sProb_pqr + doubProb_pqs*sProb_pq*rProb_pqs ) +
qProb*pProb_q * ( doubProb_qpr*rProb_qp*sProb_qpr + doubProb_qps*sProb_qp*rProb_qps );
ex1 = pFinal*2*norbs + rFinal;
ex2 = qFinal*2*norbs + sFinal;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef spawnFCIQMC_HEADER_H
#define spawnFCIQMC_HEADER_H
#include <vector>
#include "Determinants.h"
#include "semiStoch.h"
#include "walkersFCIQMC.h"
#include "workingArray.h"
class Determinant;
// Class for spawning arrays needed in FCIQMC
class spawnFCIQMC {
public:
// The number of determinants spawned to
int nDets;
// The number of replicas simulations being performed
// (i.e. the number of amplitudes to store per determinant)
int nreplicas;
// The list of determinants spawned to
vector<simpleDet> dets;
// Temporary space for communication and sorting
vector<simpleDet> detsTemp;
// The amplitudes of spawned walkers
double** amps;
double** ampsTemp;
// Flags for the spawned walkers
vector<int> flags;
vector<int> flagsTemp;
// The number of elements allocated for spawns to each processor
int nSlotsPerProc;
// The positions of the first elements for each processor in the
// spawning array
vector<int> firstProcSlots;
// The current positions in the spawning array, in which to add
// the next spawned walker to a given processor
vector<int> currProcSlots;
// The number of 64-bit integers required to represent (the alpha or beta
// part of) a determinant
// Note, this is different to DetLen in global.h
int DetLenMin;
spawnFCIQMC() {};
spawnFCIQMC(int spawnSize, int DetLenLocal, int nreplicasLocal);
~spawnFCIQMC();
// Function to initialize spawnFCIQMC. Useful if the object is created
// with the default constructor and needs to be initialized later
void init(int spawnSize, int DetLenLocal, int nreplicasLocal);
// Send spawned walkers to their correct processor
void communicate();
// Merge multiple spawned walkers to the same determinant, so that each
// determinant only appears once
void compress(vector<double>& nAnnihil);
// Move spawned walkers to the provided main walker list
template<typename Wave, typename TrialWalk>
void mergeIntoMain(Wave& wave, TrialWalk& walk, walkersFCIQMC<TrialWalk>& walkers,
semiStoch& core, vector<double>& nAnnihil, const double minPop,
bool initiator, workingArray& work);
template<typename Wave, typename TrialWalk>
void mergeIntoMain_NoInitiator(Wave& wave, TrialWalk& walk,
walkersFCIQMC<TrialWalk>& walkers, semiStoch& core,
vector<double>& nAnnihil, const double minPop,
workingArray& work);
template<typename Wave, typename TrialWalk>
void mergeIntoMain_Initiator(Wave& wave, TrialWalk& walk,
walkersFCIQMC<TrialWalk>& walkers, semiStoch& core,
vector<double>& nAnnihil, const double minPop,
workingArray& work);
};
#endif
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef JastrowMultiSlaterWalker_HEADER_H
#define JastrowMultiSlaterWalker_HEADER_H
#include "WalkerHelper.h"
using namespace Eigen;
/**
Vector of Jastrow-Slater walkers to work with the ResonatingWavefunction
*
*/
class JastrowMultiSlaterWalker
{
public:
Determinant d;
Walker<Jastrow, MultiSlater> walker;
MatrixXcd intermediate, s;
double updateTime;
// constructors
// default
JastrowMultiSlaterWalker(){};
// the following constructors are used by the wave function initWalker function
// for deterministic
JastrowMultiSlaterWalker(Jastrow &corr, const MultiSlater &ref, Determinant &pd)
{
d = pd;
updateTime = 0.;
walker = Walker<Jastrow, MultiSlater> (corr, ref, pd);
};
JastrowMultiSlaterWalker(Jastrow &corr, const MultiSlater &ref)
{
walker = Walker<Jastrow, MultiSlater> (corr, ref);
d = walker.d;
updateTime = 0.;
};
// this is used for storing bestDet
Determinant getDet() { return d; }
double getIndividualDetOverlap(int i) const
{
return walker.getIndividualDetOverlap(i);
}
double getDetOverlap(const MultiSlater &ref) const
{
return walker.getDetOverlap(ref);
}
// these det ratio functions return < m | phi_0 > / < n | phi_0 > with complex projection
double getDetFactor(int i, int a, const MultiSlater &ref) const
{
if (i % 2 == 0)
return getDetFactor(i / 2, a / 2, 0, ref);
else
return getDetFactor(i / 2, a / 2, 1, ref);
}
complex<double> getDetFactorComplex(int i, int a, const MultiSlater &ref) const
{
int tableIndexi, tableIndexa;
walker.refHelper.getRelIndices(i/2, tableIndexi, a/2, tableIndexa, i%2);
return walker.refHelper.rt(tableIndexa, tableIndexi);
}
complex<double> getDetFactorComplex(int i, int j, int a, int b, const MultiSlater &ref) const
{
int tableIndexi, tableIndexa, tableIndexj, tableIndexb;
walker.refHelper.getRelIndices(i/2, tableIndexi, a/2, tableIndexa, i%2);
walker.refHelper.getRelIndices(j/2, tableIndexj, b/2, tableIndexb, j%2);
complex<double> sliceDet = walker.refHelper.rt(tableIndexa, tableIndexi) * walker.refHelper.rt(tableIndexb, tableIndexj)
- walker.refHelper.rt(tableIndexa, tableIndexj) * walker.refHelper.rt(tableIndexb, tableIndexi);
return sliceDet;
}
double getDetFactor(int I, int J, int A, int B, const MultiSlater &ref) const
{
if (I % 2 == J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 0, ref);
else if (I % 2 == J % 2 && I % 2 == 1)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 1, ref);
else if (I % 2 != J % 2 && I % 2 == 0)
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 0, 1, ref);
else
return getDetFactor(I / 2, J / 2, A / 2, B / 2, 1, 0, ref);
}
double getDetFactor(int i, int a, bool sz, const MultiSlater &ref) const
{
int tableIndexi, tableIndexa;
walker.refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz);
return (walker.refHelper.rt(tableIndexa, tableIndexi) * walker.refHelper.refOverlap).real() / walker.refHelper.refOverlap.real();
}
complex<double> getDetFactorComplex(int i, int a, bool sz, const MultiSlater &ref) const
{
int tableIndexi, tableIndexa;
walker.refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz);
return walker.refHelper.rt(tableIndexa, tableIndexi);
}
double getDetFactor(int i, int j, int a, int b, bool sz1, bool sz2, const MultiSlater &ref) const
{
int tableIndexi, tableIndexa, tableIndexj, tableIndexb;
walker.refHelper.getRelIndices(i, tableIndexi, a, tableIndexa, sz1);
walker.refHelper.getRelIndices(j, tableIndexj, b, tableIndexb, sz2);
complex<double> sliceDet = walker.refHelper.rt(tableIndexa, tableIndexi) * walker.refHelper.rt(tableIndexb, tableIndexj)
- walker.refHelper.rt(tableIndexa, tableIndexj) * walker.refHelper.rt(tableIndexb, tableIndexi);
return (sliceDet * walker.refHelper.refOverlap).real() / walker.refHelper.refOverlap.real();
}
// used during sampling
void updateWalker(const MultiSlater &ref, Jastrow &corr, int ex1, int ex2) {
double init = getTime();
walker.updateWalker(ref, corr, ex1, ex2);
updateTime += (getTime() - init);
d = walker.d;
}
void OverlapWithGradient(const MultiSlater &ref, Eigen::VectorBlock<VectorXd> &grad) const
{
if (schd.optimizeCiCoeffs) {
for (int i = 0; i < ref.numDets; i++) grad[i] += walker.refHelper.ciOverlaps[i] / (walker.refHelper.refOverlap.real());
}
// from Filippi's paper, 10.1021/acs.jctc.7b00648, section 3.2
if (schd.optimizeOrbs) {
int norbs = Determinant::norbs, nclosed = walker.refHelper.closedOrbs.size(), nvirt = 2*norbs - nclosed;
// building the y matrix
MatrixXcd yMat = MatrixXcd::Zero(nvirt, nclosed);
int count4 = 0;
for (int i = 1; i < ref.numDets; i++) {
int rank = ref.ciExcitations[i][0].size();
if (rank == 1) {
yMat(ref.ciExcitations[i][1][0], ref.ciExcitations[i][0][0]) += ref.ciCoeffs[i] * ref.ciParity[i];
}
else if (rank == 2) {
yMat(ref.ciExcitations[i][1][0], ref.ciExcitations[i][0][0]) += ref.ciCoeffs[i] * ref.ciParity[i] * walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1]);
yMat(ref.ciExcitations[i][1][1], ref.ciExcitations[i][0][1]) += ref.ciCoeffs[i] * ref.ciParity[i] * walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]);
yMat(ref.ciExcitations[i][1][0], ref.ciExcitations[i][0][1]) -= ref.ciCoeffs[i] * ref.ciParity[i] * walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0]);
yMat(ref.ciExcitations[i][1][1], ref.ciExcitations[i][0][0]) -= ref.ciCoeffs[i] * ref.ciParity[i] * walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]);
}
else if (rank == 3) {
Matrix3cd tcSlice;
for (int mu = 0; mu < 3; mu++)
for (int nu = 0; nu < 3; nu++)
tcSlice(mu, nu) = walker.refHelper.tc(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][nu]);
auto inv = tcSlice.inverse();
for (int mu = 0; mu < 3; mu++)
for (int nu = 0; nu < 3; nu++)
yMat(ref.ciExcitations[i][1][mu], ref.ciExcitations[i][0][nu]) += ref.ciCoeffs[i] * walker.refHelper.ciOverlapRatios[i] * inv(mu, nu);
}
else if (rank == 4) {
auto inv = walker.refHelper.tcSlice[count4].inverse();
for (int mu = 0; mu < 4; mu++)
for (int nu = 0; nu < 4; nu++)
yMat(ref.ciExcitations[i][1][mu], ref.ciExcitations[i][0][nu]) += ref.ciCoeffs[i] * walker.refHelper.ciOverlapRatios[i] * inv(mu, nu);
count4++;
}
else {
MatrixXcd tcSlice = MatrixXcd::Zero(rank, rank);
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
tcSlice(mu, nu) = walker.refHelper.tc(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][nu]);
auto inv = tcSlice.inverse();
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
yMat(ref.ciExcitations[i][1][mu], ref.ciExcitations[i][0][nu]) += ref.ciCoeffs[i] * walker.refHelper.ciOverlapRatios[i] * inv(mu, nu);
}
}
yMat *= walker.refHelper.refOverlap / walker.refHelper.totalComplexOverlap;
MatrixXcd yt = yMat * walker.refHelper.t * walker.refHelper.totalComplexOverlap;
MatrixXcd t_tcyt = (walker.refHelper.t * walker.refHelper.totalComplexOverlap - walker.refHelper.tc * yt);
// iterating over orbitals
for (int i = 0; i < nclosed; i++) {
for (int j = 0; j < nclosed; j++) {
grad[ref.numDets + 4 * walker.refHelper.closedOrbs[i] * norbs + 2 * ref.ref[j]] = t_tcyt(j, i).real() / (walker.refHelper.refOverlap.real());
grad[ref.numDets + 4 * walker.refHelper.closedOrbs[i] * norbs + 2 * ref.ref[j] + 1] = -t_tcyt(j, i).imag() / (walker.refHelper.refOverlap.real());
}
}
//std::vector<int> all(2*norbs);
//std::iota(all.begin(), all.end(), 0);
//std::vector<int> virt(nvirt);
//std::set_difference(all.begin(), all.end(), ref.ref.begin(), ref.ref.end(), virt.begin());
for (int i = 0; i < nclosed; i++) {
for (int j = 0; j < nvirt; j++) {
grad[ref.numDets + 4 * walker.refHelper.closedOrbs[i] * norbs + 2 * walker.refHelper.openOrbs[j]] = yt(j, i).real() / (walker.refHelper.refOverlap.real());
grad[ref.numDets + 4 * walker.refHelper.closedOrbs[i] * norbs + 2 * walker.refHelper.openOrbs[j] + 1] = -yt(j, i).imag() / (walker.refHelper.refOverlap.real());
}
}
}
}
//to be defined for metropolis
void update(int i, int a, bool sz, const MultiSlater &ref, const Jastrow &corr) { return; };
friend ostream& operator<<(ostream& os, const JastrowMultiSlaterWalker& w) {
os << w.d << endl << endl;
os << "t\n" << w.walker.refHelper.t << endl << endl;
os << "rt\n" << w.walker.refHelper.rt << endl << endl;
os << "tc\n" << w.walker.refHelper.tc << endl << endl;
os << "rtc_b\n" << w.walker.refHelper.rtc_b << endl << endl;
os << "ciOverlaps\n";
for (int i = 0; i < w.walker.refHelper.ciOverlaps.size(); i++)
os << w.walker.refHelper.ciOverlaps[i] << endl;
os << "\ntotalOverlap\n" << w.walker.refHelper.totalOverlap << endl << endl;
return os;
}
};
#endif
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ResonatingTRWalker_HEADER_H
#define ResonatingTRWalker_HEADER_H
#include "TRWalker.h"
using namespace Eigen;
/**
Vector of Jastrow-Slater walkers to work with the ResonatingTRWavefunction
*
*/
class ResonatingTRWalker
{
public:
vector<TRWalker> walkerVec;
// constructors
// default
ResonatingTRWalker(){};
// the following constructors are used by the wave function initWalker function
// for deterministic
ResonatingTRWalker(vector<Jastrow> &corr, const vector<Slater> &ref, Determinant &pd)
{
for (int i = 0; i < corr.size(); i++) {
walkerVec.push_back(TRWalker(corr[i], ref[i], pd));
}
};
ResonatingTRWalker(vector<Jastrow> &corr, const vector<Slater> &ref)
{
for (int i = 0; i < corr.size(); i++) {
walkerVec.push_back(TRWalker(corr[i], ref[i]));
}
};
// this is used for storing bestDet
Determinant getDet() { return walkerVec[0].getDet(); }
// used during sampling
void updateWalker(const vector<Slater> &ref, vector<Jastrow> &corr, int ex1, int ex2) {
for (int i = 0; i < walkerVec.size(); i++) {
walkerVec[i].updateWalker(ref[i], corr[i], ex1, ex2);
}
}
//to be defined for metropolis
void update(int i, int a, bool sz, const vector<Slater> &ref, const vector<Jastrow> &corr) { return; };
// used for debugging
friend ostream& operator<<(ostream& os, const ResonatingTRWalker& w) {
for (int i = 0; i < w.walkerVec.size(); i++) {
os << "Walker " << i << endl << endl;
os << w.walkerVec[i] << endl;
}
return os;
}
};
#endif
<file_sep>/*
Developed by <NAME> and <NAME>, 2012
Copyright (c) 2012, <NAME>
This program is integrated in Molpro with the permission of
<NAME> and <NAME>
*/
#pragma once
#include <ctime>
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <execinfo.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
class cumulTimer
{
private:
double localStart;
double cumulativeSum;
public:
cumulTimer() : localStart(-1.0), cumulativeSum(0) {};
void reset() {localStart = -1.0; cumulativeSum = 0.;}
void start() {
struct timeval start;
gettimeofday(&start, NULL);
localStart = start.tv_sec + 1.e-6*start.tv_usec;
}
void stop()
{
struct timeval start;
gettimeofday(&start, NULL);
cumulativeSum = cumulativeSum + (start.tv_sec + 1.e-6*start.tv_usec) - localStart;
if ((start.tv_sec + 1.e-6*start.tv_usec) - localStart < -1.e-10*localStart )
{
cout << "local stop called without starting first"<<endl;
cout << localStart<<" "<<(start.tv_sec + 1.e-6*start.tv_usec)<<endl;
throw 20;
assert(1==2);
abort();
}
localStart = 0;
}
friend ostream& operator<<(ostream& os, const cumulTimer& t)
{
os << ((float)t.cumulativeSum);
return os;
}
};
<file_sep>import numpy as np
import math
from pyscf import gto, scf, ao2mo, mcscf, tools, fci, mp
#from pyscf.shciscf import shci, settings
from pyscf.lo import pipek, boys
import sys
from scipy.linalg import fractional_matrix_power
from scipy.stats import ortho_group
import scipy.linalg as la
def doRHF(mol):
mf = scf.RHF(mol)
print mf.kernel()
return mf
def doUHF(mol):
umf = scf.UHF(mol)
dm = umf.get_init_guess()
norb = mol.nao
dm[0] = dm[0] + np.random.rand(norb, norb) / 2
dm[1] = dm[1] + np.random.rand(norb, norb) / 2
print umf.kernel()
return umf
def localize(mol, mf, method):
if (method == "lowdin"):
return fractional_matrix_power(mf.get_ovlp(mol), -0.5).T
elif (method == "pm"):
return pipek.PM(mol).kernel(mf.mo_coeff)
elif (method == "pmLowdin"):
lowdin = fractional_matrix_power(mf.get_ovlp(mol), -0.5).T
return pipek.PM(mol).kernel(lowdin)
elif (method == "boys"):
return boys.Boys(mol).kernel(mf.mo_coeff)
# only use after lowdin, and for non-minimal bases
def lmoScramble(mol, lmo):
scrambledLmo = np.full(lmo.shape, 0.)
nBasisPerAtom = np.full(mol.natm, 0)
for i in range(len(gto.ao_labels(mol))):
nBasisPerAtom[int(gto.ao_labels(mol)[i].split()[0])] += 1
print nBasisPerAtom
for i in range(mol.natm):
n = nBasisPerAtom[i]
orth = ortho_group.rvs(dim=n)
scrambledLmo[::,n*i:n*(i+1)] = lmo[::,n*i:n*(i+1)].dot(orth)
return scrambledLmo
def writeFCIDUMP(mol, mf, lmo):
h1 = lmo.T.dot(mf.get_hcore()).dot(lmo)
eri = ao2mo.kernel(mol, lmo)
tools.fcidump.from_integrals('FCIDUMP', h1, eri, mol.nao, mol.nelectron, mf.energy_nuc())
def basisChange(matAO, lmo, ovlp):
matMO = (matAO.T.dot(ovlp).dot(lmo)).T
return matMO
def writeMat(mat, fileName, isComplex):
fileh = open(fileName, 'w')
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
if (isComplex):
fileh.write('(%16.10e, %16.10e) '%(mat[i,j].real, mat[i,j].imag))
else:
fileh.write('%16.10e '%(mat[i,j]))
fileh.write('\n')
fileh.close()
def readMat(fileName, shape, isComplex):
if(isComplex):
matr = np.zeros(shape)
mati = np.zeros(shape)
else:
mat = np.zeros(shape)
row = 0
fileh = open(fileName, 'r')
for line in fileh:
col = 0
for coeff in line.split():
if (isComplex):
m = coeff.strip()[1:-1]
matr[row, col], mati[row, col] = [float(x) for x in m.split(',')]
else:
mat[row, col] = float(coeff)
col = col + 1
row = row + 1
fileh.close()
if (isComplex):
mat = matr + 1j * mati
return mat
def doGHF(mol):
gmf = scf.GHF(mol)
gmf.max_cycle = 200
dm = gmf.get_init_guess()
norb = mol.nao
dm = dm + np.random.rand(2*norb, 2*norb) / 3
print gmf.kernel(dm0 = dm)
return gmf
def makeAGPFromRHF(rhfCoeffs):
norb = rhfCoeffs.shape[0]
nelec = 2*rhfCoeffs.shape[1]
diag = np.eye(nelec/2)
#diag = np.zeros((norb,norb))
#for i in range(nelec/2):
# diag[i,i] = 1.
pairMat = rhfCoeffs.dot(diag).dot(rhfCoeffs.T)
return pairMat
def makePfaffFromGHF(ghfCoeffs):
nelec = ghfCoeffs.shape[1]
amat = np.full((nelec, nelec), 0.)
for i in range(nelec/2):
amat[2 * i + 1, 2 * i] = -1.
amat[2 * i, 2 * i + 1] = 1.
pairMat = theta.dot(amat).dot(theta.T)
return pairMat
def addNoise(mat, isComplex):
if (isComplex):
randMat = 0.01 * (np.random.rand(mat.shape[0], mat.shape[1]) + 1j * np.random.rand(mat.shape[0], mat.shape[1]))
return mat + randMat
else:
randMat = 0.01 * np.random.rand(mat.shape[0], mat.shape[1])
return mat + randMat
# make your molecule here
r = 2.5 * 0.529177
atomstring = "N 0 0 0; N 0 0 %g"%(r)
mol = gto.M(
atom = atomstring,
basis = 'ccpvtz',
verbose=4,
symmetry=0,
spin = 0)
mf = doRHF(mol)
mc = mcscf.CASSCF(mf, 8, 10)
mc.kernel()
print "moEne"
for i in range(60):
print mc.mo_energy[i]
lmo = mc.mo_coeff
h1cas, energy_core = mcscf.casci.h1e_for_cas(mc)
mo_core = mc.mo_coeff[:,:2]
mo_rest = mc.mo_coeff[:,2:]
core_dm = 2 * mo_core.dot(mo_core.T)
corevhf = mc.get_veff(mol, core_dm)
h1eff = mo_rest.T.dot(mc.get_hcore() + corevhf).dot(mo_rest)
eri = ao2mo.kernel(mol, lmo[:,2:])
tools.fcidump.from_integrals('FCIDUMP', h1eff, eri, 58, 10, energy_core)
<file_sep>import numpy as np
import scipy.linalg as la
from pyscf import gto
import prepVMC
r = 2.5
atomstring = "N 0 0 0; N 0 0 %g"%(r)
mol = gto.M(
atom = atomstring,
basis = '6-31g',
unit = 'bohr',
verbose=4,
symmetry=0,
spin = 0)
mf = prepVMC.doRHF(mol)
lmo = prepVMC.localizeAllElectron(mf, "lowdin")
# sp hybrids to improve the jastrow
hybrid1p = (lmo[::,1] + lmo[::,5])/2**0.5
hybrid1n = (lmo[::,1] - lmo[::,5])/2**0.5
hybrid2p = (lmo[::,2] + lmo[::,8])/2**0.5
hybrid2n = (lmo[::,2] - lmo[::,8])/2**0.5
lmo[::,1] = hybrid1p
lmo[::,5] = hybrid1n
lmo[::,2] = hybrid2p
lmo[::,8] = hybrid2n
hybrid1p = (lmo[::,10] + lmo[::,14])/2**0.5
hybrid1n = (lmo[::,10] - lmo[::,14])/2**0.5
hybrid2p = (lmo[::,11] + lmo[::,17])/2**0.5
hybrid2n = (lmo[::,11] - lmo[::,17])/2**0.5
lmo[::,10] = hybrid1p
lmo[::,14] = hybrid1n
lmo[::,11] = hybrid2p
lmo[::,17] = hybrid2n
prepVMC.writeFCIDUMP(mol, mf, lmo)
# initial det to start vmc run with
fileh = open("bestDet", 'w')
fileh.write('1. 2 2 0 a a a 0 0 0 2 2 0 b b b 0 0 0\n')
fileh.close()
# rhf
overlap = mf.get_ovlp(mol)
rhfCoeffs = prepVMC.basisChange(mf.mo_coeff, lmo, overlap)
prepVMC.writeMat(rhfCoeffs, "rhf.txt")
# agp
theta = rhfCoeffs[::, :mol.nelectron//2]
pairMat = prepVMC.makeAGPFromRHF(theta)
prepVMC.writeMat(pairMat, "agp.txt")
# uhf
dm = [0. * mf.get_init_guess(), 0. * mf.get_init_guess()]
double = [0, 1]
for i in double:
dm[0][i, i] = 1.
dm[1][i, i] = 1.
dm[0][9+i, 9+i] = 1.
dm[1][9+i, 9+i] = 1.
single = [3, 4, 5]
for i in single:
dm[0][i, i] = 1.
dm[1][9+i, 9+i] = 1.
umf = prepVMC.doUHF(mol, dm)
uhfCoeffs = np.empty((mol.nao, 2*mol.nao))
uhfCoeffs[::,:mol.nao] = prepVMC.basisChange(umf.mo_coeff[0], lmo, overlap)
uhfCoeffs[::,mol.nao:] = prepVMC.basisChange(umf.mo_coeff[1], lmo, overlap)
prepVMC.writeMat(uhfCoeffs, "uhf.txt")
# ghf
dmg = la.block_diag(dm[0], dm[1])
gmf = prepVMC.doGHF(mol, dmg)
ghfCoeffs = prepVMC.basisChange(gmf.mo_coeff, la.block_diag(lmo, lmo), la.block_diag(overlap, overlap))
prepVMC.writeMat(ghfCoeffs, "ghf.txt")
# pfaffian
theta = ghfCoeffs[::, :mol.nelectron]
pairMat = prepVMC.makePfaffFromGHF(theta)
pairMat = prepVMC.addNoise(pairMat)
prepVMC.writeMat(pairMat, "pfaffian.txt")
# multi slater
prepVMC.writeFCIDUMP(mol, mf, mf.mo_coeff, 'FCIDUMP_can')
prepVMC.writeMat(la.block_diag(rhfCoeffs, rhfCoeffs), "rghf.txt")
<file_sep>#pragma once
#include <vector>
#include "fittedFunctions.h"
using namespace std;
using namespace Eigen;
using namespace boost;
extern "C" {
//get density at grid points
void GTOval_cart(int ngrids, int *shls_slice, int *ao_loc,
double *ao, double *coord, char *non0table,
int *atm, int natm, int *bas, int nbas, double *env);
void getValuesAtGrid(const double* coords, int n, double* out);
//FMM functions
void getFockFMM(double* pdm, double* fock, double tol);
void initFMMGridAndTree(double* pdm, double* centroid, double scale, double tol);
void getPotentialFMM(int n, double* coords, double* potential, double* pdm,
double* centroid, double scale, double tol);
//Becke grid functions
void VXCgen_grid(double* pbecke, double* coords, double* atmcoord,
double* p_radii_table, int natm, int ngrid);
void init(int* pshls, int *pao_loc, int *patm, int pnatm,
int *pbas, int pnbas, double *penv);
void getPotentialBecke(int ngird, double* grid, double* potential,
int lmax, int* nrad, double* rm, double* pdm);
void getPotentialBeckeOfAtom(int ia, int ngird, double* grid, double* potential);
}
//miscellaneous functions
void initAtomGrids(int natom, double* atomCoords);
void initAngularData(int lmax, int lebdevOrder, double* angGrid, double* angWts);
void initDensityRadialGrid(int ia, int rmax, double rm, double* radialGrid, double* radialWts);
void fitDensity(int ia, int rindex, double* density);
//void getDensityOnLebdevGridAtGivenR(int rindex, double* density);
void solvePoissonsEquation(int ia);
void fitSplinePotential(int ia);
<file_sep>/* Copyright (c) 2012 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bfint (LICENSE). If not, see http://www.gnu.org/licenses/
*/
#ifndef IR_BOYSFN_H
#define IR_BOYSFN_H
namespace ir {
// store Boys function values Factor*Fm(T) at pOut[0...MaxM], MaxM inclusive
void IrBoysFn(double *pOut, double T, unsigned MaxM, double Factor);
} // namespace ir
#endif // IR_BOYSFN_H
<file_sep>#include "utilsFCIQMC.h"
// This is hash_combine closely based on that used in boost. We use this
// instead of boost::hash_combined directly, because the latter is
// inconsistent across different versions of boost, meaning that tests fail
// depending on the boost version used.
template <class T>
inline void hash_combine_proc(std::size_t& seed, const T& v) {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
// Get unique processor label for this determinant
int getProc(const Determinant& d, int DetLenLocal) {
std::size_t h_tot = 0;
for (int i=0; i<DetLenLocal; i++) {
hash_combine_proc(h_tot, d.reprA[i]);
hash_combine_proc(h_tot, d.reprB[i]);
}
return h_tot % commsize;
}
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
// include OpenMP header if available or define inline dummy functions
// for OMP primitives if not.
#ifndef OPENMP_PROXY_H
#define OPENMP_PROXY_H
#ifdef _OPENMP
#include <omp.h>
#else
inline int omp_get_thread_num() { return 0; } // current thread id
inline void omp_set_num_threads(int) {};
inline int omp_get_max_threads() { return 1; } // total number of threads supposed to be running.
struct omp_lock_t {};
inline void omp_destroy_lock(omp_lock_t *){};
inline void omp_init_lock(omp_lock_t *){};
inline void omp_set_lock(omp_lock_t *){};
#endif
#endif // OPENMP_PROXY_H
<file_sep>#pragma once
#include <Eigen/Dense>
#include "CalculateSphHarmonics.h"
#include <boost/math/interpolators/cubic_b_spline.hpp>
using namespace boost;
using namespace Eigen;
using MatrixXdR = Eigen::Matrix<double, Dynamic, Dynamic, RowMajor>;
void getSphericalCoords(MatrixXdR& grid, MatrixXd& SphericalCoords);
void getBeckePartition(double* coords, int ngrids, double* pbecke);
namespace LebdevGrid{
int MakeAngularGrid(double *Out, int nPoints);
};
//We use this to store the quantities rho^{i,n}_{lm}
//this is a four index quantity
struct RawDataOnGrid {
Vector3d coord; //this is the coordinate of the atom
MatrixXd GridValues; //r x lebdev
MatrixXd CoeffsYlm; //r x lm
VectorXd radialGrid; //r
VectorXd zgrid; //r = rm*(1+cos(pi z))/(1-cos(pi z))
VectorXd wts; //w
double rm;
//al radial points use the same lebdev grid and so this is only needed once
static vector<int> lebdevGridSize;
static int lmax;
static MatrixXdR lebdevgrid; //#lebdev x 4
static MatrixXd SphericalCoords; //#lebdev x 3
static MatrixXd sphVals; //#lebdev x Ylm
static MatrixXd WeightedSphVals; //#lebdev x Ylm
static VectorXd densityStore; //#lebdev
static void InitStaticVariables(int lmax, int lebdevOrder);
void InitRadialGrids(int rmax, double rm);
//calculate the coefficients for spherical Harmonics for lebdev grid at radius r
void fit(int rindex,double* density);
void getValue(int rindex, double* densityOut);
};
struct SplineFit {
Vector3d coord; //this is the coordinate of the atom
vector<boost::math::cubic_b_spline<double> > CoeffsYlmFit; //length = #lm
VectorXd zgrid; //r = rm*(1+cos(pi z))/(1-cos(pi z))
double rm;
int lmax;
VectorXd CoeffsYlm; //#lm (this is just used during claculations)
void Init(const RawDataOnGrid& in);
void getPotential(int ngrid, double* grid, double* potential);
};
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef CX_FIXED_SIZE_ARRAY_H
#define CX_FIXED_SIZE_ARRAY_H
#include <functional> // for std::less
/// Array class with fixed maximum size which stores its elements
/// in-place (i.e., no allocations).
///
/// For technical reasons, all MaxN array elements are default-constructed on
/// construction and only destroyed when TArrayFix is (i.e., technically,
/// all array elements are alive all the time even if size() < max_size()).
template<class FType, unsigned int MaxN, class FSizeType = std::size_t>
struct TArrayFix
{
typedef FType value_type;
typedef FType *iterator;
typedef FType const *const_iterator;
typedef FSizeType size_type;
typedef size_type size_t;
// compiler-generated default destructor, copy-ctor and assignment op should work.
TArrayFix()
: nSize(0)
{};
explicit TArrayFix( size_t nEntries )
: nSize(0)
{ resize(nEntries); };
TArrayFix( size_t nEntries, FType const &Scalar )
: nSize(0)
{ resize(nEntries); *this = Scalar; };
template<class FInputIt>
TArrayFix( FInputIt first, FInputIt last ){
nSize = 0;
while( first != last )
push_back(*(first++));
}
FType &operator[] ( size_t i ){ assert(i < nSize); return m[i]; };
FType const &operator[] ( size_t i ) const { assert(i < nSize); return m[i]; };
FType &back(){ assert(nSize!=0); return m[nSize-1]; };
FType const &back() const { assert(nSize!=0); return m[nSize-1]; };
FType &front(){ assert(nSize!=0); return m[0]; };
FType const &front() const { assert(nSize!=0); return m[0]; };
bool operator == ( TArrayFix const &other ) const {
if ( size() != other.size() )
return false;
for ( size_t i = 0; i != size(); ++ i )
if ( (*this)[i] != other[i] )
return false;
return true;
}
bool operator != ( TArrayFix const &other ) const {
return !this->operator ==(other);
}
size_t size() const { return nSize; }
bool empty() const { return nSize == 0; }
size_t capacity() const { return MaxN; }
void clear() { resize(0); };
void push_back( FType const &t ){
assert( nSize < MaxN );
m[nSize] = t;
++nSize;
}
void pop_back(){
assert( nSize > 0 );
--nSize;
}
void resize( size_t NewSize ){
assert( NewSize <= MaxN );
nSize = NewSize;
}
void resize( size_t NewSize, FType const &value ){
assert( NewSize <= MaxN );
for ( size_t i = nSize; i < NewSize; ++ i )
m[i] = value;
nSize = NewSize;
}
iterator erase( iterator itFirst, iterator itLast ){
assert( itFirst >= begin() && itLast <= end() && itFirst <= itLast );
nSize -= itLast - itFirst;
for ( iterator it = itFirst; it < end(); ++ it, ++ itLast )
*it = *itLast;
return itFirst;
};
iterator erase( iterator itWhere ){
return erase(itWhere, itWhere+1);
};
FType *data() { return &m[0]; };
FType const *data() const { return &m[0]; };
// assign Scalar to every element of *this
void operator = ( FType const &Scalar ){
for ( iterator it = begin(); it != end(); ++ it )
*it = Scalar;
}
template <class FIt>
void assign(FIt first, FIt last) {
resize(last - first);
for ( FSizeType i = 0; i < nSize; ++ i )
m[i] = first[i];
}
iterator begin(){ return &m[0]; }
iterator end(){ return &m[nSize]; }
const_iterator begin() const { return &m[0]; }
const_iterator end() const { return &m[nSize]; }
protected:
FType
m[MaxN];
FSizeType
nSize; // actual number of elements (<= MaxN).
};
// lexicographically compare two arrays. -1: A < B; 0: A == B; +1: A > B.
template<class FType, unsigned int MaxN, class FPred>
int Compare(TArrayFix<FType,MaxN> const &A, TArrayFix<FType,MaxN> const &B, FPred less = std::less<FType>())
{
if ( A.size() < B.size() ) return -1;
if ( B.size() < A.size() ) return +1;
for ( unsigned int i = 0; i < A.size(); ++ i ) {
if ( less(A[i], B[i]) ) return -1;
if ( less(B[i], A[i]) ) return +1;
}
return 0;
}
#endif // CX_FIXED_SIZE_ARRAY_H
// kate: space-indent on; tab-indent on; backspace-indent on; tab-width 4; indent-width 4; mixedindent off; indent-mode normal;
<file_sep>/* Copyright (c) 2012 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bfint (LICENSE). If not, see http://www.gnu.org/licenses/
*/
#include <boost/format.hpp>
#include <ostream>
#include "BasisShell.h"
int BasisSet::getNbas() {
int nbas = 0;
for (int i = 0 ; i <BasisShells.size(); i++) {
nbas += BasisShells[i].nCo * (2 * BasisShells[i].l + 1);
}
return nbas;
}
void BasisShell::PrintAligned(std::ostream &xout, uint Indent) const
{
using boost::format;
std::streampos
p0 = xout.tellp(),
p1;
// xout << format("%3i " % iCenter;
xout << format("%3i: %c %8.4f %8.4f %8.4f ")
% nCo % "spdfghiklm"[l] % Xcoord % Ycoord % Zcoord;
p1 = xout.tellp();
// ^- hm... this doesn't work. tellp() I mean.
p0 = 0;
p1 = 47;
for (uint iExp = 0; iExp < exponents.size(); ++iExp){
if ( iExp != 0 ){
xout << "\n";
for ( uint i = 0; i < Indent + p1 - p0; ++ i )
xout << " ";
}
xout << format("%16.7f ") % exponents[iExp];
double
fRenorm = RawGaussNorm(exponents[iExp], l);
std::stringstream
str;
for ( uint iCo = 0; iCo < nCo; ++ iCo ){
double
fCo = contractions(iExp, iCo);
if ( fCo != 0. )
str << format(" %9.5f") % (fCo*fRenorm);
else
str << format(" %9s") % " - - - -";
}
std::string
s = str.str();
if (0) {
while( !s.empty() && (s[s.size()-1] == ' ' || s[s.size()-1] == '-' ) )
s.resize(s.size() - 1);
}
xout << s;
}
}
unsigned DoubleFactR(int l) {
unsigned r = 1;
while (l > 1) {
r *= l;
l -= 2;
}
return r;
}
double RawGaussNorm(double fExp, unsigned l)
{
// return 1./InvRawGaussNorm(fExp, l);
return pow(M_PI/(2*fExp),.75) * sqrt(DoubleFactR(2*l-1)/pow(4.*fExp,l));
}
<file_sep>import pdb
import itertools
orbitalOrder=[9, 5, 16, 2, 1, 18, 19, 0, 7, 15, 4, 14, 3, 12, 11, 17, 8, 10, 13, 6]
norbs = 20
f = open("twosite.txt", 'w')
l = []
for i in range(norbs):
l.append(i)
combin = list(itertools.combinations(l, 2))
for t in combin:
if ( abs(orbitalOrder[t[0]] - orbitalOrder[t[1]]) <= 1):
f.write("%d %d \n"%( t[0], t[1]))
f.close()
<file_sep>#pragma once
#include <vector>
//#### LIBCINT VARIABLES ######
/*
extern int *shls, *ao_loc, *atm, *bas;
extern int natm, nbas, ncalls;
extern double *env, *dm, *centroid, coordScale, *lattice;
extern std::vector<unsigned char> non0tab;
extern int BLKSIZE;
extern std::vector<double> aovals, intermediate, grid_fformat;
*/
extern "C" {
void getDensityValuesAtGrid(const double* coords, int n, double* out);
void getAoValuesAtGrid(const double* grid_cformat, int ngrid, double* aovals);
void getDensityFittedPQIntegrals();
void initPeriodic(int* pshls, int *pao_loc, int *patm, int pnatm,
int *pbas, int pnbas, double *penv,
double* lattice);
//3 center integral interface
void calcShellIntegralWrapper_3c(double* integrals, int sh1, int sh2, int sh3, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) ;
void calcIntegralWrapper_3c(double* integrals, int *shls, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) ;
//nuclear integral for shell
void calcShellNuclearWrapper(double* integrals, int sh1, int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) ;
void calcNuclearWrapper(double* integrals, int* sh, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) ;
//2 center integral interface
void calcShellIntegralWrapper_2c(char* name, double* integrals, int sh1,
int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) ;
void calcIntegralWrapper_2c(char* name, double* integrals, int *shls, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) ;
}
<file_sep>import numpy
xmax, ymax = 1,10
nsites = xmax*ymax
U = 4.
writeLocal = True
corrLen = 1
sqrt2 = 2**0.5
data = []
for i in range(xmax):
for j in range(ymax):
data.append([i,j])
correlators=[]
print "&FCI NORB=%d ,NELEC=%d ,MS2=0,"%(nsites, nsites)
print "ORBSYM=",
for i in range(nsites):
print "%d,"%(1),
print
print "ISYM=1,"
print "&END"
int2 = numpy.zeros((nsites, nsites, nsites, nsites))
int1 = numpy.zeros((nsites, nsites))
fock = numpy.zeros(shape=(nsites, nsites))
fockUp = numpy.zeros(shape=(nsites, nsites))
fockDn = numpy.zeros(shape=(nsites, nsites))
for i in range(len(data)):
if (writeLocal):
print U, i+1, i+1, i+1, i+1
int2[i,i,i,i] = U
for i in range(len(data)):
for j in range(i+1,len(data)):
d1, d2 = data[i], data[j]
if ( (abs(d1[0] - d2[0]) == 1 or abs(d1[0] - d2[0]) == xmax-1) and d1[1]== d2[1]) :
if (writeLocal):
print "-1.", i+1, j+1, 0, 0
int1[i,j] = int1[j,i] = -1
fock[i,j] = fock[j,i] = -1
fockUp[i,j] = fockUp[j,i] = -1
fockDn[i,j] = fockDn[j,i] = -1
elif ( (abs(d1[1] - d2[1]) == 1 or abs(d1[1] - d2[1]) == ymax-1) and d1[0]== d2[0]) :
if (writeLocal):
print "-1.", i+1, j+1, 0, 0
int1[i,j] = int1[j,i] = -1
fock[i,j] = fock[j,i] = -1
fockUp[i,j] = fockUp[j,i] = -1
fockDn[i,j] = fockDn[j,i] = -1
m = 0.4
n = nsites/2
for i in range(nsites):
fockUp[i, i] = U*(n-m*(-1)**(i+1))
fockDn[i, i] = U*(n+m*(-1)**(i+1))
print fockUp
print fockDn
ekUp, orbUp = numpy.linalg.eigh(fockUp)
ekDn, orbDn = numpy.linalg.eigh(fockDn)
print ekUp
print orbUp
print ekDn
print orbDn
fileHF = open("uhf.txt", 'w')
for i in range(nsites):
for j in range(nsites):
fileHF.write('%16.10e '%(orbUp[i,j]))
for j in range(nsites):
fileHF.write('%16.10e '%(orbDn[i,j]))
fileHF.write('\n')
fileHF = open("ghfy.txt", 'w')
for i in range(nsites):
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbDn[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j+nsites/2]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbDn[i,j+nsites/2]/sqrt2))
fileHF.write('\n')
for i in range(nsites):
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(-orbDn[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j+nsites/2]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(-orbDn[i,j+nsites/2]/sqrt2))
fileHF.write('\n')
for i in range(nsites):
c = [i]
for j in range(nsites):
d1, d2 = data[i], data[j]
if ( (abs(d1[0] - d2[0]) <= corrLen or abs(d1[0] - d2[0]) >= xmax-corrLen) and d1[1]== d2[1]) :
c.append(j)
elif ( (abs(d1[1] - d2[1]) <= corrLen or abs(d1[1] - d2[1]) >= xmax-corrLen) and d1[0]== d2[0]) :
c.append(j)
c = list(set(c))
correlators.append(c)
f = open("correlators.txt", 'w')
for c in correlators:
for t in c:
f.write("%d "%(t))
f.write("\n")
[d,v] = numpy.linalg.eigh(int1)
fileHF = open("rhf.txt", 'w')
for i in range(nsites):
for j in range(nsites):
fileHF.write('%16.10e '%(v[i,j]))
fileHF.write('\n')
#fileHF = open("ghfrhf.txt", 'w')
#for i in range(nsites):
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(v[i,j]))
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(0.))
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(v[i,j+nsites/2]))
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(0.))
# fileHF.write('\n')
#for i in range(nsites):
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(0.))
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(v[i,j]))
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(0.))
# for j in range(nsites/2):
# fileHF.write('%16.10e '%(v[i,j+nsites/2]))
# fileHF.write('\n')
if (not writeLocal) :
newint = numpy.einsum('ij,iklm->jklm', v , int2)
int2 = numpy.einsum('ij,kilm->kjlm', v , newint)
newint = numpy.einsum('ij,klim->kljm', v , int2)
int2 = numpy.einsum('ij,klmi->klmj', v , newint)
for i in range(len(data)):
for j in range(i, len(data)):
for k in range(len(data)):
for l in range(k, len(data)):
print int2[i,j,k,l], i+1, j+1, k+1, l+1
for i in range(len(data)):
print d[i], i+1, i+1, 0, 0
<file_sep>#include "interface.h"
BasisSet basis;
double doubleFact(size_t n) {
if (n == -1) return 1.;
double val = 1.0;
int limit = n/2;
for (int i=0; i<limit; i++)
val *= (n-2*i);
return val;
}
void initPeriodic(int* pshls, int *pao_loc, int *patm, int pnatm,
int *pbas, int pnbas, double *penv,
double* lattice) {
basis.BasisShells.resize(pnbas);
for (int i=0; i<pnbas; i++) {
BasisShell& shell = basis.BasisShells[i];
int atm = pbas[8*i];
//position
shell.Xcoord = penv[patm[6*atm+1]+0];
shell.Ycoord = penv[patm[6*atm+1]+1];
shell.Zcoord = penv[patm[6*atm+1]+2];
shell.l = pbas[8*i + 1];
int nFn = pbas[8*i + 2], nCo = pbas[8*i + 3];
shell.nFn = nFn;
shell.nCo = nCo;
assert(pbas[8*i+6] - pbas[8*i+5] == shell.nFn);
shell.exponents.resize(nFn);
shell.contractions.resize(nFn, nCo);
for (int f=0; f<nFn; f++) {
shell.exponents[f] = penv[ pbas[8*i + 5] + f];
}
//the normalization is really weird coming from pyscf
double norm = sqrt(2*shell.l + 1) * pow(1./M_PI/4., 0.5);// * sqrt(4* M_PI/ (2*LA+1));
for (int f=0; f<nFn; f++)
for (int co=0; co<nCo; co++) {
shell.contractions(f, co) = penv[ pbas[8*i+5] + (co+1) * nFn + f] * norm;
}
}
}
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef IOWRAPPER_HEADER_H
#define IOWRAPPER_HEADER_H
#include <Eigen/Dense>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/complex.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
using namespace Eigen;
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive & ar, MatrixXcd& a, const unsigned int version)
{
int dim1 = a.rows(), dim2 = a.cols();
ar & dim1 & dim2;
if(dim1 != a.rows() || dim2 != a.cols())
a.resize(dim1, dim2);
for(int i=0;i<a.rows();++i)
for(int j=0;j<a.cols();++j)
ar & a(i,j);
}
template<class Archive>
void serialize(Archive & ar, MatrixXd& a, const unsigned int version)
{
int dim1 = a.rows(), dim2 = a.cols();
ar & dim1 & dim2;
if(dim1 != a.rows() || dim2 != a.cols())
a.resize(dim1, dim2);
for(int i=0;i<a.rows();++i)
for(int j=0;j<a.cols();++j)
ar & a(i,j);
}
template<class Archive>
void serialize(Archive & ar, VectorXd& a, const unsigned int version)
{
int dim1 = a.rows();
ar & dim1 ;
if(dim1 != a.rows())
a.resize(dim1);
for(int i=0;i<a.rows();++i)
ar & a(i);
}
}
}
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "JRBM.h"
#include "Determinants.h"
#include <boost/container/static_vector.hpp>
#include <fstream>
#include "input.h"
using namespace Eigen;
JRBM::JRBM () {};
double JRBM::Overlap(const Determinant &d) const
{
return jastrow.Overlap(d) * rbm.Overlap(d);
}
double JRBM::OverlapRatio (const Determinant &d1, const Determinant &d2) const {
return Overlap(d1)/Overlap(d2);
}
double JRBM::OverlapRatio(int i, int a, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
double JRBM::OverlapRatio(int i, int j, int a, int b, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
void JRBM::OverlapWithGradient(const Determinant& d,
Eigen::VectorBlock<VectorXd>& grad,
const double& ovlp) const {
VectorXd gradVec = VectorXd::Zero(grad.size());
Eigen::VectorBlock<VectorXd> gradhead = gradVec.head(jastrow.getNumVariables());
jastrow.OverlapWithGradient(d, gradhead, ovlp);
Eigen::VectorBlock<VectorXd> gradtail = gradVec.tail(rbm.getNumVariables());
rbm.OverlapWithGradient(d, gradtail, ovlp);
grad = gradVec;
}
long JRBM::getNumVariables() const
{
return jastrow.getNumVariables() + rbm.getNumVariables();
}
void JRBM::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
VectorXd vVec = VectorXd::Zero(v.size());
Eigen::VectorBlock<VectorXd> vhead = vVec.head(jastrow.getNumVariables());
jastrow.getVariables(vhead);
Eigen::VectorBlock<VectorXd> vtail = vVec.tail(rbm.getNumVariables());
rbm.getVariables(vtail);
v = vVec;
}
void JRBM::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
VectorXd vVec = v;
Eigen::VectorBlock<VectorXd> vhead = vVec.head(jastrow.getNumVariables());
jastrow.updateVariables(vhead);
Eigen::VectorBlock<VectorXd> vtail = vVec.tail(rbm.getNumVariables());
rbm.updateVariables(vtail);
}
void JRBM::printVariables() const
{
jastrow.printVariables();
rbm.printVariables();
}
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef CX_STORAGE_DEVICE_H
#define CX_STORAGE_DEVICE_H
#include <vector>
#include <map>
#include "CxTypes.h"
namespace ct {
typedef uint64_t
FStreamSize;
typedef uint64_t
FStreamOffset;
uint64_t const
UnknownSize = static_cast<FStreamOffset>(-1);
struct FStorageBlock;
struct FMemoryStack;
/// An object managing persistent storage. Abstracts real or virtual file systems.
/// Intended for interface compatibility with Molpro/ITF.
struct FStorageDevice
{
// identifies storage records within the device.
// Resource is owned by the device, not by the FRecord structure.
struct FRecord
{
uint
iFile,
iRecord;
FStreamOffset
BaseOffset,
EndOffset;
uint
Id; // for internal use of storage device
FRecord() : BaseOffset(0), EndOffset(UnknownSize), Id(0) {}
FRecord(uint iFile_, uint iRecord_ = 0, FStreamOffset nBaseOffset_ = 0, FStreamOffset nLength_ = UnknownSize )
: iFile(iFile_), iRecord(iRecord_), BaseOffset(nBaseOffset_), EndOffset(UnknownSize), Id(0)
{
if ( nLength_ != UnknownSize)
SetLength(nLength_);
}
void SetLength(FStreamOffset NewLength) const;
};
// allocate a new record for temporary data.
virtual FRecord AllocNewRecord(FStreamOffset SizeInBytes) = 0;
FStorageBlock AllocNewBlock(FStreamOffset SizeInBytes);
virtual void Write( FRecord const &r, void const *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const = 0;
virtual void Read( FRecord const &r, void *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const = 0;
virtual void Reserve( FRecord const &r, FStreamOffset nLength ) const = 0;
virtual void Delete( FRecord const &r ) = 0;
virtual ~FStorageDevice(); // = 0;
FStorageDevice() {};
private:
FStorageDevice(FStorageDevice const &other); // not implemented, don't copy!
void operator = (FStorageDevice const &other); // not implemented, don't copy!
};
typedef FStorageDevice::FRecord FRecord;
/// Convenience-combination of storage device and block. Note that these
/// objects DO NOT OWN the data they refer to. The data belongs to the storage
/// device. As such storage blocks are copy-able and don't contain state.
struct FStorageBlock{
FStorageDevice
*pDevice;
FStorageDevice::FRecord
Record;
FStorageBlock() : pDevice(0) {};
FStorageBlock( FStorageDevice &Device_, FStorageDevice::FRecord const &Record_ )
: pDevice(&Device_), Record( Record_ )
{}
FStorageBlock( FStorageDevice const &Device_, FStorageDevice::FRecord const &Record_ )
: pDevice(const_cast<FStorageDevice*>(&Device_)), Record( Record_ )
{} // ^- yeah, I know.
void RawWrite( void const *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) {
pDevice->Write(Record, pData, nLength, Offset);
}
void RawRead( void *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const {
pDevice->Read(Record, pData, nLength, Offset);
}
template<class FScalar>
void Write( FScalar const *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) {
RawWrite(pData, sizeof(FScalar) * nLength, sizeof(FScalar) * Offset);
}
template<class FScalar>
void Read( FScalar *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const {
RawRead(pData, sizeof(FScalar) * nLength, sizeof(FScalar) * Offset);
}
void Delete() {
if ( pDevice != 0 )
pDevice->Delete(Record);
}
};
std::ostream &operator << ( std::ostream &out, FStorageDevice::FRecord const &r );
std::ostream &operator << ( std::ostream &out, FStorageBlock const &r );
/// Implements FStorageDevice interface based on basic posix file system interfaces.
/// Each record is represented by a file; files are put into locations returned by ::tmpfile().
struct FStorageDevicePosixFs : public FStorageDevice
{
FRecord AllocNewRecord(FStreamOffset SizeInBytes); // override.
void Write( FRecord const &r, void const *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const; // override
void Read( FRecord const &r, void *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const; // override
void Reserve( FRecord const &r, FStreamOffset nLength ) const; // override
void Delete( FRecord const &r ); // override
FStorageDevicePosixFs();
~FStorageDevicePosixFs();
protected:
typedef std::map<uint, FILE*>
FFileIdMap;
FFileIdMap
FileIds;
FILE *GetHandle(FRecord const &r) const;
};
/// Implements FStorageDevice with data kept in memory.
/// Each record is represented by a in-memory storage block.
struct FStorageDeviceMemoryBuf : public FStorageDevice
{
FRecord AllocNewRecord(FStreamOffset SizeInBytes = 0);
void Write( FRecord const &r, void const *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const;
void Read( FRecord const &r, void *pData, FStreamOffset nLength, FStreamOffset Offset = 0 ) const;
void Reserve( FRecord const &r, FStreamOffset nLength ) const; // override
void Delete( FRecord const &r );
virtual ~FStorageDeviceMemoryBuf();
private:
struct FBuffer {
char *p;
std::size_t Length;
};
typedef std::vector<FBuffer>
FBufferSet;
FBufferSet
m_Buffers;
FBuffer &GetBuf(FRecord const &r) const;
};
enum FFileAndMemOp {
OP_AddToMem,
OP_Dot,
OP_AddToFile,
OP_WriteFile
};
// provides some simple constant buffer size file+memory operations (see .cpp).
// This template is bound for 64bit and 32bit floats.
template<class FScalar>
void FileAndMemOp( FFileAndMemOp Op, FScalar &f, FScalar *pMemBuf,
std::size_t nMemLength, FStorageBlock const &Rec,
FMemoryStack &Temp );
} // namespace ct
#endif // CX_STORAGE_DEVICE_H
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "Jastrow.h"
#include "Correlator.h"
#include "Determinants.h"
#include <boost/container/static_vector.hpp>
#include <fstream>
#include <iomanip>
#include "input.h"
using namespace Eigen;
Jastrow::Jastrow () {
int norbs = Determinant::norbs;
SpinCorrelator = MatrixXd::Constant(2*norbs, 2*norbs, 1.);
/*
if (schd.optimizeCps)
SpinCorrelator += 0.01*MatrixXd::Random(2*norbs, 2*norbs);
*/
bool readJastrow = false;
char file[5000];
sprintf(file, "Jastrow.txt");
ifstream ofile(file);
if (ofile)
readJastrow = true;
if (readJastrow) {
for (int i = 0; i < SpinCorrelator.rows(); i++) {
for (int j = 0; j < SpinCorrelator.rows(); j++){
ofile >> SpinCorrelator(i, j);
}
}
}
};
double Jastrow::Overlap(const Determinant &d) const
{
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
double ovlp = 1.0;
for (int i=0; i<closed.size(); i++) {
for (int j=0; j<=i; j++) {
int I = max(closed[i], closed[j]), J = min(closed[i], closed[j]);
ovlp *= SpinCorrelator(I, J);
}
}
return ovlp;
}
double Jastrow::OverlapRatio (const Determinant &d1, const Determinant &d2) const {
return Overlap(d1)/Overlap(d2);
}
double Jastrow::OverlapRatio(int i, int a, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
double Jastrow::OverlapRatio(int i, int j, int a, int b, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
void Jastrow::OverlapWithGradient(const Determinant& d,
Eigen::VectorBlock<VectorXd>& grad,
const double& ovlp) const {
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
if (schd.optimizeCps) {
for (int i=0; i<closed.size(); i++) {
for (int j=0; j<=i; j++) {
int I = max(closed[i], closed[j]), J = min(closed[i], closed[j]);
grad[I*(I+1)/2 + J] += ovlp/SpinCorrelator(I, J);
}
}
}
}
long Jastrow::getNumVariables() const
{
long spinOrbs = SpinCorrelator.rows();
return spinOrbs*(spinOrbs+1)/2;
}
void Jastrow::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
int numVars = 0;
for (int i=0; i<SpinCorrelator.rows(); i++)
for (int j=0; j<=i; j++) {
v[numVars] = SpinCorrelator(i,j);
numVars++;
}
}
void Jastrow::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
int numVars = 0;
for (int i=0; i<SpinCorrelator.rows(); i++)
for (int j=0; j<=i; j++) {
SpinCorrelator(i,j) = v[numVars];
numVars++;
}
}
void Jastrow::addNoise() {
SpinCorrelator += 0.01 * MatrixXd::Random(2*Determinant::norbs, 2*Determinant::norbs);
}
void Jastrow::printVariables() const
{
cout << "Jastrow"<< endl;
//for (int i=0; i<SpinCorrelator.rows(); i++)
// for (int j=0; j<=i; j++)
// cout << SpinCorrelator(i,j);
cout << SpinCorrelator << endl << endl;
}
void Jastrow::printVariablesToFile() const
{
string jastrowFileName = "JASTROW";
ofstream out_jastrow;
out_jastrow.open(jastrowFileName);
out_jastrow.precision(12);
out_jastrow << scientific;
for (int i=0; i<SpinCorrelator.rows(); i++) {
for (int j=0; j<=i; j++) {
out_jastrow << " " << setw(4) << i << " " << setw(4) << j << " " << SpinCorrelator(i,j) << endl;
}
}
out_jastrow.close();
}
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Determinants_HEADER_H
#define Determinants_HEADER_H
#include "global.h"
#include <iostream>
#include <vector>
#include <boost/serialization/serialization.hpp>
#include <boost/functional/hash.hpp>
#include <Eigen/Dense>
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
class workingArray;
using namespace std;
inline int CountNonZeroBits (long x)
{
x = (x & 0x5555555555555555ULL) + ((x >> 1) & 0x5555555555555555ULL);
x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
x = (x & 0x0F0F0F0F0F0F0F0FULL) + ((x >> 4) & 0x0F0F0F0F0F0F0F0FULL);
return (x * 0x0101010101010101ULL) >> 56;
}
// Just the determinant bit string, stored in a contiguous array
typedef std::array<long, 2*DetLen> simpleDet;
// A shorter version of simpleDet that. This is useful if we only
// need to store the active space occupations, for example in
// SC-NEVPT2(s) calculations
typedef std::array<long, 2*innerDetLen> shortSimpleDet;
/**
* This is the occupation number representation of a Determinants
* with alpha, beta strings
*/
class Determinant {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
for (int i=0; i<DetLen; i++)
ar & reprA[i] & reprB[i];
}
public:
// 0th position of 0th long is the first position
// 63rd position of the last long is the last position
long reprA[DetLen], reprB[DetLen];
static int EffDetLen;
static char Trev;
static int norbs;
static int nalpha, nbeta;
static Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic> LexicalOrder;
//Constructors
Determinant();
Determinant(const Determinant& d);
Determinant(const simpleDet combined) {
for (int i=0; i<DetLen; i++) {
reprA[i] = combined[i];
}
for (int i=0; i<DetLen; i++) {
reprB[i] = combined[i+DetLen];
}
}
Determinant(const shortSimpleDet combined) {
for (int i=0; i<innerDetLen; i++) {
reprA[i] = combined[i];
}
for (int i=0; i<innerDetLen; i++) {
reprB[i] = combined[i+innerDetLen];
}
}
void operator=(const Determinant& d);
//mutates the Determinant
void setoccA(int i, bool occ);
void setoccB(int i, bool occ);
void setocc(int i, bool occ) ; //i is the spin orbital index
void setocc(int i, bool sz, bool occ) ; //i is the spatial orbital index, sz=0 for alpha, =1 for beta
bool getocc(int i) const ;//i is the spin orbital index
bool getocc(int i, bool sz) const ;//i is the spatial orbital index
bool getoccA(int i) const ;
bool getoccB(int i) const;
void getOpenClosed( std::vector<int>& open, std::vector<int>& closed) const;//gets spin orbitals
void getOpenClosed( bool sz, std::vector<int>& open, std::vector<int>& closed) const;//gets spatial orbitals
void getOpenClosedAlphaBeta( std::vector<int>& openAlpha,
std::vector<int>& closedAlpha,
std::vector<int>& openBeta,
std::vector<int>& closedBeta ) const;
void getClosedAlphaBeta( std::vector<int>& closedAlpha,
std::vector<int>& closedBeta ) const;
void getAlphaBeta(std::vector<int>& alpha, std::vector<int>& beta) const;
void getClosed(std::vector<int>& closed) const;
void getClosedAllocated(std::vector<int>& closed) const;
void getClosed(bool sz, std::vector<int>& closed) const;
int getNbetaBefore(int i) const;
int getNalphaBefore(int i) const;
int Noccupied() const;
int Nalpha() const;
int Nbeta() const;
void flipAlphaBeta() ;
double parityA(const int& a, const int& i) const;
double parityB(const int& a, const int& i) const;
double parity(const int& a, const int& i, const bool& sz) const;
double parityA(const vector<int>& aArray, const vector<int>& iArray) const ;
double parityB(const vector<int>& aArray, const vector<int>& iArray) const ;
double parity(const vector<int>& aArray, const vector<int>& iArray, bool sz) const ;
double parityAA(const int& i, const int& j, const int& a, const int& b) const ;
double parityBB(const int& i, const int& j, const int& a, const int& b) const ;
double parityFull(const int ex2, const int i, const int j, const int a, const int b) const;
double Energy(const oneInt& I1, const twoInt& I2, const double& coreE) const ;
CItype Hij_1ExciteScreened(const int& a, const int& i, const twoIntHeatBathSHM& Ishm,
const double& TINY, bool doparity = true) const;
CItype Hij_1Excite(const int& a, const int& i, const oneInt&I1, const twoInt& I2,
bool doparity=true) const ;
CItype Hij_1ExciteA(const int& a, const int& i, const oneInt&I1, const twoInt& I2,
bool doparity=true) const ;
CItype Hij_1ExciteB(const int& a, const int& i, const oneInt&I1, const twoInt& I2,
bool doparity=true) const ;
CItype Hij_2ExciteAA(const int& a, const int& i, const int& b, const int& j,
const oneInt&I1, const twoInt& I2) const ;
CItype Hij_2ExciteBB(const int& a, const int& i, const int& b, const int& j,
const oneInt&I1, const twoInt& I2) const ;
CItype Hij_2ExciteAB(const int& a, const int& i, const int& b, const int& j,
const oneInt&I1, const twoInt& I2) const ;
bool connected(const Determinant& d) const;
int ExcitationDistance(const Determinant& d) const;
//operators
bool operator<(const Determinant& d) const;
bool operator==(const Determinant& d) const;
friend ostream& operator<<(ostream& os, const Determinant& d);
friend size_t hash_value(Determinant const& d);
// print the occupations of orbitals within the active space
void printActive(ostream& os);
// Return simplified version of determinant
inline simpleDet getSimpleDet() const {
simpleDet combined;
for (int i=0; i<DetLen; i++) {
combined[i] = reprA[i];
}
for (int i=0; i<DetLen; i++) {
combined[i+DetLen] = reprB[i];
}
return combined;
}
inline shortSimpleDet getShortSimpleDet() const {
shortSimpleDet combined;
for (int i=0; i<innerDetLen; i++) {
combined[i] = reprA[i];
}
for (int i=0; i<innerDetLen; i++) {
combined[i+innerDetLen] = reprB[i];
}
return combined;
}
};
//instead of storing memory in bits it uses 1 integer per bit
//so it is clearly very exepnsive. This is only used during computations
class BigDeterminant {
public:
vector<char> occupation;
BigDeterminant(const Determinant& d);
BigDeterminant(const BigDeterminant& d) : occupation(d.occupation){};
const char& operator[] (int j) const ;
char& operator[] (int j) ;
};
//note some of i, j, k, l might be repeats
//and some its possible that the determinant might get killed
//the return value tell us whether the determinant is killed
bool applyExcitation(int a, int b, int k, int l, Determinant& dcopy);
CItype Hij(const Determinant& bra, const Determinant& ket,
const oneInt& I1, const twoInt& I2, const double& coreE);
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket,
vector<int> &creA, vector<int> &desA,
vector<int> &creB, vector<int> &desB);
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket,
vector<int> &cre, vector<int> &des,
bool sz);
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket, int &I, int &A);
void getDifferenceInOccupation(const Determinant &bra, const Determinant &ket,
int &I, int &J, int& A, int& B);
double getParityForDiceToAlphaBeta(const Determinant& det);
//---Generate all screened excitations---------------------------
void generateAllScreenedSingleExcitation(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
void generateAllScreenedDoubleExcitation(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
//---Generate all screened excitations in the FOIS---------------
void generateAllScreenedDoubleExcitationsFOIS(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
void generateAllScreenedSingleExcitationsDyallOld(const Determinant& det,
const Determinant& detAct,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
void generateAllScreenedDoubleExcitationsDyallOld(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
void generateAllScreenedSingleExcitationsDyall(const Determinant& det,
const Determinant& detAct,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
void generateAllScreenedDoubleExcitationsDyall(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
//---Generate all screened excitations into the CAS-------------------
//---From excitation class 0 (the CAS itself) into the CAS------------
void generateAllScreenedSingleExcitationsCAS_0h0p(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
bool doparity = false);
//---From excitation class 0 (the CAS itself) into the CAS------------
void generateAllScreenedDoubleExcitationsCAS_0h0p(const Determinant& det,
const double& screen,
workingArray& work);
//---From excitation class 1 (0 holes in core, 1 particle in virtuals) into the CAS
void generateAllScreenedSingleExcitationsCAS_0h1p(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
const int& i,
bool doparity = false);
//---From excitation class 1 (0 holes in core, 1 particle in virtuals) into the CAS
void generateAllScreenedDoubleExcitationsCAS_0h1p(const Determinant& det,
const double& screen,
workingArray& work,
const int& i);
//---From excitation class 2 (0 holes in core, 2 particles in virtuals) into the CAS
void generateAllScreenedExcitationsCAS_0h2p(const Determinant& det,
const double& screen,
workingArray& work,
const int& iExc, const int& jExc);
//---From excitation class 3 (1 hole in core, 0 particles in virtuals) into the CAS
void generateAllScreenedSingleExcitationsCAS_1h0p(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
const int& a,
bool doparity = false);
//---From excitation class 3 (1 hole in core, 0 particles in virtuals) into the CAS
void generateAllScreenedDoubleExcitationsCAS_1h0p(const Determinant& det,
const double& screen,
workingArray& work,
const int& a);
//---From excitation class 4 (1 hole in core, 1 particle in virtuals) into the CAS
void generateAllScreenedSingleExcitationsCAS_1h1p(const Determinant& det,
const double& screen,
const double& TINY,
workingArray& work,
const int& i, const int& a,
bool doparity = false);
//---From excitation class 4 (1 hole in core, 1 particle in virtuals) into the CAS
void generateAllScreenedDoubleExcitationsCAS_1h1p(const Determinant& det,
const double& screen,
workingArray& work,
const int& i, const int& a);
//---From excitation class 5 (1 hole in core, 2 particles in virtuals) into the CAS
void generateAllScreenedExcitationsCAS_1h2p(const Determinant& det,
const double& screen,
workingArray& work,
const int& iExc, const int& jExc,
const int& a);
//---From excitation class 6 (2 holes in core, 0 particles in virtuals) into the CAS
void generateAllScreenedExcitationsCAS_2h0p(const Determinant& det,
const double& screen,
workingArray& work,
const int& aExc, const int& bExc);
//---From excitation class 7 (2 holes in core, 1 particle in virtuals) into the CAS
void generateAllScreenedExcitationsCAS_2h1p(const Determinant& det,
const double& screen,
workingArray& work,
const int& iExc,
const int& aExc, const int& bExc);
//---From excitation class 8 (2 holes in core, 2 particles in virtuals) into the CAS
void generateAllScreenedExcitationsCAS_2h2p(const double& screen,
workingArray& work,
const int& iExc, const int& jExc,
const int& aExc, const int& bExc);
void comb(int N, int K, vector<vector<int>> &combinations);
void generateAllDeterminants(vector<Determinant>& allDets, int norbs, int nalpha, int nbeta);
void generateAllDeterminantsActive(vector<Determinant>& allDets, const Determinant dExternal, const int ncore,
const int nact, const int nalpha, const int nbeta);
void generateAllDeterminantsFOIS(vector<Determinant>& allDets, int norbs, int nalpha, int nbeta);
template<> struct std::hash<Determinant>
{
std::size_t operator()(Determinant const& d) const noexcept
{
std::size_t h_tot = 0;
for (int i=0; i<DetLen; i++) {
boost::hash_combine(h_tot, d.reprA[i]);
boost::hash_combine(h_tot, d.reprB[i]);
}
return h_tot;
}
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <vector>
#include <boost/serialization/serialization.hpp>
#include <Eigen/Dense>
#include "global.h"
#include "input.h"
#include "spawnFCIQMC.h"
#include "walkersFCIQMC.h"
#include "AGP.h"
#include "CorrelatedWavefunction.h"
#include "Jastrow.h"
#include "Slater.h"
#include "SelectedCI.h"
#include "trivialWF.h"
#include "trivialWalk.h"
template <typename T, typename Compare>
vector<size_t> sort_permutation(int const nDets, const vector<T>& vec, Compare compare)
{
vector<size_t> p(nDets);
iota(p.begin(), p.end(), 0);
sort(p.begin(), p.end(),
[&](size_t i, size_t j){ return compare(vec[i], vec[j]); });
return p;
}
template <typename T>
void apply_permutation(int const nDets, const vector<T>& vec, vector<T>& sorted_vec, const vector<size_t>& p)
{
transform(p.begin(), p.end(), sorted_vec.begin(),
[&](size_t i){ return vec[i]; });
}
void apply_permutation(int const nDets, double** amps, double** sorted_amps, const vector<size_t>& p)
{
for (int iDet = 0; iDet<nDets; iDet++) {
int sorted_ind = p.at(iDet);
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
sorted_amps[iDet][iReplica] = amps[sorted_ind][iReplica];
}
}
}
spawnFCIQMC::spawnFCIQMC(int spawnSize, int DetLenLocal, int nreplicasLocal) {
init(spawnSize, DetLenLocal, nreplicasLocal);
}
void spawnFCIQMC::init(int spawnSize, int DetLenLocal, int nreplicasLocal) {
nDets = 0;
nreplicas = nreplicasLocal;
dets.resize(spawnSize);
detsTemp.resize(spawnSize);
amps = allocateAmpsArray(spawnSize, nreplicas, 0.0);
ampsTemp = allocateAmpsArray(spawnSize, nreplicas, 0.0);
if (schd.initiator) {
flags.resize(spawnSize, 0);
flagsTemp.resize(spawnSize, 0);
}
firstProcSlots.resize(commsize);
currProcSlots.resize(commsize);
nSlotsPerProc = spawnSize / commsize;
for (int i=0; i<commsize; i++) {
firstProcSlots[i] = i*nSlotsPerProc;
}
currProcSlots = firstProcSlots;
DetLenMin = DetLenLocal;
}
spawnFCIQMC::~spawnFCIQMC() {
dets.clear();
detsTemp.clear();
deleteAmpsArray(amps);
deleteAmpsArray(ampsTemp);
flags.clear();
flagsTemp.clear();
firstProcSlots.clear();
currProcSlots.clear();
}
// Send spawned walkers to their correct processor
void spawnFCIQMC::communicate() {
#ifdef SERIAL
nDets = currProcSlots[0] - firstProcSlots[0];
// Copy spawning data to temp arrays
for (int iDet=0; iDet<nDets; iDet++) {
detsTemp[iDet] = dets[iDet];
for (int iReplica = 0; iReplica<nreplicas; iReplica++) {
ampsTemp[iDet][iReplica] = amps[iDet][iReplica];
}
if (schd.initiator) flagsTemp[iDet] = flags[iDet];
}
#else
int sendCounts[commsize], recvCounts[commsize];
int sendDispls[commsize], recvDispls[commsize];
int sendCountsDets[commsize], recvCountsDets[commsize];
int sendDisplsDets[commsize], recvDisplsDets[commsize];
int sendCountsAmps[commsize], recvCountsAmps[commsize];
int sendDisplsAmps[commsize], recvDisplsAmps[commsize];
// The number of determinants to send to each processor, and their
// displacements in the spawning list
for (int proc=0; proc<commsize; proc++) {
sendCounts[proc] = currProcSlots[proc] - firstProcSlots[proc];
sendDispls[proc] = firstProcSlots[proc];
}
// Communicate the number of dets to be sent and received
MPI_Alltoall(sendCounts, 1, MPI_INTEGER, recvCounts, 1, MPI_INTEGER, MPI_COMM_WORLD);
// Displacements of dets about to be received
recvDispls[0] = 0;
for (int proc=1; proc<commsize; proc++) {
recvDispls[proc] = recvDispls[proc-1] + recvCounts[proc-1];
}
// Dets have width of 2*DetLen
// They are stored contiguously in the vector, as required for MPI
for (int proc=0; proc<commsize; proc++) {
sendCountsDets[proc] = sendCounts[proc] * 2*DetLen;
recvCountsDets[proc] = recvCounts[proc] * 2*DetLen;
sendDisplsDets[proc] = sendDispls[proc] * 2*DetLen;
recvDisplsDets[proc] = recvDispls[proc] * 2*DetLen;
sendCountsAmps[proc] = sendCounts[proc] * nreplicas;
recvCountsAmps[proc] = recvCounts[proc] * nreplicas;
sendDisplsAmps[proc] = sendDispls[proc] * nreplicas;
recvDisplsAmps[proc] = recvDispls[proc] * nreplicas;
}
MPI_Alltoallv(&dets.front(), sendCountsDets, sendDisplsDets, MPI_LONG,
&detsTemp.front(), recvCountsDets, recvDisplsDets, MPI_LONG, MPI_COMM_WORLD);
MPI_Alltoallv(&(amps[0][0]), sendCountsAmps, sendDisplsAmps, MPI_DOUBLE,
&(ampsTemp[0][0]), recvCountsAmps, recvDisplsAmps, MPI_DOUBLE, MPI_COMM_WORLD);
if (schd.initiator) {
MPI_Alltoallv(&flags.front(), sendCounts, sendDispls, MPI_INTEGER,
&flagsTemp.front(), recvCounts, recvDispls, MPI_INTEGER, MPI_COMM_WORLD);
}
// The total number of determinants received
nDets = recvDispls[commsize-1] + recvCounts[commsize-1];
#endif
}
// Merge multiple spawned walkers to the same determinant, so that each
// determinant only appears once
void spawnFCIQMC::compress(vector<double>& nAnnihil) {
if (nDets > 0) {
// Perform sort
auto p = sort_permutation(nDets, detsTemp, [](simpleDet const& a, simpleDet const& b){ return (a < b); });
apply_permutation( nDets, detsTemp, dets, p );
apply_permutation( nDets, ampsTemp, amps, p );
if (schd.initiator) {
apply_permutation( nDets, flagsTemp, flags, p );
}
bool exitOuter = false;
int j = 0, k = 0;
// Now the array is sorted, loop through and merge repeats
while (true) {
dets[j] = dets[k];
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
amps[j][iReplica] = amps[k][iReplica];
}
if (schd.initiator) flags[j] = flags[k];
while (true) {
k += 1;
if (k == nDets) {
exitOuter = true;
break;
}
if ( dets[j] == dets[k] ) {
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
if (amps[j][iReplica]*amps[k][iReplica] < 0.0) {
nAnnihil[iReplica] += 2.0*min(abs(amps[j][iReplica]), abs(amps[k][iReplica]));
}
amps[j][iReplica] += amps[k][iReplica];
}
// If the parent of any of the child walkers on this
// determinant was an initiator, then we want to allow the
// spawn. So set the child's flag to specify this, if so.
// (Bitwise OR operation).
if (schd.initiator) {
flags[j] |= flags[k];
}
} else {
break;
}
}
if (exitOuter) break;
if (j == nDets-1) {
break;
} else {
j += 1;
}
}
nDets = j+1;
}
}
// Wrapper function for merging the spawned list into the main list
// Two versions are used for optimization
template<typename Wave, typename TrialWalk>
void spawnFCIQMC::mergeIntoMain(Wave& wave, TrialWalk& walk,
walkersFCIQMC<TrialWalk>& walkers,
semiStoch& core, vector<double>& nAnnihil,
const double minPop, bool initiator,
workingArray& work) {
if (initiator) {
mergeIntoMain_Initiator(wave, walk, walkers, core, nAnnihil, minPop, work);
} else {
mergeIntoMain_NoInitiator(wave, walk, walkers, core, nAnnihil, minPop, work);
}
}
// Move spawned walkers to the provided main walker list
template<typename Wave, typename TrialWalk>
void spawnFCIQMC::mergeIntoMain_NoInitiator(Wave& wave, TrialWalk& walk,
walkersFCIQMC<TrialWalk>& walkers,
semiStoch& core, vector<double>& nAnnihil,
const double minPop, workingArray& work) {
for (int i = 0; i<nDets; i++) {
// Convert from simpleDet to Determinant object
Determinant det_i = Determinant(dets[i]);
// Is this spawned determinant already in the main list?
if (walkers.ht.find(det_i) != walkers.ht.end()) {
int iDet = walkers.ht[det_i];
// If using semi-stochastic, don't round spawning to core dets
bool round = true;
if (schd.semiStoch) {
round = core.ht.find(dets[i]) == core.ht.end();
}
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
double oldAmp = walkers.amps[iDet][iReplica];
// To ensure the various replicas are statistically independent,
// we should stochastically round the spawning on a determinant
// if it is currently unoccupied, and the new walker is below
// the minimum threshold (since this is what happens if all
// replicas are unoccupied):
if (round) {
if (abs(oldAmp) < 1.0e-12 && abs(amps[i][iReplica]) < minPop) {
bool keepDet;
stochastic_round(minPop, amps[i][iReplica], keepDet);
}
}
if (amps[i][iReplica]*oldAmp < 0.0) {
nAnnihil[iReplica] += 2.0*min(abs(amps[i][iReplica]), abs(oldAmp));
}
double newAmp = amps[i][iReplica] + oldAmp;
walkers.amps[iDet][iReplica] = newAmp;
}
}
else
{
// New determinant:
bool keepDetAny = false;
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
// If smaller than the smallest allowed population, then stochastically
// round up to the threshold or down to 0:
if (abs(amps[i][iReplica]) < minPop) {
bool keepDet;
stochastic_round(minPop, amps[i][iReplica], keepDet);
keepDetAny = keepDetAny || keepDet;
} else {
keepDetAny = true;
}
}
if (keepDetAny) {
int pos;
// Check if a determinant has become unoccupied in the existing list
// If so, insert into that position
// If not, then increase the walkers.ndets by 1 and add it on the end
if (walkers.firstEmpty <= walkers.lastEmpty) {
pos = walkers.emptyDets[walkers.firstEmpty];
walkers.firstEmpty += 1;
}
else
{
pos = walkers.nDets;
walkers.nDets += 1;
}
walkers.dets[pos] = det_i;
walkers.diagH[pos] = det_i.Energy(I1, I2, coreE);
TrialWalk newWalk(wave, det_i);
double ovlp, localE, SVTotal;
wave.HamAndOvlpAndSVTotal(newWalk, ovlp, localE, SVTotal, work,
schd.epsilon);
walkers.ovlp[pos] = ovlp;
walkers.localE[pos] = localE;
walkers.SVTotal[pos] = SVTotal;
walkers.trialWalk[pos] = newWalk;
// Add in the new walker population
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
walkers.amps[pos][iReplica] = amps[i][iReplica];
}
walkers.ht[det_i] = pos;
}
}
}
}
// Move spawned walkers to the provided main walker list, while
// applying the initiator criteria
template<typename Wave, typename TrialWalk>
void spawnFCIQMC::mergeIntoMain_Initiator(Wave& wave, TrialWalk& walk,
walkersFCIQMC<TrialWalk>& walkers,
semiStoch& core, vector<double>& nAnnihil,
const double minPop, workingArray& work) {
for (int i = 0; i<nDets; i++) {
// Convert from simpleDet to Determinant object
Determinant det_i = Determinant(dets[i]);
// Used for testing if an initiator flag is set:
bitset<max_nreplicas> initFlags(flags[i]);
// Is this spawned determinant already in the main list?
if (walkers.ht.find(det_i) != walkers.ht.end()) {
int iDet = walkers.ht[det_i];
// When doing semi-stochastic, all spawnings to core dets are
// allowed, and are never stochastically rounded
bool coreDet = false;
if (schd.semiStoch) {
coreDet = core.ht.find(dets[i]) != core.ht.end();
}
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
double oldAmp = walkers.amps[iDet][iReplica];
// For the initiator criteria: only add in the spawned walker
// for this determinant if it is already on occupied on
// *this* particular replica, or the initiator flag is set
if ( initFlags.test(iReplica) || abs(oldAmp) > 1.0e-12 || coreDet ) {
// To ensure the various replicas are statistically independent,
// we should stochastically round the spawning on a determinant
// if it is currently unoccupied, and the new walker is below
// the minimum threshold (since this is what happens if all
// replicas are unoccupied):
if (!coreDet) {
if (abs(oldAmp) < 1.0e-12 && abs(amps[i][iReplica]) < minPop) {
bool keepDet;
stochastic_round(minPop, amps[i][iReplica], keepDet);
}
}
if (amps[i][iReplica]*oldAmp < 0.0) {
nAnnihil[iReplica] += 2.0*min(abs(amps[i][iReplica]), abs(oldAmp));
}
double newAmp = amps[i][iReplica] + oldAmp;
walkers.amps[iDet][iReplica] = newAmp;
}
}
}
else
{
// Note that a new determinant can never be a core determinant when
// semi-stochastic is in use; core determinants are never removed
// from the main walker list. So we don't need to check for this.
// New determinant:
bool keepDetAny = false;
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
// Check if initiator flag is set for this replica:
if ( initFlags.test(iReplica) ) {
// If smaller than the smallest allowed population, then stochastically
// round up to the threshold or down to 0:
if (abs(amps[i][iReplica]) < minPop) {
bool keepDet;
stochastic_round(minPop, amps[i][iReplica], keepDet);
keepDetAny = keepDetAny || keepDet;
} else {
keepDetAny = true;
}
}
}
if (keepDetAny) {
int pos;
// Check if a determinant has become unoccupied in the existing list
// If so, insert into that position
// If not, then increase the walkers.ndets by 1 and add it on the end
if (walkers.firstEmpty <= walkers.lastEmpty) {
pos = walkers.emptyDets[walkers.firstEmpty];
walkers.firstEmpty += 1;
}
else
{
pos = walkers.nDets;
walkers.nDets += 1;
}
walkers.dets[pos] = det_i;
walkers.diagH[pos] = det_i.Energy(I1, I2, coreE);
TrialWalk newWalk(wave, det_i);
double ovlp, localE, SVTotal;
wave.HamAndOvlpAndSVTotal(newWalk, ovlp, localE, SVTotal, work,
schd.epsilon);
walkers.ovlp[pos] = ovlp;
walkers.localE[pos] = localE;
walkers.SVTotal[pos] = SVTotal;
walkers.trialWalk[pos] = newWalk;
// Add in the new walker population, but only if allowed by the
// initiator criteria (i.e. if the flag is set):
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
if ( initFlags.test(iReplica) ) {
walkers.amps[pos][iReplica] = amps[i][iReplica];
}
}
walkers.ht[det_i] = pos;
}
}
}
}
// Instantiate needed templates
// Trivial (no trial wave function)
template void spawnFCIQMC::mergeIntoMain(
TrivialWF& wave, TrivialWalk& walk,
walkersFCIQMC<TrivialWalk>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
bool initiator,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_NoInitiator(
TrivialWF& wave, TrivialWalk& walk,
walkersFCIQMC<TrivialWalk>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_Initiator(
TrivialWF& wave, TrivialWalk& walk,
walkersFCIQMC<TrivialWalk>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
// Jastrow-AGP
using JAGPWalker = Walker<Jastrow, AGP>;
template void spawnFCIQMC::mergeIntoMain(
CorrelatedWavefunction<Jastrow, AGP>& wave,
Walker<Jastrow, AGP>& walk,
walkersFCIQMC<JAGPWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
bool initiator,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_NoInitiator(
CorrelatedWavefunction<Jastrow, AGP>& wave,
Walker<Jastrow, AGP>& walk,
walkersFCIQMC<JAGPWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_Initiator(
CorrelatedWavefunction<Jastrow, AGP>& wave,
Walker<Jastrow, AGP>& walk,
walkersFCIQMC<JAGPWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
// Jastrow-Slater
using JSWalker = Walker<Jastrow, Slater>;
template void spawnFCIQMC::mergeIntoMain(
CorrelatedWavefunction<Jastrow, Slater>& wave,
Walker<Jastrow, Slater>& walk,
walkersFCIQMC<JSWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
bool initiator,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_NoInitiator(
CorrelatedWavefunction<Jastrow, Slater>& wave,
Walker<Jastrow, Slater>& walk,
walkersFCIQMC<JSWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_Initiator(
CorrelatedWavefunction<Jastrow, Slater>& wave,
Walker<Jastrow, Slater>& walk,
walkersFCIQMC<JSWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
// SelectedCI
template void spawnFCIQMC::mergeIntoMain(
SelectedCI& wave,
SimpleWalker& walk,
walkersFCIQMC<SimpleWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
bool initiator,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_NoInitiator(
SelectedCI& wave,
SimpleWalker& walk,
walkersFCIQMC<SimpleWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
template void spawnFCIQMC::mergeIntoMain_Initiator(
SelectedCI& wave,
SimpleWalker& walk,
walkersFCIQMC<SimpleWalker>& walkers,
semiStoch& core,
vector<double>& nAnnihil,
const double minPop,
workingArray& work);
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace NEVPT2_ACVV {
FTensorDecl TensorDecls[29] = {
/* 0*/{"t", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "eeca", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"f", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"f", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory}, //dummy
/* 6*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory}, //dummy
/* 7*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory}, //dummy
/* 8*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory}, //dummy
/* 9*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory}, //dummy
/* 10*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 13*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 14*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S1", "AA", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"S2", "aa", "",USAGE_Density, STORAGE_Memory},
/* 18*/{"T", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 19*/{"b", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"p", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"Ap", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"P", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"AP", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"B", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"W", "eeca", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 26*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 27*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
};
//Number of terms : 10
FEqInfo EqsRes[10] = {
{"CDJR,IJ,RQ,CDIQ", -2.0 , 4, {21,2,13,20}}, //Ap[CDJR] += -2.0 f[IJ] E1[RQ] p[CDIQ]
{"CDJR,IJ,RQ,DCIQ", 1.0 , 4, {21,2,13,20}}, //Ap[CDJR] += 1.0 f[IJ] E1[RQ] p[DCIQ]
{"CDJR,AC,RQ,ADJQ", 2.0 , 4, {21,4,13,20}}, //Ap[CDJR] += 2.0 f[AC] E1[RQ] p[ADJQ]
{"CDJR,AD,RQ,ACJQ", -1.0 , 4, {21,4,13,20}}, //Ap[CDJR] += -1.0 f[AD] E1[RQ] p[ACJQ]
{"CDJR,BC,RQ,DBJQ", -1.0 , 4, {21,4,13,20}}, //Ap[CDJR] += -1.0 f[BC] E1[RQ] p[DBJQ]
{"CDJR,BD,RQ,CBJQ", 2.0 , 4, {21,4,13,20}}, //Ap[CDJR] += 2.0 f[BD] E1[RQ] p[CBJQ]
{"CDJR,Qa,Ra,CDJQ", -2.0 , 4, {21,3,13,20}}, //Ap[CDJR] += -2.0 f[Qa] E1[Ra] p[CDJQ]
{"CDJR,Qa,Ra,DCJQ", 1.0 , 4, {21,3,13,20}}, //Ap[CDJR] += 1.0 f[Qa] E1[Ra] p[DCJQ]
{"CDJR,Qabc,Rabc,CDJQ", -2.0 , 4, {21,12,14,20}}, //Ap[CDJR] += -2.0 W[Qabc] E2[Rabc] p[CDJQ]
{"CDJR,Qabc,Rabc,DCJQ", 1.0 , 4, {21,12,14,20}}, //Ap[CDJR] += 1.0 W[Qabc] E2[Rabc] p[DCJQ]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[2] = {
{"ABIP,RP,ABIR", 2.0, 3, {19, 13, 25}},
{"ABIP,RP,BAIR",-1.0, 3, {19, 13, 25}}
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "NEVPT2_ACVV";
Out.perturberClass = "ACVV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 29;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsRes = FEqSet(&EqsRes[0], 10, "NEVPT2_ACVV/Res");
Out.Overlap = FEqSet(&Overlap[0], 2, "NEVPT2_ACVV/Overlap");
};
};
<file_sep>#include <vector>
#include <Eigen/Dense>
#include "Wfn.h"
#include <algorithm>
#include "integral.h"
#include "Determinants.h"
#include "Walker.h"
#include <boost/format.hpp>
#include <iostream>
#include "evaluateE.h"
#include "Davidson.h"
#include "Hmult.h"
#include <math.h>
#include "global.h"
#include "input.h"
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace std;
using namespace Eigen;
/*
void getVarianceGradiantDeterministic(CPSSlater &w, double &E0, int &nalpha, int &nbeta, int &norbs,
oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb, double &coreE,
VectorXd &grad, double &var)
{
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
vector<double> HijElements;
int nExcitations;
double Overlap = 0, Energy = 0;
grad.setZero();
VectorXd diagonalGrad = VectorXd::Zero(grad.rows());
VectorXd localdiagonalGrad = VectorXd::Zero(grad.rows());
VectorXd localgrad = VectorXd::Zero(grad.rows());
double E2 = 0.;
VectorXd gradone = VectorXd::Zero(grad.rows());
VectorXd gradtwo = VectorXd::Zero(grad.rows());
VectorXd gradthree = VectorXd::Zero(grad.rows());
VectorXd gradfour = VectorXd::Zero(grad.rows());
for (int i = commrank; i < allDets.size(); i += commsize)
{
Walker walk(allDets[i]);
walk.initUsingWave(w);
double ovlp = 0, ham = 0;
{
E0 = 0.;
double scale = 1.0;
localgrad.setZero();
localdiagonalGrad.setZero();
gradone.setZero();
gradtwo.setZero();
gradthree.setZero();
gradfour.setZero();
w.HamAndOvlpGradient(walk, ovlp, ham, localgrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, true, true);
double tmpovlp = 1.0;
w.OverlapWithGradient(walk, tmpovlp, localdiagonalGrad);
double detovlp = walk.getDetOverlap(w);
for (int k=0; k<w.ciExpansion.size(); k++) {
localdiagonalGrad(k+w.getNumJastrowVariables()) += walk.alphaDet[k]*walk.betaDet[k]/detovlp;
}
if (w.determinants.size() <= 1 && schd.optimizeOrbs) {
walk.OverlapWithGradient(w, localdiagonalGrad, detovlp);
}
}
*/
void getStochasticVarianceGradientContinuousTime(CPSSlater &w, double &E0, double &stddev,
int &nalpha, int &nbeta, int &norbs, oneInt &I1,
twoInt &I2, twoIntHeatBathSHM &I2hb, double &coreE,
VectorXd &grad, double &var, double &rk, int niter,
double targetError)
{
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),std::ref(generator));
//initialize the walker
Determinant d;
bool readDeterminant = false;
char file [5000];
sprintf (file, "BestDeterminant.txt");
{
ifstream ofile(file);
if (ofile) readDeterminant = true;
}
if ( !readDeterminant )
{
for (int i =0; i<nalpha; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j=0; j<norbs; j++) {
if (abs(HforbsA(i,j)) > maxovlp && !d.getoccA(j)) {
maxovlp = abs(HforbsA(i,j));
bestorb = j;
}
}
d.setoccA(bestorb, true);
}
for (int i =0; i<nbeta; i++) {
int bestorb = 0;
double maxovlp = 0;
for (int j=0; j<norbs; j++) {
if (abs(HforbsB(i,j)) > maxovlp && !d.getoccB(j)) {
bestorb = j; maxovlp = abs(HforbsB(i,j));
}
}
d.setoccB(bestorb, true);
}
}
else {
if (commrank == 0) {
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> d;
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
Walker walk(d);
walk.initUsingWave(w);
int maxTerms = (nalpha) * (norbs-nalpha);
vector<double> ovlpRatio(maxTerms);
vector<size_t> excitation1( maxTerms), excitation2( maxTerms);
vector<double> HijElements(maxTerms);
int nExcitations = 0;
stddev = 1.e4;
int iter = 0;
double M1 = 0., S1 = 0., Eavg = 0.;
double Eloc = 0.;
double ham = 0., ovlp = 0.;
VectorXd localGrad = grad;
localGrad.setZero();
double scale = 1.0;
VectorXd diagonalGrad = VectorXd::Zero(grad.rows());
VectorXd localdiagonalGrad = VectorXd::Zero(grad.rows());
double bestOvlp =0.;
Determinant bestDet=d;
//new variables for variance
double Eloc2 = 0.;
VectorXd gradone = VectorXd::Zero(grad.rows());
VectorXd gradtwo = VectorXd::Zero(grad.rows());
VectorXd gradthree = VectorXd::Zero(grad.rows());
VectorXd gradfour = VectorXd::Zero(grad.rows());
//find the best determinant at overlap
if (!readDeterminant) {
for (int i=0; i<0; i++) {
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio, excitation1, excitation2, HijElements, nExcitations, true, true);
int bestDet = 0;
double bestOvlp = 0.;
for (int j=0; j<nExcitations; j++) {
if (abs(ovlpRatio[j]) > bestOvlp) {
bestOvlp = abs(ovlpRatio[j]);
bestDet = j;
}
}
int I = excitation1[bestDet] / 2/ norbs, A = excitation1[bestDet] - 2 * norbs * I;
if (I % 2 == 0)
walk.updateA(I / 2, A / 2, w);
else
walk.updateB(I / 2, A / 2, w);
if (excitation2[bestDet] != 0) {
int J = excitation2[bestDet] / 2 / norbs, B = excitation2[bestDet] - 2 * norbs * J;
if (J %2 == 1){
walk.updateB(J / 2, B / 2, w);
}
else {
walk.updateA(J / 2, B / 2, w);
}
}
nExcitations = 0;
}
walk.initUsingWave(w, true);
}
nExcitations = 0;
E0 = 0.0;
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, true, true);
w.OverlapWithGradient(walk, scale, localdiagonalGrad);
for (int k = 0; k < w.ciExpansion.size(); k++)
{
localdiagonalGrad(k + w.getNumJastrowVariables()) += walk.alphaDet[k] * walk.betaDet[k]/ovlp;
}
//localGrad = localdiagonalGrad * ham ;
//we wanto 100000 steps
int nstore = 1000000/commsize;
int gradIter = min(nstore, niter);
std::vector<double> gradError(gradIter*commsize, 0);
bool reset = true;
double cumdeltaT = 0., cumdeltaT2 = 0.;
int reset_len = readDeterminant ? 1 : 10*norbs;
while (iter < niter && stddev > targetError)
{
if (iter == reset_len && reset)
{
iter = 0;
reset = false;
M1 = 0.;
S1 = 0.;
Eloc = 0;
grad.setZero();
diagonalGrad.setZero();
walk.initUsingWave(w, true);
cumdeltaT = 0.;
cumdeltaT2 = 0;
Eloc2 = 0.;
gradone.setZero();
gradtwo.setZero();
gradthree.setZero();
gradfour.setZero();
}
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < nExcitations; i++)
{
cumovlpRatio += abs(ovlpRatio[i]);
//cumovlpRatio += min(1.0, pow(ovlpRatio[i], 2));
ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random()*cumovlpRatio;
int nextDet = std::lower_bound(ovlpRatio.begin(), (ovlpRatio.begin()+nExcitations),
nextDetRandom) - ovlpRatio.begin();
cumdeltaT += deltaT;
cumdeltaT2 += deltaT * deltaT;
double Elocold = Eloc;
double ratio = deltaT/cumdeltaT;
for (int i=0; i<grad.rows(); i++) {
gradone(i) += ratio * ( (ham * localGrad(i)) - gradone(i));
gradtwo(i) += ratio * ( (ham * ham * localdiagonalGrad(i)) - gradtwo(i));
gradthree(i) += ratio * ( localGrad(i) - gradthree(i));
gradfour(i) += ratio * ( (ham * localdiagonalGrad(i)) - gradfour(i));
localdiagonalGrad[i] = 0.0;
localGrad(i) = 0.0;
}
Eloc = Eloc + deltaT * (ham - Eloc) / (cumdeltaT); //running average of energy
S1 = S1 + (ham - Elocold) * (ham - Eloc);
Eloc2 = Eloc2 + ratio * ( (ham * ham) - Eloc2);
if (iter < gradIter)
gradError[iter + commrank*gradIter] = ham;
iter++;
//update walker
if (true)
{
int I = excitation1[nextDet] / 2 / norbs, A = excitation1[nextDet] - 2 * norbs * I;
int J = excitation2[nextDet] / 2 / norbs, B = excitation2[nextDet] - 2 * norbs * J;
if (I % 2 == J % 2 && excitation2[nextDet] != 0)
{
if (I % 2 == 1) {
walk.updateB(I / 2, J / 2, A / 2, B / 2, w);
}
else {
walk.updateA(I / 2, J / 2, A / 2, B / 2, w);
}
}
else
{
if (I % 2 == 0)
walk.updateA(I / 2, A / 2, w);
else
walk.updateB(I / 2, A / 2, w);
if (excitation2[nextDet] != 0)
{
if (J % 2 == 1)
{
walk.updateB(J / 2, B / 2, w);
}
else
{
walk.updateA(J / 2, B / 2, w);
}
}
}
}
nExcitations = 0;
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, true, true);
w.OverlapWithGradient(walk.d, scale, localdiagonalGrad);
double detovlp=0;
for (int k = 0; k < w.ciExpansion.size(); k++)
{
localdiagonalGrad(k + w.getNumJastrowVariables()) += walk.alphaDet[k] * walk.betaDet[k]/ovlp;
detovlp += w.ciExpansion[k]*walk.alphaDet[k] * walk.betaDet[k];
}
if (w.determinants.size() <= 1 && schd.optimizeOrbs) {
walk.OverlapWithGradient(w, localdiagonalGrad, detovlp);
}
if (abs(ovlp) > bestOvlp) {
bestOvlp = abs(ovlp);
bestDet = walk.d;
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(gradError[0]), gradError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(diagonalGrad[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradone[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradtwo[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradthree[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradfour[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
//if (commrank == 0) { std::cout << "I work up to here " << Eloc << std::endl; }
MPI_Allreduce(MPI_IN_PLACE, &Eloc, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
//if (commrank == 0) { std::cout << "hello" << std::endl; }
MPI_Allreduce(MPI_IN_PLACE, &Eloc2, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
rk = calcTcorr(gradError);
diagonalGrad /= (commsize);
gradone /= (commsize);
gradtwo /= (commsize);
gradthree /= (commsize);
gradfour /= (commsize);
Eloc2 /= (commsize);
E0 = Eloc / commsize;
stddev = sqrt(S1 * rk / (niter - 1) / niter / commsize);
var = Eloc2 - (E0 * E0);
grad = 2.0 * ( gradone - gradtwo + E0 * (gradfour - gradthree));
#ifndef SERIAL
MPI_Bcast(&stddev, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0) {
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << bestDet;
}
}
<file_sep>#pragma once
#include <vector>
#include <iostream>
using namespace std;
struct tensor {
vector<int> dimensions;
double* vals;
vector<double> values;
vector<int> strides;
tensor(vector<int> pdimensions)
{
int n = pdimensions.size();
dimensions.resize(n);
strides.resize(n);
int size = 1.;
for (int i=0; i<n; i++) {
dimensions[i] = pdimensions[i];
strides[n-1-i] = i == 0 ? 1 : strides[n-i] * pdimensions[i-1];
size *= dimensions[i];
}
values.resize(size);
vals = &values[0];
}
tensor(vector<int> pdimensions, double* pvals)
{
int n = pdimensions.size();
dimensions.resize(n);
vals = pvals;
}
double& operator()(int i) {
return vals[i];
}
double& operator()(int i, int j) {
return vals[i*dimensions[1]+j];
}
double& operator()(int i, int j, int k) {
return vals[ (i*dimensions[1]+j)*dimensions[2]+k];
}
double& operator()(int i, int j, int k, int l) {
return vals[ ((i*dimensions[1]+j)*dimensions[2]+k)*dimensions[3]+l];
}
const double& operator()(int i) const {
return vals[i];
}
const double& operator()(int i, int j) const {
return vals[i*dimensions[1]+j];
}
const double& operator()(int i, int j, int k) const {
return vals[ (i*dimensions[1]+j)*dimensions[2]+k];
}
const double& operator()(int i, int j, int k, int l) const {
return vals[ ((i*dimensions[1]+j)*dimensions[2]+k)*dimensions[3]+l];
}
void setZero() {
int size = 1;
for (int i=0; i<dimensions.size(); i++)
size *= dimensions[i];
for (int i=0; i<size; i++)
vals[i] = 0.0;
}
};
int contract_IJK_IJL_LK(tensor *O, tensor *C, tensor *S, double scale=1.0, double beta=0.);
<file_sep>#include "statistics.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include "global.h"
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace std;
//random calcTcorr function, idk who wrote this it's pretty rough
double calcTcorr(vector<double> &v)
{
//vector<double> w(v.size(), 1);
int n = v.size();
double norm, rk, f, neff;
double aver = 0, var = 0;
for (int i = 0; i < v.size(); i++)
{
aver += v[i] ;
norm += 1.0 ;
}
aver = aver / norm;
neff = 0.0;
for (int i = 0; i < n; i++)
{
neff = neff + 1.0;
};
neff = norm * norm / neff;
for (int i = 0; i < v.size(); i++)
{
var = var + (v[i] - aver) * (v[i] - aver);
};
var = var / norm;
var = var * neff / (neff - 1.0);
//double c[v.size()];
vector<double> c(v.size(),0);
//for (int i=0; i<v.size(); i++) c[i] = 0.0;
int l = v.size() - 1;
int i = commrank+1;
for (; i < l; i+=commsize)
//int i = 1;
//for (; i < l; i++)
{
c[i] = 0.0;
double norm = 0.0;
for (int k = 0; k < n - i; k++)
{
c[i] = c[i] + (v[k] - aver) * (v[k + i] - aver);
norm = norm + 1.0;
};
c[i] = c[i] / norm / var;
};
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &c[0], v.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
rk = 1.0;
f = 1.0;
i = 1;
ofstream out("OldCorrFunc.txt");
for (; i < l; i++)
{
if (commrank == 0)
{
out << c[i] << endl;
}
if (c[i] < 0.0)
f = 0.0;
rk = rk + 2.0 * c[i] * f;
}
out.close();
return rk;
}
//various functions for calculating statistics of serially correlated data, functions overloaded for weighted and unweighted data sets
//average function
double average(vector<double> &x, vector<double> &w)
{
double x_bar = 0.0, W = 0.0;
int n = x.size();
for (int i = 0; i < n; i++)
{
x_bar += w[i] * x[i];
W += w[i];
}
x_bar /= W;
return x_bar;
}
double average(vector<double> &x)
{
vector<double> w(x.size(), 1.0);
return average(x, w);
}
//calculates effective sample size for weighted data sets. For unweighted data, will just return the size of the data set
double neff(vector<double> &w)
{
double n_eff, W = 0.0, W_2 = 0.0;
int n = w.size();
for (int i = 0; i < n; i++)
{
W += w[i];
W_2 += w[i] * w[i];
}
n_eff = (W * W) / W_2;
return n_eff;
}
//variance function, takes advantage of bessel's correction
double variance(vector<double> &x, vector<double> &w)
{
double x_bar = 0.0, x_bar_2 = 0.0, n_eff, W = 0.0, W_2 = 0.0;
int n = x.size();
for (int i = 0; i < n; i++)
{
x_bar += w[i] * x[i];
x_bar_2 += w[i] * x[i] * x[i];
W += w[i];
W_2 += w[i] * w[i];
}
x_bar /= W;
x_bar_2 /= W;
n_eff = (W * W) / W_2;
double s_2, var;
s_2 = x_bar_2 - x_bar * x_bar;
var = (s_2 * n_eff) / (n_eff - 1.0);
return var;
}
double variance(vector<double> &x)
{
vector<double> w(x.size(), 1.0);
return variance(x, w);
}
//correlation function: given a weighted/unweighted data set, calculates C(t) = <(x(i)-x_bar)(x(i+t)-x_bar)> / <(x(i)-x_bar)^2>
//Input: x, w if weighted; x if unweighted
//Output: c
void corrFunc(vector<double> &c, vector<double> &x, vector<double> &w)
{
double x_bar = average(x,w);
double var = variance(x,w);
int n = x.size();
int l = min(n - 1, 1000);
double norm;
c.assign(l, 0.0);
c[0] = 1.0;
for (int t = 1; t < l; t++)
{
norm = 0.0;
for (int i = 0; i < n - t; i++)
{
c[t] += sqrt(w[i] * w[i+t]) * (x[i] - x_bar) * (x[i+t] - x_bar);
norm += sqrt(w[i] * w[i+t]);
}
c[t] /= norm;
c[t] /= var;
}
}
void corrFunc(vector<double> &c, vector<double> &x)
{
vector<double> w(x.size(), 1.0);
corrFunc(c, x, w);
}
//autocorrelation time: given correlation function, calculates autocorrelation time: t = 1 + 2 \sum C(i)
double corrTime(vector<double> &c)
{
double t = 1.0;
for (int i = 1; i < c.size(); i++)
{
if (c[i] < 0.0 || c[i] < 0.01)
{
break;
}
t += 2 * c[i];
}
return t;
}
//writes correlation function to text file
void writeCorrFunc(vector<double> &c)
{
ofstream ofile("CorrFunc.txt");
for (int i = 0; i < c.size(); i++)
{
ofile << i << "\t" << c[i] << endl;
}
ofile.close();
}
//blocking function, given a wighted or unweighted data set, calculates autocorrelation time vs. block size
//Input: x, w if weighted; x if unweighted
//Output: b_size - block size per iteration, r_t - autocorrelation time per iteration
void block(vector<double> &b_size, vector<double> &r_t, vector<double> &x, vector<double> &w)
{
b_size.clear();
r_t.clear();
double var = variance(x,w);
vector<double> x_0, x_1, w_0, w_1;
x_0 = x;
w_0 = w;
int N, n_0, n_1;
double b_var, b_size_tok;
N = x.size();
for (int iter = 0; iter < 40; iter++)
{
b_size_tok = pow(2.0, (double)iter);
if (b_size_tok > (N / 2))
{
break;
}
b_var = variance(x_0,w_0);
b_size.push_back(b_size_tok);
r_t.push_back((b_size_tok * b_var) / var);
n_0 = x_0.size();
n_1 = floor(n_0 / 2);
x_1.assign(n_1, 0.0);
w_1.assign(n_1, 0.0);
for (int i = 0; i < n_1; i++)
{
w_1[i] = w_0[2*i] + w_0[(2*i)+1];
x_1[i] = w_0[2*i] * x_0[2*i] + w_0[(2*i)+1] * x_0[(2*i)+1];
x_1[i] /= w_1[i];
}
x_0 = x_1;
w_0 = w_1;
}
}
void block(vector<double> &b_size, vector<double> &r_t, vector<double> &x)
{
vector<double> w(x.size(), 1.0);
block(b_size, r_t, x, w);
}
//autocorrelation time: given blocking data, finds autocorrelation time based on the criteria: (block size)^3 > 2 * (number of original data points) * (autocorrelation time)^2
double corrTime(double n_original, vector<double> &b_size, vector<double> &r_t)
{
double t = 0.0;
for (int i = 0; i < r_t.size(); i++)
{
double B = b_size[i] * b_size[i] * b_size[i];
double C = 2 * n_original * (r_t[i] * r_t[i]);
if (B > C)
{
t = r_t[i];
break;
}
}
if (t == 0.0)
{
//throw runtime_error("Insufficient number of stochastic iterations");
t = 1.;
}
if (t < 1.0)
{
t = 1.0;
}
return t;
}
//writes blocking data to file
void writeBlock(vector<double> &b_size, vector<double> &r_t)
{
ofstream ofile("Block.txt");
for (int i = 0; i < r_t.size(); i++)
{
ofile << b_size[i] << "\t" << r_t[i] << endl;
}
ofile.close();
}
<file_sep>##########################
# User Specific Settings #
##########################
CXX = icpc
EIGEN=/home/sash2458/newApps/eigen/
#MKLLIB = /curc/sw/intel/16.0.3/mkl/lib/intel64/
FLAGS = -O3 -std=c++17 -g -qopenmp -I${EIGEN} #-I/curc/sw/intel/16.0.3/mkl/include/
OBJ = test.o primitives.o Integral2c.o workArray.o Integral3c.o coulomb_14_8_8.o coulomb_14_14_8.o tensor.o
LIBOBJ = primitives.o Integral2c.o workArray.o Integral3c.o coulomb_14_8_8.o coulomb_14_14_8.o tensor.o interface.o
%.o: %.cpp
$(CXX) $(FLAGS) $(OPT) -fPIC -c $< -o $@
all: a.out libseparated.so
a.out: $(OBJ)
$(CXX) $(FLAGS) $(OBJ) -o a.out #-L${MKLLIB} -lmkl_gf_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lrt
libseparated.so: $(LIBOBJ)
$(CXX) $(FLAGS) $(LIBOBJ) -shared -o libseparated.so
clean :
find . -name "*.o"|xargs rm 2>/dev/null
<file_sep>#!/bin/bash
printf "\n\nRunning Tests for VMC/GFMC/NEVPT2/FCIQMC\n"
printf "======================================================\n"
MPICOMMAND="mpirun -np 4"
VMCPATH="../../bin/VMC vmc.json"
CIPATH="../../bin/VMC ci.json"
LANCZOSPATH="../../bin/VMC lanczos.dat"
GFMCPATH="../../bin/GFMC gfmc.json"
NEVPTPATH="../../../../bin/VMC nevpt.json"
NEVPTPRINTPATH="../../../../bin/VMC nevpt_print.json"
NEVPTREADPATH="../../../../bin/VMC nevpt_read.json"
FCIQMCPATH="../../../bin/FCIQMC fciqmc.json"
here=`pwd`
tol=1.0e-7
clean=0
# VMC tests
cd $here/hubbard_1x10
../clean.sh
printf "...running hubbard_1x10\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
#printf "...running hubbard_1x10 lanczos\n"
#$MPICOMMAND $LANCZOSPATH > lanczos.out
#python2 ../testEnergy.py 'lanczos' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/hubbard_1x10ghf
../clean.sh
printf "...running hubbard_1x10 ghf\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/hubbard_1x10agp
../clean.sh
printf "...running hubbard_1x10 agp\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/hubbard_1x14
../clean.sh
printf "...running hubbard_1x14\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
printf "...running hubbard_1x14 ci\n"
$MPICOMMAND $CIPATH > ci.out
python2 ../testEnergy.py 'ci' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/hubbard_1x22
../clean.sh
printf "...running hubbard_1x22\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/hubbard_1x50
../clean.sh
printf "...running hubbard_1x50\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/hubbard_1x6
../clean.sh
printf "...running hubbard_1x6\n"
$VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/hubbard_18_tilt/
../clean.sh
printf "...running hubbard_18_tilt uhf\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
printf "...running hubbard_18_tilt gfmc\n"
$MPICOMMAND $GFMCPATH > gfmc.out
python2 ../testEnergy.py 'gfmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
#cd $here/h6/
#../clean.sh
#printf "...running h6\n"
#$MPICOMMAND $VMCPATH > vmc.out
#python2 ../testEnergy.py 'vmc' $tol
#if [ $clean == 1 ]
#then
# ../clean.sh
#fi
cd $here/h4_ghf_complex/
../clean.sh
printf "...running h4 ghf complex\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/h4_pfaffian_complex/
../clean.sh
printf "...running h4 pfaffian complex\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
#cd $here/h10sr/
#../clean.sh
#printf "...running h10 sr\n"
#$MPICOMMAND $VMCPATH > vmc.out
#python2 ../testEnergy.py 'vmc' $tol
#if [ $clean == 1 ]
#then
# ../clean.sh
#fi
cd $here/h10pfaff/
../clean.sh
printf "...running h10 pfaffian\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/h20/
../clean.sh
printf "...running h20\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/h20ghf/
../clean.sh
printf "...running h20 ghf\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
cd $here/c2/
../clean.sh
printf "...running c2\n"
$MPICOMMAND $VMCPATH > vmc.out
python2 ../testEnergy.py 'vmc' $tol
if [ $clean == 1 ]
then
../clean.sh
fi
# SC-NEVPT2 tests
cd $here/NEVPT2/n2_vdz/stoch
../../../clean.sh
printf "...running NEVPT2/n2_vdz/stoch\n"
$MPICOMMAND $NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'nevpt' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/n2_vdz/continue_norms
../../../clean_wo_bkp.sh
printf "...running NEVPT2/n2_vdz/continue_norms PRINT\n"
$MPICOMMAND $NEVPTPRINTPATH > nevpt_print.out
python2 ../../../testEnergy.py 'nevpt_print' $tol
if [ $clean == 1 ]
then
../../../clean_wo_bkp.sh
fi
cd $here/NEVPT2/n2_vdz/continue_norms
../../../clean_wo_bkp.sh
printf "...running NEVPT2/n2_vdz/continue_norms READ\n"
$MPICOMMAND $NEVPTREADPATH > nevpt_read.out
python2 ../../../testEnergy.py 'nevpt_read' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/n2_vdz/exact_energies
../../../clean.sh
printf "...running NEVPT2/n2_vdz/exact_energies PRINT\n"
$NEVPTPRINTPATH > nevpt_print.out
python2 ../../../testEnergy.py 'nevpt_print' $tol
if [ $clean == 1 ]
then
../../../clean_wo_bkp.sh
fi
cd $here/NEVPT2/n2_vdz/exact_energies
../../../clean_wo_bkp.sh
printf "...running NEVPT2/n2_vdz/exact_energies READ\n"
$NEVPTREADPATH > nevpt_read.out
python2 ../../../testEnergy.py 'nevpt_read' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/h4_631g/determ
../../../clean.sh
printf "...running NEVPT2/h4_631g/determ\n"
$MPICOMMAND $NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'nevpt' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/polyacetylene/stoch
../../../clean.sh
printf "...running NEVPT2/polyacetylene/stoch\n"
$MPICOMMAND $NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'nevpt' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
# SC-NEVPT2 single perturber
cd $here/NEVPT2/n2_vdz/single_perturber
../../../clean.sh
printf "...running NEVPT2/n2_vdz/single_perturber\n"
$NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'single_perturber' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/FCIQMC/He2
../../clean.sh
printf "...running FCIQMC/He2\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/He2_hb_uniform
../../clean.sh
printf "...running FCIQMC/He2_hb_uniform\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_plateau
../../clean.sh
printf "...running FCIQMC/Ne_plateau\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator
../../clean.sh
printf "...running FCIQMC/Ne_initiator\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator_replica
../../clean.sh
printf "...running FCIQMC/Ne_initiator_replica\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_replica' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator_en2
../../clean.sh
printf "...running FCIQMC/Ne_initiator_en2\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_replica' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator_en2_ss
../../clean.sh
printf "...running FCIQMC/Ne_initiator_en2_ss\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_replica' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/water_vdz_hb
../../clean.sh
printf "...running FCIQMC/water_vdz_hb\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/N2_fixed_node
../../clean.sh
printf "...running FCIQMC/N2_fixed_node\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/N2_is_ss
../../clean.sh
printf "...running FCIQMC/N2_is_ss\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/H10_free_prop
../../clean.sh
printf "...running FCIQMC/H10_free_prop\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/H10_partial_node
../../clean.sh
printf "...running FCIQMC/H10_partial_node\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#include <stdexcept>
#include <sstream>
#include <new>
#ifdef _DEBUG
#include <stdio.h> // for printf and fflush
#endif
#include "CxMemoryStack.h"
#include "CxDefs.h"
#include "CxOpenMpProxy.h"
namespace ct {
inline void FMemoryStack2::PushTopMark() {
#ifdef _DEBUG
assert(m_Pos < m_Size - 8);
*reinterpret_cast<size_t*>(&m_pData[m_Pos]) = 0xbadc0de;
m_Pos += sizeof(size_t);
#endif
}
inline void FMemoryStack2::PopTopMark() {
#ifdef _DEBUG
m_Pos -= sizeof(size_t);
assert(m_Pos < m_Size - 8);
if ( *reinterpret_cast<size_t*>(&m_pData[m_Pos]) != 0xbadc0de ) {
printf("\n\n\n===================\nstack inconsistent!\n===================\n");
assert(!"stack error");
}
#endif
}
void* FMemoryStack2::Alloc( size_t nSizeInBytes )
{
PopTopMark();
std::size_t OldPos = m_Pos;
m_Pos += nSizeInBytes;
PushTopMark();
if ( m_Pos >= m_Size )
throw std::runtime_error("FMemoryStack2: Stack size exceeded.");
return &m_pData[OldPos];
}
void FMemoryStack2::Free( void *p )
{
PopTopMark();
std::ptrdiff_t
n = &m_pData[m_Pos] - (char*)p;
if ( n < 0 )
throw std::runtime_error("FMemoryStack2: Release address too low!");
m_Pos -= n;
PushTopMark();
}
size_t FMemoryStack2::MemoryLeft() {
return m_Size - m_Pos;
}
FMemoryStack2::FMemoryStack2( char *pBase, std::size_t nActualSize, std::size_t nNeededSize )
: m_pData(0)
{
if (pBase && nActualSize >= nNeededSize)
AssignMemory(pBase, nActualSize);
else
Create((nNeededSize != 0)? nNeededSize : nActualSize);
}
void FMemoryStack2::Create( std::size_t nSize )
{
//assert_rt(m_pData == 0);
m_Size = nSize;
m_Pos = 0;
m_pData = 0;
m_bOwnMemory = false;
if ( nSize != 0 ) {
m_pData = new(std::nothrow) char[nSize];
m_bOwnMemory = true;
if ( m_pData == 0 ) {
std::stringstream str; str.precision(2); str.setf(std::ios::fixed);
str << "FMemoryStack2: Sorry, failed to allocate " << nSize/1e6 << " MB of memory.";
throw std::runtime_error(str.str());
}
PushTopMark();
}
}
void FMemoryStack2::AssignMemory( char *pBase_, std::size_t nSize )
{
assert(m_pData == 0 && pBase_ != 0);
Create(0);
m_bOwnMemory = false;
m_pData = pBase_;
m_Size = nSize;
m_Pos = 0;
PushTopMark();
}
void FMemoryStack2::Destroy()
{
#ifdef _DEBUG
if ( m_Size != 0 )
PopTopMark();
else
assert(m_pData == 0);
assert(m_Pos == 0);
#endif // _DEBUG
if ( m_bOwnMemory )
delete []m_pData;
m_pData = 0;
}
FMemoryStack::~FMemoryStack()
{
}
FMemoryStack2::~FMemoryStack2()
{
if ( m_bOwnMemory )
delete []m_pData;
m_pData = (char*)0xbadc0de;
}
void FMemoryStack::Align( uint Boundary )
{
std::size_t
iPos = reinterpret_cast<std::size_t>(Alloc(0)),
iNew = ((iPos - 1) | (Boundary - 1)) + 1;
Alloc(iNew - iPos);
}
FMemoryStackArray::FMemoryStackArray( FMemoryStack &BaseStack )
: pBaseStack(&BaseStack)
{
nThreads = omp_get_max_threads();
pSubStacks = new FMemoryStack2[nThreads];
std::size_t
nSize = static_cast<std::size_t>(0.98 * (pBaseStack->MemoryLeft() / nThreads));
pBaseStack->Alloc(pStackBase, nThreads * nSize);
for ( std::size_t i = 0; i < nThreads; ++ i )
pSubStacks[i].AssignMemory(pStackBase + i * nSize, nSize);
};
void FMemoryStackArray::Release()
{
assert(pBaseStack != 0);
delete []pSubStacks;
pBaseStack->Free(pStackBase);
pStackBase = 0;
pBaseStack = 0;
}
FMemoryStackArray::~FMemoryStackArray()
{
if ( pBaseStack )
Release();
};
FMemoryStack2 &FMemoryStackArray::GetStackOfThread()
{
int iThread = omp_get_thread_num();
assert(iThread < (int)nThreads);
return pSubStacks[iThread];
};
} // namespace ct
// kate: indent-width 4
<file_sep>#include <cmath>
#include <iostream>
#include "Kernel.h"
#include "IrBoysFn.h"
using namespace std;
using namespace ir;
void CoulombKernel::getValueRSpace(double* pFmT, double T, int L, double factor, double rho,
double eta, ct::FMemoryStack& Mem) {
IrBoysFn(pFmT, T, L, factor*(2*M_PI)/rho);
double* pFmtOmega;
Mem.Alloc(pFmtOmega, L+1);
IrBoysFn(pFmtOmega, eta*eta*T, L, factor*(2*M_PI)/rho);
double etaPow = eta;
for (int i=0; i<L+1; i++) {
pFmT[i] -= pFmtOmega[i] * etaPow;
etaPow *= eta * eta;
}
//cout << rho<<" "<<eta<<" "<<pFmT[0]<<" "<<pFmtOmega[0]<<endl;
Mem.Free(pFmtOmega);
}
inline double CoulombKernel::getValueKSpace(double Gsq, double factor, double rho){
return exp(-Gsq/rho/4.0)/(Gsq/4) * factor;
}
void OverlapKernel::getValueRSpace(double* pFmT, double T, int L, double factor, double rho,
double eta, ct::FMemoryStack& Mem) {
double val = exp(-T)*factor;// * pow(M_PI/rho, 1.5);
for (int i=0; i<L+1; i++) {
pFmT[i] = val;
}
}
inline double OverlapKernel::getValueKSpace(double Gsq, double factor, double rho) {
return exp(-Gsq/rho/4.0) * factor;
}
void KineticKernel::getValueRSpace(double* pFmT, double T, int L, double factor, double rho,
double eta, ct::FMemoryStack& Mem) {
double val = -0.5*exp(-T)*factor;// * pow(M_PI/rho, 1.5);
//double val = -0.5*exp(-T)*(-6*rho + 4*T)*factor;
for (int i=0; i<L+1; i++) {
pFmT[i] = val;
}
}
inline double KineticKernel::getValueKSpace(double Gsq, double factor, double rho) {
return 0.5*exp(-Gsq/rho/4.0) * Gsq * factor;
}
<file_sep>/* Copyright (c) 2012 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bfint (LICENSE). If not, see http://www.gnu.org/licenses/
*/
#ifndef _CX_MEMORYSTACK_H
#define _CX_MEMORYSTACK_H
#include <stddef.h> // for size_t
#include <string.h> // for memset
#include <omp.h>
typedef unsigned int
uint;
namespace ct {
#define CX_DEFAULT_MEM_ALIGN 64 // align to 64 bytes.
// note: boundary must be size-of-2
inline size_t AlignSizeT(size_t iPos, size_t Boundary) {
size_t
iNew = ((iPos - 1) | (Boundary - 1)) + 1;
return iNew;
}
/// An object managing a continuous block of memory. Used for allocation-free
/// temporary work space storage.
/// Notes:
/// - Deallocations must occur in reverse allocation order. A deallocation
/// FREES ALL MEMORY ALLOCATED AFTER THE ALLOCATION POINT.
/// - Both alloc and free are effectively non-ops in terms of computational
/// cost. Any work space, no matter how large or small, can be allocated
/// at will.
/// - There is no memory fragmentation.
struct FMemoryStack
{
/// allocate nSizeInBytes bytes off the stack. Return pointer to start.
virtual void* Alloc(size_t nSizeInBytes) = 0;
/// Free pointer p on stack. Should be an address returned by Alloc.
virtual void Free(void *p) = 0;
/// return amount of memory left (in bytes).
virtual size_t MemoryLeft() = 0;
/// allocate nObjects objects of size sizeof(T). Store pointer in p.
/// Usage:
/// MyType *p;
/// Mem.Alloc(p, 10); // allocate array of 10 objects of type MyType.
template<class T>
inline void Alloc(T *&p, size_t nObjects = 1){
p = reinterpret_cast<T*>( this->Alloc(sizeof(T) * nObjects) );
// note: objects are not constructed. Use only for PODs!
}
/// as Alloc(), but set allocated memory to zero.
template<class T>
inline void ClearAlloc(T *&p, size_t nObjects = 1){
Alloc(p, nObjects);
::memset(p, 0, sizeof(T) * nObjects);
}
template<class T>
inline T* AllocN(size_t nObjects, T const &){
return reinterpret_cast<T*>( this->Alloc(sizeof(T) * nObjects) );
}
template<class T>
inline T* ClearAllocN(size_t nObjects, T const &){
T *p;
this->Alloc(p, nObjects);
::memset(p, 0, sizeof(T) * nObjects);
return p;
}
/// align stack to next 'Boundary' (must be power of two)-boundary .
virtual void Align(uint Boundary);
virtual ~FMemoryStack();
};
/// A memory stack defined by a base pointer and a size. Can own
/// the memory managed, but can also be put on memory allocated from
/// elsewhere.
struct FMemoryStack2 : public FMemoryStack {
/// creates a stack of 'nInitialSize' bytes on the global heap.
/// If nInitialSize is 0, the stack is created empty and a storage
/// area can be later assigned by AssignMemory() or Create().
explicit FMemoryStack2(size_t nInitialSize = 0) : m_pDataStart(0), m_pDataAligned(0) { Create(nInitialSize); }
/// if pBase != 0 && nActualSize >= nNeededSize:
/// creates a stack of 'nActualSize' bytes at memory pBase (i.e., at a memory location given from the outside)
/// otherwise
/// construction equivalent to FMemoryStack2((nNeededSize != 0)? nNeededSize : nActualSize).
FMemoryStack2(char *pBase, size_t nActualSize, size_t nNeededSize = 0);
inline void PushTopMark();
inline void PopTopMark();
void* Alloc(size_t nSizeInBytes); // override
using FMemoryStack::Alloc;
void Free(void *p); // override
size_t MemoryLeft(); // override
~FMemoryStack2(); // override
/// create a new stack of size 'nSize' bytes on the global heap.
void Create( size_t nSize );
/// create a new stack in the storage area marked by 'pBase',
/// of 'nSize' bytes. This assumes that pBase is already allocated
/// from elsewhere.
void AssignMemory(char *pBase_, size_t nSize);
void Destroy();
void Align(uint Boundary); // override
private:
size_t
m_Pos, m_Size;
char
*m_pDataStart,
*m_pDataAligned; // next default-aligned address beyond m_pDataStart.
void DefaultAlign();
bool m_bOwnMemory; // if true, we allocated m_pData and need to free it on Destroy().
private:
FMemoryStack2(FMemoryStack2 const &); // not implemented
void operator = (FMemoryStack2 const &); // not implemented
};
// allocate a block of memory from pMem, and free it when the object goes out of scope.
template<class FType>
struct TMemoryLock
{
FType
*p; // pointer to allocated data
// allocate nCount objects from pMem, and store the pointer in this->p
inline TMemoryLock(size_t nCount, FMemoryStack *pMem);
// allocate nCount objects from pMem, and store the pointer in this->p and pOutsidePtr.
inline TMemoryLock(FType *&pOutsidePtr, size_t nCount, FMemoryStack *pMem);
inline ~TMemoryLock();
operator FType* () { return p; }
operator FType const* () const { return p; }
inline FType* data() { return p; }
inline FType const* data() const { return p; }
FMemoryStack
*m_pMemoryStack;
};
template<class FType>
TMemoryLock<FType>::TMemoryLock(size_t nCount, FMemoryStack *pMem)
{
m_pMemoryStack = pMem;
m_pMemoryStack->Alloc(p, nCount);
}
template<class FType>
TMemoryLock<FType>::TMemoryLock(FType *&pOutsidePtr, size_t nCount, FMemoryStack *pMem)
{
m_pMemoryStack = pMem;
m_pMemoryStack->Alloc(p, nCount);
pOutsidePtr = p;
}
template<class FType>
TMemoryLock<FType>::~TMemoryLock()
{
m_pMemoryStack->Free(p);
p = 0;
}
/// split a base memory stack into sub-stacks, one for each openmp thread.
struct FMemoryStackArray
{
explicit FMemoryStackArray(FMemoryStack &BaseStack);
~FMemoryStackArray();
FMemoryStack2
*pSubStacks;
FMemoryStack
*pBaseStack;
uint
nThreads;
// return substack for the calling openmp thread.
FMemoryStack2 &GetStackOfThread();
// destroy this object (explicitly) already now
void Release();
char
*pStackBase;
private:
FMemoryStackArray(FMemoryStackArray const &); // not implemented
void operator = (FMemoryStackArray const &); // not implemented
};
enum FOmpAccBlockFlags {
OMPACC_ClearTarget = 0x01
};
struct FOmpAccBlock
{
double *pTls(); // return thread-local block of the storage. Must be called from within parallel block.
void Join(); // copy to target by summation; must be called OUTSIDE of parallel block.
// allocate and clear thread-local storage for all threads. Must be called OUTSIDE of parallel block.
void Init(double *pTarget, size_t nSize, unsigned Flags, FMemoryStack &Mem);
FOmpAccBlock() : m_pTarget(0), m_pTlsData(0), m_nSize(0), m_Flags(0) {};
FOmpAccBlock(double *pTarget_, size_t nSize_, unsigned Flags_, FMemoryStack &Mem_) : m_pTarget(0), m_pTlsData(0), m_nSize(0), m_Flags(Flags_) { Init(pTarget_, nSize_, Flags_, Mem_); }
protected:
double
*m_pTarget,
*m_pTlsData; // m_nAlignedSize * m_nThreads
size_t
m_nSize,
m_nAlignedSize,
m_nThreads;
unsigned
m_Flags;
size_t nScalarBlockSize() const { return 128; }
size_t nTotalSize() const { return m_nAlignedSize * m_nThreads; }
// size_t nScalarBlocksTotal() const { return nTotalSize() / nScalarBlockSize(); }
size_t nScalarBlocks(size_t nSize) { return (nSize + nScalarBlockSize() - 1)/nScalarBlockSize(); }
};
} // namespace ct
#endif // _CX_MEMORYSTACK_H
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef walkersFCIQMC_HEADER_H
#define walkersFCIQMC_HEADER_H
#include <iostream>
#include <vector>
#include <unordered_map>
#include "Determinants.h"
#include "dataFCIQMC.h"
class Determinant;
void stochastic_round(const double minPop, double& amp, bool& roundedUp);
template <typename T>
T** allocateAmpsArray(const int nrows, const int ncols, const T& init = T())
{
// array to hold pointers to the first elements for each row
T** amps = nullptr;
// a single block of contiguous memory
T* pool = nullptr;
// allocate pointers
amps = new T*[nrows];
// allocate the block of memory
pool = new T[nrows*ncols]{init};
// point to the first position in each row
for (int i = 0; i < nrows; ++i, pool += ncols) {
amps[i] = pool;
}
return amps;
}
template <typename T>
void deleteAmpsArray(T** amps)
{
delete [] amps[0];
delete [] amps;
}
// Class for main walker list in FCIQMC
template<typename TrialWalk>
class walkersFCIQMC {
public:
// The index of the final occupied determinant
// Note that some determinants with lower indicies may be unoccupied
int nDets;
// The number of replicas simulations being performed
// (i.e. the number of amplitudes to store per determinant)
int nreplicas;
// The list of determinants. The total size is constant, and elements
// beyond nDets are not filled, and so should not be used
vector<Determinant> dets;
// List of diagonal Hamiltonian elements for the occupied determinants
vector<double> diagH;
// When using a trial wave function, this holds a list of the overlaps
// between the wave function and the occupied determinants
vector<double> ovlp;
// When using a trial wave function, this holds a list of the local
// energies for the occupied determinants
vector<double> localE;
// When using a trial wave function, this holds a list of the sum of
// the sign violating terms (in the impoprtance-sampled Hamiltonian)
// for each occupied determinant
vector<double> SVTotal;
// VMC walker used to calculate properties involving the trial wave
// function, such as the overlap and local energy
vector<TrialWalk> trialWalk;
// List of walkers amplitudes
double** amps;
// Hash table to access the walker array
unordered_map<Determinant, int> ht;
// Positions in main walker list which have become unoccupied,
// and so can be freely overwritten
vector<int> emptyDets;
int firstEmpty, lastEmpty;
// The number of 64-bit integers required to represent (the alpha or beta
// part of) a determinant
// Note, this is different to DetLen in global.h
int DetLenMin;
walkersFCIQMC() {};
walkersFCIQMC(int arrayLength, int DetLenLocal, int nreplicasLocal) {
init(arrayLength, DetLenLocal, nreplicasLocal);
}
// Define a init function, so that a walkersFCIQMC object can be
// initialized after it is constructed, useful in some cases
void init(int arrayLength, int DetLenLocal, int nreplicasLocal) {
nDets = 0;
nreplicas = nreplicasLocal;
dets.resize(arrayLength);
diagH.resize(arrayLength);
ovlp.resize(arrayLength);
localE.resize(arrayLength);
SVTotal.resize(arrayLength);
trialWalk.resize(arrayLength);
amps = allocateAmpsArray(arrayLength, nreplicas, 0.0);
emptyDets.resize(arrayLength);
firstEmpty = 0;
lastEmpty = -1;
DetLenMin = DetLenLocal;
}
~walkersFCIQMC() {
dets.clear();
diagH.clear();
ovlp.clear();
localE.clear();
SVTotal.clear();
trialWalk.clear();
deleteAmpsArray(amps);
ht.clear();
emptyDets.clear();
}
// return true if all replicas for determinant i are unoccupied
bool allUnoccupied(const int i) const {
return all_of(&s[i][0], &s[i][nreplicas], [](double x) { return abs(x)<1.0e-12; });
}
// To be a valid walker in the main list, there must be a corresponding
// hash table entry *and* the amplitude must be non-zero for a replica
// (the exception is core determinants).
bool validWalker(const int i) const {
return ht.find(dets[i]) != ht.end() && !allUnoccupied(i);
}
void stochasticRoundAll(const double minPop, unordered_map<simpleDet, int, boost::hash<simpleDet>>& coreht) {
for (int iDet=0; iDet<nDets; iDet++) {
// When semi-stochastic is turned on, core determinants should never
// be removed from the list or stochastically rounded.
if (schd.semiStoch) {
simpleDet simple = dets[iDet].getSimpleDet();
if (coreht.find(simple) != coreht.end()) {
continue;
}
}
// Check if this is a valid walker - see the comments in this function.
if (validWalker(iDet)) {
bool keepDetAny = false;
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
if (abs(amps[iDet][iReplica]) < minPop) {
bool keepDet;
stochastic_round(minPop, amps[iDet][iReplica], keepDet);
keepDetAny = keepDetAny || keepDet;
} else {
keepDetAny = true;
}
}
// If the population is now 0 on all replicas then remove the ht entry
if (!keepDetAny) {
ht.erase(dets[iDet]);
lastEmpty += 1;
emptyDets[lastEmpty] = iDet;
}
} else {
if ( !allUnoccupied(iDet) ) {
// This should never happen - the hash table entry should not be
// removed unless the walker population becomes zero for all replicas
cout << "#Error: Non-empty det no hash table entry found." << endl;
// Print determinant and all amplitudes
cout << dets[iDet];
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
cout << " " << amps[iDet][iReplica];
}
cout << endl;
}
}
}
}
void calcStats(dataFCIQMC& dat, Determinant& HFDet, oneInt& I1, twoInt& I2, double& coreE) {
int excitLevel = 0;
double overlapRatio = 0.0;
std::fill(dat.walkerPop.begin(), dat.walkerPop.end(), 0.0);
std::fill(dat.EProj.begin(), dat.EProj.end(), 0.0);
std::fill(dat.HFAmp.begin(), dat.HFAmp.end(), 0.0);
std::fill(dat.trialEProj.begin(), dat.trialEProj.end(), 0.0);
std::fill(dat.ampSum.begin(), dat.ampSum.end(), 0.0);
for (int iDet=0; iDet<nDets; iDet++) {
// If using importance sampling then the wave function sampled
// is psi_i^T*C_i. If not, then it is just C_i. So we have the
// extra factors of psi_i^T to include in estimators when using
// importance sampling.
double ISFactor = 1.0;
if (schd.importanceSampling) {
ISFactor = ovlp[iDet];
}
if ( ht.find(dets[iDet]) != ht.end() ) {
excitLevel = HFDet.ExcitationDistance(dets[iDet]);
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
// To be a valid walker in the main list, there must be a corresponding
// hash table entry *and* the amplitude must be non-zero
if ( abs(amps[iDet][iReplica]) > 1.0e-12 ) {
dat.walkerPop.at(iReplica) += abs(amps[iDet][iReplica]);
// Trial-WF-based estimator data
if (schd.trialWFEstimator) {
dat.trialEProj.at(iReplica) +=
localE[iDet] * amps[iDet][iReplica] * ovlp[iDet] / ISFactor;
dat.ampSum.at(iReplica) +=
amps[iDet][iReplica] * ovlp[iDet] / ISFactor;
}
// HF-based estimator data
if (excitLevel == 0) {
dat.HFAmp.at(iReplica) = amps[iDet][iReplica] / ISFactor;
dat.EProj.at(iReplica) +=
amps[iDet][iReplica] * HFDet.Energy(I1, I2, coreE) / ISFactor;
} else if (excitLevel <= 2) {
dat.EProj.at(iReplica) +=
amps[iDet][iReplica] * Hij(HFDet, dets[iDet], I1, I2, coreE) / ISFactor;
}
}
} // Loop over replicas
} // If hash table entry exists
} // Loop over all entries in list
}
void calcPop(vector<double>& walkerPop, vector<double>& walkerPopTot) {
std::fill(walkerPop.begin(), walkerPop.end(), 0.0);
for (int iDet=0; iDet<nDets; iDet++) {
if ( ht.find(dets[iDet]) != ht.end() ) {
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
// To be a valid walker in the main list, there must be a corresponding
// hash table entry *and* the amplitude must be non-zero
if ( abs(amps[iDet][iReplica]) > 1.0e-12 ) {
walkerPop.at(iReplica) += abs(amps[iDet][iReplica]);
}
} // Loop over replicas
} // If hash table entry exists
} // Loop over all entries in list
// Sum walker population from each process
#ifdef SERIAL
walkerPopTot = walkerPop;
#else
MPI_Allreduce(
&walkerPop.front(),
&walkerPopTot.front(),
nreplicas,
MPI_DOUBLE,
MPI_SUM,
MPI_COMM_WORLD
);
#endif
}
// Print the determinants and hash table
friend ostream& operator<<(ostream& os, const walkersFCIQMC& walkers) {
os << "Walker list:" << endl;
for (int iDet=0; iDet<walkers.nDets; iDet++) {
os << iDet << " " << walkers.dets[iDet];
for (int iReplica=0; iReplica<walkers.nreplicas; iReplica++) {
os << " " << walkers.amps[iDet][iReplica];
}
os << endl;
}
os << "Hash table:" << endl;
for (auto kv : walkers.ht) {
os << kv.first << " " << kv.second << " " << endl;
}
return os;
}
};
#endif
<file_sep>##########################
# User Specific Settings #
##########################
CXX = icpc
CC = icc
EIGEN=/projects/sash2458/newApps/eigen/
BOOST=/projects/sash2458/newApps/boost_1_67_0/
#EIGEN=/usr/include/eigen3
#BOOST=/usr/include/boost
#MKLLIB = /curc/sw/intel/16.0.3/mkl/lib/intel64/
FLAGS = -DNDEBUG -O3 -std=c++17 -g -fopenmp -I${EIGEN} -I${BOOST} #-I/curc/sw/intel/16.0.3/mkl/include/
#FLAGS = -std=c++17 -g -fopenmp -I${EIGEN} -I${BOOST} #-I/curc/sw/intel/16.0.3/mkl/include/
OBJ = main.o BasisShell.o interface.o GeneratePolynomials.o CxMemoryStack.o IrAmrr.o Integral2c_Boys.o IrBoysFn.o Kernel.o LatticeSum.o
LIBOBJ = BasisShell.o interface.o GeneratePolynomials.o
%.o: %.cpp
$(CXX) $(FLAGS) $(OPT) -fPIC -c $< -o $@
%.o: %.c
$(CC) -O3 -g -qopenmp -fPIC -c $< -o $@
all: a.out libseparated.so
a.out: $(OBJ)
$(CXX) $(FLAGS) $(OBJ) -o a.out #-L${MKLLIB} -lmkl_gf_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lrt
libseparated.so: $(LIBOBJ)
$(CXX) $(FLAGS) $(LIBOBJ) -shared -o libseparated.so
clean :
find . -name "*.o"|xargs rm 2>/dev/null
<file_sep>#ifndef dataFCIQMC_HEADER_H
#define dataFCIQMC_HEADER_H
class dataFCIQMC {
public:
// The total walker population (on this process only)
vector<double> walkerPop;
// The numerator of the projected energy (against the HF determinant)
vector<double> EProj;
// The walker population on the HF determinant
vector<double> HFAmp;
// The numerator of the trial-WF-based projected energy estimator
vector<double> trialEProj;
// The sum of all walker amplitudes (the denominator of the trial
// WF-based projected energy estimator)
vector<double> ampSum;
// The total number of walkers annihilated (on this process only)
vector<double> nAnnihil;
// The shift to the diagonal of the Hamiltonian
vector<double> Eshift;
// True is the shift has started to vary (left the constant phase)
vector<bool> varyShift;
// All of the following quantities are summed over all processes:
// The total walker population
vector<double> walkerPopTot;
// The total walker population from the previous iteration
vector<double> walkerPopOldTot;
// The numerator of the projected energy (against the HF determinant)
vector<double> EProjTot;
// The walker population on the HF determinant
vector<double> HFAmpTot;
// The numerator of the trial-WF-based projected energy
vector<double> trialEProjTot;
// The denominator of the trial-WF-based projected energy
vector<double> ampSumTot;
// The total number of walkers annihilated
vector<double> nAnnihilTot;
// Estimates requiring two replicas simulations:
// The numerator and denominator of the variational energy
double EVarNumAll;
double EVarDenomAll;
// The numerator of the EN2 perturbative correction
double EN2All;
dataFCIQMC(int nreplicas, double initEshift) {
walkerPop.resize(nreplicas, 0.0);
EProj.resize(nreplicas, 0.0);
HFAmp.resize(nreplicas, 0.0);
trialEProj.resize(nreplicas, 0.0);
ampSum.resize(nreplicas, 0.0);
Eshift.resize(nreplicas, initEshift);
varyShift.resize(nreplicas, false);
walkerPopTot.resize(nreplicas, 0.0);
walkerPopOldTot.resize(nreplicas, 0.0);
EProjTot.resize(nreplicas, 0.0);
HFAmpTot.resize(nreplicas, 0.0);
trialEProjTot.resize(nreplicas, 0.0);
ampSumTot.resize(nreplicas, 0.0);
nAnnihil.resize(nreplicas, 0.0);
nAnnihilTot.resize(nreplicas, 0.0);
EVarNumAll = 0.0;
EVarDenomAll = 0.0;
EN2All = 0.0;
}
};
#endif
<file_sep>#pragma once
#include <vector>
#include "coulomb.h"
#include "tensor.h"
using namespace std;
extern vector<double> normA, normB;
extern const int Lmax;// = 7;
extern vector<vector<int>> CartOrder;//[(Lmax+1) * (Lmax+2) * (Lmax+3)/6][3];
extern vector<double> workArray; //only need 4*Lmax
extern tensor DerivativeToPolynomial;
extern Coulomb_14_8_8 coulomb_14_8_8;
extern Coulomb_14_14_8 coulomb_14_14_8;
extern tensor Sx_2d ;
extern tensor Sy_2d ;
extern tensor Sz_2d ;
extern tensor Sx2_2d;
extern tensor Sy2_2d;
extern tensor Sz2_2d;
extern tensor S_2d ;
extern tensor Sx_3d;
extern tensor Sy_3d;
extern tensor Sz_3d;
extern tensor Sx2_3d;
extern tensor Sy2_3d;
extern tensor Sz2_3d;
extern tensor S_3d;
extern tensor Coeffx_3d;
extern tensor Coeffy_3d;
extern tensor Coeffz_3d;
extern tensor powExpAPlusExpB;
extern tensor powExpA;
extern tensor powExpB;
extern tensor powExpC;
extern tensor powPIOverLx;
extern tensor powPIOverLy;
extern tensor powPIOverLz;
extern vector<double> expbPow;
extern vector<double> expaPow;
extern tensor Ci;
extern tensor Cj;
extern tensor Ck;
extern tensor teri;
void initWorkArray();
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PROPAGATE_HEADER_H
#define PROPAGATE_HEADER_H
#include <Eigen/Dense>
#include <boost/serialization/serialization.hpp>
#include "iowrapper.h"
#include "global.h"
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <list>
#include <utility>
#include <vector>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include "workingArray.h"
using namespace Eigen;
using namespace boost;
using namespace std;
template<typename Walker, typename Wfn>
void generateWalkers(list<pair<Walker, double> >& Walkers, Wfn& w,
workingArray& work) {
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
Walker walk = Walkers.begin()->first;
double ham, ovlp;
int iter = 0;
//select a new walker every 30 iterations
int numSample = Walkers.size();
int niter = 30*numSample+1;
auto it = Walkers.begin();
while(iter < niter) {
w.HamAndOvlp(walk, ovlp, ham, work);
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < work.nExcitations; i++)
{
cumovlpRatio += abs(work.ovlpRatio[i]);
//cumovlpRatio += min(1.0, pow(ovlpRatio[i], 2));
work.ovlpRatio[i] = cumovlpRatio;
}
if (iter % 30 == 0) {
it->first = walk; it->second = 1.0/cumovlpRatio;
it++;
if (it == Walkers.end()) break;
}
double nextDetRandom = random()*cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(),
(work.ovlpRatio.begin()+work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
walk.updateWalker(w.getRef(), w.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
}
};
/*Take the walker and propagate it for time tau using continous time algorithm
*/
template<typename Wfn, typename Walker>
void applyPropogatorContinousTime(Wfn &w, Walker& walk, double& wt,
double& tau, workingArray &work, double& Eshift,
double& ham, double& ovlp, double fn_factor) {
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
double t = tau;
vector<double> cumHijElements;
while (t > 0) {
double Ewalk = walk.d.Energy(I1, I2, coreE);
w.HamAndOvlp(walk, ovlp, ham, work);
if (cumHijElements.size()< work.nExcitations) cumHijElements.resize(work.nExcitations);
double cumHij = 0;
for (int i = 0; i < work.nExcitations; i++)
{
//if sy,x is > 0 then add include contribution to the diagonal
if (work.HijElement[i]*work.ovlpRatio[i] > 0.0) {
Ewalk += work.HijElement[i]*work.ovlpRatio[i] * (1+fn_factor);
cumHij += fn_factor*abs(work.HijElement[i]*work.ovlpRatio[i]);
cumHijElements[i] = cumHij;
}
else {
cumHij += abs(work.HijElement[i]*work.ovlpRatio[i]);
cumHijElements[i] = cumHij;
}
}
//ham = Ewalk-cumHij;
double tsample = -log(random())/cumHij;
double deltaT = min(t, tsample);
t -= tsample;
wt = wt * exp(deltaT*(Eshift - (Ewalk-cumHij) ));
if (t > 0.0) {
double nextDetRandom = random()*cumHij;
int nextDet = std::lower_bound(cumHijElements.begin(),
(cumHijElements.begin() + work.nExcitations),
nextDetRandom) - cumHijElements.begin();
walk.updateWalker(w.getRef(), w.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
}
}
};
template<typename Walker>
void reconfigure(std::list<pair<Walker, double> >& walkers) {
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
vector< typename std::list<pair<Walker, double> >::iterator > smallWts; smallWts.reserve(10);
double totalSmallWts = 0.0;
auto it = walkers.begin();
//if a walker has wt > 2.0, then ducplicate it int(wt) times
//accumulate walkers with wt < 0.5,
//then combine them and assing it to one of the walkers
//with a prob. proportional to its wt.
while (it != walkers.end()) {
double wt = it->second;
if (wt < 0.5) {
totalSmallWts += wt;
smallWts.push_back(it);
it++;
}
else if (wt > 2.0) {
int numReplicate = int(wt);
it->second = it->second/(1.0*numReplicate);
for (int i=0; i<numReplicate-1; i++)
walkers.push_front(*it); //add at front
it++;
}
else
it++;
if (totalSmallWts > 1.0 || it == walkers.end()) {
double select = random()*totalSmallWts;
//remove all wts except the selected one
for (int i=0; i<smallWts.size(); i++) {
double bkpwt = smallWts[i]->second;
if (select > 0 && select < smallWts[i]->second)
smallWts[i]->second = totalSmallWts;
else
walkers.erase(smallWts[i]);
select -= bkpwt;
}
totalSmallWts = 0.0;
smallWts.resize(0);
}
}
//now redistribute the walkers so that all procs havve roughly the same number
vector<int> nwalkersPerProc(commsize);
nwalkersPerProc[commrank] = walkers.size();
int nTotalWalkers = nwalkersPerProc[commrank];
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &nTotalWalkers, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &nwalkersPerProc[0], commsize, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
#endif
vector<int> procByNWalkers(commsize);
std::iota(procByNWalkers.begin(), procByNWalkers.end(), 0);
std::sort(procByNWalkers.begin(), procByNWalkers.end(), [&nwalkersPerProc](size_t i1, size_t i2) {return nwalkersPerProc[i1] < nwalkersPerProc[i2];});
return;
};
//continously apply the continous time GFMC algorithm
template<typename Wfn, typename Walker>
void doGFMCCT(Wfn &w, Walker& walk, double Eshift)
{
startofCalc = getTime();
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
workingArray work;
//we want to have a set of schd.nwalk walkers and weights
//we just replciate the input walker nwalk times
list<pair<Walker, double> > Walkers;
for (int i=0; i<schd.nwalk; i++)
Walkers.push_back(std::pair<Walker, double>(walk, 1.0));
//now actually sample the wavefunction w to generate these walkers
generateWalkers(Walkers, w, work);
//normalize so the cumulative weight is schd.nwalk whichi s also the target wt
double oldwt = .0;
for (auto it=Walkers.begin(); it!=Walkers.end(); it++) oldwt += it->second;
for (auto it=Walkers.begin(); it!=Walkers.end(); it++) {
it->second = it->second*schd.nwalk/oldwt;
}
oldwt = schd.nwalk * commsize;
double targetwt = schd.nwalk;
//run calculation for niter itarions
int niter = schd.maxIter, iter = 0;
//each iteration consists of a time tau
//(after every iteration pop control and reconfiguration is performed
double tau = schd.tau;
//after every nGeneration iterations, calculate/print the energy
//the Enum and Eden are restarted after each geneation
int nGeneration = schd.nGeneration;
//exponentially decaying average and regular average
double EavgExpDecay = 0.0, Eavg;
double Enum = 0.0, Eden = 0.0;
double popControl = 1.0;
double iterPop = 0.0, olditerPop = oldwt;
while (iter < niter)
{
//propagate all walkers for time tau
iterPop = 0.0;
for (auto it = Walkers.begin(); it != Walkers.end(); it++) {
Walker& walk = it->first;
double& wt = it->second;
double ham=0., ovlp=0.;
double wtsold = wt;
applyPropogatorContinousTime(w, walk, wt, schd.tau,
work, Eshift, ham, ovlp,
schd.fn_factor);
iterPop += abs(wt);
Enum += popControl*wt*ham;
Eden += popControl*wt;
}
//reconfigure
reconfigure(Walkers);
//accumulate the total weight across processors
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &iterPop, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
//all procs have the same Eshift
Eshift = Eshift - 0.1/tau * log(iterPop/olditerPop);
//population control and keep a exponentially decaying population
//control factor
//double factor = pow(olditerPop/iterPop, 0.1);
//popControl = pow(popControl, 0.99)*factor;
olditerPop = iterPop;
if (iter % nGeneration == 0 && iter != 0) {
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &Enum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &Eden, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
//calculate average energy acorss all procs
double Ecurrentavg = Enum/Eden;
//this is the exponentially moving average
if (iter == nGeneration)
EavgExpDecay = Ecurrentavg;
else
EavgExpDecay = (0.9)*EavgExpDecay + 0.1*Ecurrentavg;
//this is the average energy, but only start
//taking averages after 4 generations because
//we assume that it takes atleast 4 generations to reach equilibration
if (iter/nGeneration == 4)
Eavg = Ecurrentavg;
else if (iter/nGeneration > 4) {
int oldIter = iter/nGeneration;
Eavg = ((oldIter - 4)*Eavg + Ecurrentavg)/(oldIter-3);
}
else
Eavg = EavgExpDecay;
//growth estimator
double Egr = Eshift ;
if (commrank == 0)
cout << format("%8i %14.8f %14.8f %14.8f %10i %8.2f %14.8f %8.2f\n") % iter % Ecurrentavg % (EavgExpDecay) %Eavg % (Walkers.size()) % (iterPop/commsize) % Egr % (getTime()-startofCalc);
//restart the Enum and Eden
Enum=0.0; Eden =0.0;
popControl = 1.0;
}
iter++;
}
};
#endif
<file_sep>#ifndef TrivialWF_HEADER_H
#define TrivialWF_HEADER_H
// This is a trial wave function class for cases in FCIQMC where a
// trial wave function is not used (i.e. the original version of the
// algorithm). In this case, these functions are either not used or
// should return trivial results. This is a basic class to deal with
// this situation, together with the TrialWalk class.
#include "trivialWalk.h"
class TrivialWF {
public:
Determinant d;
TrivialWF() {}
TrivialWF(Determinant& det) : d(det) {}
void HamAndOvlp(const TrivialWalk &walk, double &ovlp,
double &ham, workingArray& work, bool fillExcitations=true,
double epsilon=schd.epsilon) const {
work.setCounterToZero();
ovlp = 1.0;
ham = 0.0;
}
void HamAndOvlpAndSVTotal(const TrivialWalk &walk, double &ovlp,
double &ham, double& SVTotal, workingArray& work,
double epsilon=schd.epsilon) const {
work.setCounterToZero();
ovlp = 1.0;
ham = 0.0;
SVTotal = 0.0;
}
double parityFactor(Determinant& det, const int ex2, const int i,
const int j, const int a, const int b) const {
return 1.0;
}
double getOverlapFactor(const TrivialWalk& walk, Determinant& dNew,
bool doparity) const {
return 1.0;
}
double getOverlapFactor(int I, int J, int A, int B,
const TrivialWalk& walk, bool doparity) const {
return 1.0;
}
double Overlap(const TrivialWalk& walk) const {
return 1.0;
}
Determinant& getRef() {
return d;
}
Determinant& getCorr() {
return d;
}
};
#endif
<file_sep>#include "SHCIshm.h"
#include <boost/interprocess/managed_shared_memory.hpp>
#include <vector>
#ifndef SERIAL
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#include "mpi.h"
#endif
using namespace std;
void initSHM() {
#ifndef SERIAL
boost::mpi::communicator world;
MPI_Comm_rank(MPI_COMM_WORLD, &commrank);
MPI_Comm_size(MPI_COMM_WORLD, &commsize);
if (true){
char hostname[MPI_MAX_PROCESSOR_NAME]; int resultsize;
MPI_Get_processor_name(hostname, &resultsize);
string HName(hostname);
vector<string> AllHostNames(commsize);
AllHostNames[commrank] = HName;
// all nodes will not have node names for all procs
for (int i=0; i<commsize; i++)
boost::mpi::broadcast(world, AllHostNames[i], i);
std::sort( AllHostNames.begin(), AllHostNames.end());
AllHostNames.erase(std::unique(AllHostNames.begin(), AllHostNames.end()), AllHostNames.end());
int color = -1;
for (int i=0; i<AllHostNames.size(); i++)
if (HName == AllHostNames[i])
color = i;
MPI_Comm_split(MPI_COMM_WORLD, color, commrank, &localcomm);
MPI_Comm_rank(localcomm, &localrank);
MPI_Comm_size(localcomm, &localsize);
}
else {
MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, 0,
MPI_INFO_NULL, &localcomm);
MPI_Comm_rank(localcomm, &localrank);
MPI_Comm_size(localcomm, &localsize);
}
int localrankcopy = localrank;
MPI_Comm_split(MPI_COMM_WORLD, localrankcopy, commrank, &shmcomm);
MPI_Comm_rank(shmcomm, &shmrank);
MPI_Comm_size(shmcomm, &shmsize);
//MPI_Comm_free(&localcomm);
#else
commrank=0;shmrank=0;localrank=0;
commsize=1;shmsize=1;localsize=1;
#endif
//set up shared memory files to store the integrals
shciint2 = "SHCIint2" + to_string(static_cast<long long>(time(NULL) % 1000000));
int2Segment = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create, shciint2.c_str(), boost::interprocess::read_write);
shciint2shm = "SHCIint2shm" + to_string(static_cast<long long>(time(NULL) % 1000000));
int2SHMSegment = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create, shciint2shm.c_str(), boost::interprocess::read_write);
shciint2shmcas = "SHCIint2shmcas" + to_string(static_cast<long long>(time(NULL) % 1000000));
int2SHMCASSegment = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create, shciint2shmcas.c_str(), boost::interprocess::read_write);
}
void removeSHM(){
boost::interprocess::shared_memory_object::remove(shciint2.c_str());
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "CPS.h"
#include "Correlator.h"
#include "Determinants.h"
#include <boost/container/static_vector.hpp>
#include "input.h"
using namespace Eigen;
CPS::CPS () {
twoSiteOrSmaller = true;
for(const auto& p : schd.correlatorFiles) {
if (p.first > 2) twoSiteOrSmaller = false;
readCorrelator(p, this->cpsArray);
}
generateMapFromOrbitalToCorrelators();
};
CPS::CPS (std::vector<Correlator>& pcpsArray) : cpsArray(pcpsArray) {
twoSiteOrSmaller = true;
for (const auto& p : pcpsArray)
if (p.asites.size() > 2) twoSiteOrSmaller = false;
generateMapFromOrbitalToCorrelators();
};
void CPS::generateMapFromOrbitalToCorrelators() {
int norbs = Determinant::norbs;
mapFromOrbitalToCorrelator.resize(norbs);
for (int i = 0; i < cpsArray.size(); i++)
{
for (int j = 0; j < cpsArray[i].asites.size(); j++) {
int orbital = cpsArray[i].asites[j];
mapFromOrbitalToCorrelator[orbital].push_back(i);
}
}
for (int i = 0; i < norbs; i++)
std::sort(mapFromOrbitalToCorrelator[i].begin(),
mapFromOrbitalToCorrelator[i].end());
}
double CPS::Overlap(const Determinant &d) const
{
double ovlp = 1.0;
for (const auto& c : cpsArray) ovlp *= c.Overlap(d);
return ovlp;
}
double CPS::OverlapRatio (const Determinant &d1, const Determinant &d2) const {
double ovlp = 1.0;
for (const auto& c : cpsArray) ovlp *= c.Overlap(d1)/c.Overlap(d2);
return ovlp;
}
double CPS::OverlapRatio(int i, int a, const Determinant &dcopy, const Determinant &d) const
{
//boost::container::static_vector<int, 100> commonCorrelators;
vector<int>& common = const_cast<vector<int>&>(commonCorrelators);
common.resize(0);
merge(mapFromOrbitalToCorrelator[i].begin(),
mapFromOrbitalToCorrelator[i].end(),
mapFromOrbitalToCorrelator[a].begin(),
mapFromOrbitalToCorrelator[a].end(),
back_inserter(common));
sort(common.begin(), common.end() );
double ovlp = 1.0;
int previ = -1;
for (const auto& i : common)
if (i != previ) {
ovlp *= cpsArray[i].OverlapRatio(dcopy,d);
previ = i;
}
return ovlp;
}
double CPS::OverlapRatio(int i, int j, int a, int b, const Determinant &dcopy, const Determinant &d) const
{
//boost::container::static_vector<int, 100> common;
vector<int>& common = const_cast<vector<int>&>(commonCorrelators);
common.resize(0);
merge(mapFromOrbitalToCorrelator[i].begin(),
mapFromOrbitalToCorrelator[i].end(),
mapFromOrbitalToCorrelator[a].begin(),
mapFromOrbitalToCorrelator[a].end(),
back_inserter(common));
int middlesize = common.size();
merge(mapFromOrbitalToCorrelator[j].begin(),
mapFromOrbitalToCorrelator[j].end(),
mapFromOrbitalToCorrelator[b].begin(),
mapFromOrbitalToCorrelator[b].end(),
back_inserter(common));
//The following is an ugly code but is used because it is faster than the alternative.
//Essentially common has elements 0...middlesize sorted and elements
//middlesize..end sorted as well. The loop below find unique elements
//in the entire common vector.
double ovlp = 1.0;
int previ = -1;
for (int i=0,j=middlesize; i<middlesize || j<common.size(); ) {
if (common[i] < common[j] ) {
if (common[i] <= previ)
i++;
else {
int I = common[i];
ovlp *= cpsArray[I].OverlapRatio(dcopy,d);
i++; previ = I;
}
}
else {
if (common[j] <= previ)
j++;
else {
int J = common[j];
ovlp *= cpsArray[J].OverlapRatio(dcopy,d);
j++; previ = J;
}
}
}
return ovlp;
}
double CPS::OverlapRatio(int i, int a, const BigDeterminant &dcopy, const BigDeterminant &d) const
{
//boost::container::static_vector<int, 100> commonCorrelators;
vector<int>& common = const_cast<vector<int>&>(commonCorrelators);
common.resize(0);
merge(mapFromOrbitalToCorrelator[i].begin(),
mapFromOrbitalToCorrelator[i].end(),
mapFromOrbitalToCorrelator[a].begin(),
mapFromOrbitalToCorrelator[a].end(),
back_inserter(common));
sort(common.begin(), common.end() );
double ovlp = 1.0;
int previ = -1;
for (const auto& i : common)
if (i != previ) {
ovlp *= cpsArray[i].OverlapRatio(dcopy,d);
previ = i;
}
return ovlp;
}
double CPS::OverlapRatio(int i, int j, int a, int b, const BigDeterminant &dcopy, const BigDeterminant &d) const
{
//boost::container::static_vector<int, 100> common;
vector<int>& common = const_cast<vector<int>&>(commonCorrelators);
common.resize(0);
merge(mapFromOrbitalToCorrelator[i].begin(),
mapFromOrbitalToCorrelator[i].end(),
mapFromOrbitalToCorrelator[a].begin(),
mapFromOrbitalToCorrelator[a].end(),
back_inserter(common));
int middlesize = common.size();
merge(mapFromOrbitalToCorrelator[j].begin(),
mapFromOrbitalToCorrelator[j].end(),
mapFromOrbitalToCorrelator[b].begin(),
mapFromOrbitalToCorrelator[b].end(),
back_inserter(common));
//The following is an ugly code but is used because it is faster than the alternative.
//Essentially common has elements 0...middlesize sorted and elements
//middlesize..end sorted as well. The loop below find unique elements
//in the entire common vector.
double ovlp = 1.0;
int previ = -1;
for (int i=0,j=middlesize; i<middlesize || j<common.size(); ) {
if (common[i] < common[j] ) {
if (common[i] <= previ)
i++;
else {
int I = common[i];
ovlp *= cpsArray[I].OverlapRatio(dcopy,d);
i++; previ = I;
}
}
else {
if (common[j] <= previ)
j++;
else {
int J = common[j];
ovlp *= cpsArray[J].OverlapRatio(dcopy,d);
j++; previ = J;
}
}
}
return ovlp;
}
void CPS::OverlapWithGradient(const Determinant& d,
Eigen::VectorBlock<VectorXd>& grad,
const double& ovlp) const {
if (schd.optimizeCps) {
long startIndex = 0;
for (const auto& c : cpsArray) {
c.OverlapWithGradient(d, grad, ovlp, startIndex);
startIndex += c.Variables.size();
}
}
}
long CPS::getNumVariables() const
{
long numVars = 0;
return std::accumulate(cpsArray.begin(), cpsArray.end(), numVars,
[](long a, const Correlator& c)
{return a + c.Variables.size();}
);
}
void CPS::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
int numVars = 0;
for (const auto& c : cpsArray) {
std::copy(c.Variables.begin(), c.Variables.end(), &v[numVars]);
numVars+= c.Variables.size();
}
}
void CPS::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
int numVars = 0;
for (auto& c : cpsArray) {
for (int j=0; j<c.Variables.size(); j++)
c.Variables[j] = v[numVars+j];
numVars+= c.Variables.size();
}
}
void CPS::printVariables() const
{
cout << "CPS"<< endl;
for (int i = 0; i < cpsArray.size(); i++)
{
for (int j = 0; j < cpsArray[i].Variables.size(); j++)
{
cout << " " << cpsArray[i].Variables[j] << endl;
}
}
}
<file_sep>import numpy as np
from itertools import permutations
def perm_parity(lst_in):
'''\
Given a permutation of the digits 0..N in order as a list,
returns its parity (or sign): +1 for even parity; -1 for odd.
'''
lst = lst_in.copy()
parity = 1
for i in range(0,len(lst)-1):
if lst[i] != i:
parity *= -1
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i],lst[mn] = lst[mn],lst[i]
return parity
def detExpression(lst):
n = len(lst)
for perm in permutations(range(n)):
pl = list(perm)
parity = '{} '.format('+' if perm_parity(pl) == 1 else '-')
productFS = "".join([ '{} * ' for i in range(n - 1) ]) + '{}'
permElements = [ lst[i][pl[i]] for i in range(n) ]
expr = parity + productFS.format(*permElements)
print(expr)
def column_mat_det(nc):
print('{} column{}'.format(nc, 's' if nc > 1 else ''))
tc = [ [ f'tc(w.ciExcitations[j][0][{p}], w.ciExcitations[j][1][{t}])' for t in range(nc) ] for p in range(nc) ]
detExpression(tc)
print('\n')
def laplace_det(nc):
print('{} column{}'.format(nc, 's' if nc > 1 else ''))
for mu in range(nc):
tc = [ [ f'walk.walker.refHelper.tc(ref.ciExcitations[i][0][{p}], ref.ciExcitations[i][1][{t}])' for t in range(nc) ] for p in range(nc) ]
tc[mu] = [ f's(ref.ciExcitations[i][0][{mu}], ref.ciExcitations[i][1][{t}])' for t in range(nc) ]
detExpression(tc)
print('\n')
def row1_mat_det(nc):
print('1 row {} column{}'.format(nc, 's' if nc > 1 else ''))
rt = [ 'rtSlice' ]
rtc = [ f'refHelper.rtc_b(mCre[0], ref.ciExcitations[j][1][{t}])' for t in range(nc) ]
t = [ f'refHelper.t(ref.ciExcitations[j][0][{p}], mDes[0])' for p in range(nc)]
tc = [ [ f'refHelper.tc(ref.ciExcitations[j][0][{p}], ref.ciExcitations[j][1][{t}])' for t in range(nc) ] for p in range(nc) ]
m = [ rt + rtc ] + [ [t[i]] + tc[i] for i in range(nc) ]
detExpression(m)
print('\n')
def row2_mat_det(nc):
print('2 rows {} column{}'.format(nc, 's' if nc > 1 else ''))
rt = [ [ f'rtSlice({a}, {i})' for i in range(2) ] for a in range(2) ]
rtc = [ [ f'refHelper.rtc_b(mCre[{a}], ref.ciExcitations[k][1][{t}])' for t in range(nc) ] for a in range(2) ]
t = [ [ f'refHelper.t(ref.ciExcitations[k][0][{p}], mDes[{i}])' for i in range(2) ] for p in range(nc) ]
tc = [ [ f'refHelper.tc(ref.ciExcitations[k][0][{p}], ref.ciExcitations[k][1][{t}])' for t in range(nc) ] for p in range(nc) ]
m = [ rt[i] + rtc[i] for i in range(2) ] + [ t[i] + tc[i] for i in range(nc) ]
detExpression(m)
print('\n')
if __name__ == "__main__":
#for i in range(4):
# row1_mat_det(i+1)
#for i in range(3):
# row2_mat_det(i+1)
for i in range(3):
laplace_det(i+2)
<file_sep>/* Copyright (c) 2012 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bfint (LICENSE). If not, see http://www.gnu.org/licenses/
*/
#include <stdexcept>
#include <cmath>
#include "IrBoysFn.h"
#include "IrBoysFn.inl"
namespace ir {
// store Boys function values Factor*Fm(T) at pOut[0...MaxM], MaxM inclusive
void IrBoysFn(double *pOut, double T, unsigned MaxM, double Factor)
{
if (MaxM > TableMaxM)
throw std::runtime_error("This version of IrBoysFn does not support the supplied M.");
unsigned
// index of table entry closest to T
iTab = (unsigned)(T * StepsPerT + .5);
if (iTab >= TableSize || T > 100.) {
// large T, out of tabulated range.
// calculate F(m=0,T) directly and get the other Fms by upward recursion.
// Note: F0(T) = sqrt(pi/4) * Erf(sqrt(T))/sqrt(T)
// F_{m}(T) = ((2*m-1)*F_{m-1}(T) - exp(-T))/(2*T)
double
ExpT = 0.,
Erf = 1.,
SqrtT = std::sqrt(T),
InvSqrtT = 1./SqrtT;
if (T < 36 + 2*MaxM)
// may need this in the upward recursion
ExpT = std::exp(-T);
if (T < 36) { // <- for T >= 36 1-erf(T) < 1e-16.
// Target: Erf = std::erf(SqrtT);
// p is a chebyshev approximation for erfc(x)*exp(x**2)*x
// with x=T**.5 in the interval T=12..36
double p = -7.2491691372602426e-09;
p = p * SqrtT + 3.8066154133517713e-07;
p = p * SqrtT - 9.0705120587974647e-06;
p = p * SqrtT + 1.2950910968223645e-04;
p = p * SqrtT - 1.2316919353973963e-03;
p = p * SqrtT + 8.1970126968511671e-03;
p = p * SqrtT - 3.8969822025737025e-02;
p = p * SqrtT + 1.3231983459351979e-01;
p = p * SqrtT - 3.1347761821045855e-01;
p = p * SqrtT + 4.8563266902187724e-01;
p = p * SqrtT + 1.6056422712311058e-01;
Erf = 1. - p*ExpT*InvSqrtT;
// max error of fit for erf(sqrt(T)): 1.11e-16
}
double
Inv2T = .5 * InvSqrtT * InvSqrtT; // 1/(2*T)
ExpT *= Factor;
pOut[0] = Factor * HalfSqrtPi * InvSqrtT * Erf;
for (unsigned m = 1; m <= MaxM; ++ m)
pOut[m] = ((2*m-1) * pOut[m-1] - ExpT)*Inv2T;
} else {
// T is in tabulated range. Calculate Fm for highest order M by
// Taylor expansion and other Ts by downward recursion.
double const
// difference to next tabulated point
Delta = T - iTab*TsPerStep,
*pTab = &BoysData[iTab*TableOrder + MaxM];
double
Fm;
Fm = pTab[8]/(double)(1*2*3*4*5*6*7*8);
Fm = Delta * Fm - pTab[7]/(double)(1*2*3*4*5*6*7);
Fm = Delta * Fm + pTab[6]/(double)(1*2*3*4*5*6);
Fm = Delta * Fm - pTab[5]/(double)(1*2*3*4*5);
Fm = Delta * Fm + pTab[4]/(double)(1*2*3*4);
Fm = Delta * Fm - pTab[3]/(double)(1*2*3);
Fm = Delta * Fm + pTab[2]/(double)(1*2);
Fm = Delta * Fm - pTab[1];
Fm = Delta * Fm + pTab[0];
pOut[MaxM] = Factor * Fm;
if (MaxM != 0) {
double
ExpT = Factor * std::exp(-T);
for (int m = MaxM-1; m != -1; --m)
pOut[m] = (2*T * pOut[m+1] + ExpT)*Inv2mp1[m];
}
}
// printf("IrBoysFn(T=%f, M=%i, F=%f) -> [0] = %f", T, MaxM, Factor, pOut[0]);
}
} // namespace ir
<file_sep>#include <iomanip>
#include "Determinants.h"
#include "evaluateE.h"
#include "global.h"
#include "input.h"
#include "runFCIQMC.h"
#include "walkersFCIQMC.h"
#include "AGP.h"
#include "CorrelatedWavefunction.h"
#include "Jastrow.h"
#include "Slater.h"
#include "SelectedCI.h"
#include "trivialWF.h"
#include "trivialWalk.h"
// Perform initialization of variables needed for the runFCIQMC routine.
// In particular the Hartree--Fock determinant and energy, the heat bath
// integrals (hb), and the walker and spawned walker objects.
template<typename Wave, typename TrialWalk>
void initFCIQMC(Wave& wave, TrialWalk& walk,
const int norbs, const int nel, const int nalpha, const int nbeta,
Determinant& HFDet, double& HFEnergy, heatBathFCIQMC& hb,
walkersFCIQMC<TrialWalk>& walkers, spawnFCIQMC& spawn,
semiStoch& core, workingArray& work) {
// The number of 64-bit integers required to represent (the alpha
// or beta part of) a determinant
int DetLenAlpha = (nalpha-1)/64 + 1;
int DetLenBeta = (nalpha-1)/64 + 1;
int DetLenMin = max(DetLenAlpha, DetLenBeta);
for (int i = 0; i < nalpha; i++)
HFDet.setoccA(i, true);
for (int i = 0; i < nbeta; i++)
HFDet.setoccB(i, true);
int walkersSize = schd.targetPop * schd.mainMemoryFac / commsize;
int spawnSize = schd.targetPop * schd.spawnMemoryFac / commsize;
// Resize and initialize the walker and spawned walker arrays
walkers.init(walkersSize, DetLenMin, schd.nreplicas);
spawn.init(spawnSize, DetLenMin, schd.nreplicas);
HFEnergy = HFDet.Energy(I1, I2, coreE);
if (schd.semiStoch) {
if (commrank == 0) cout << "Starting semi-stochastic construction..." << endl << flush;
core.init(schd.semiStochFile, wave, walk, walkers, DetLenMin, schd.nreplicas,
schd.importanceSampling, schd.semiStochInit, schd.initialPop, work);
if (commrank == 0) cout << "Semi-stochastic construction finished." << endl << flush;
}
// Set up the initial walker list, if we didn't do so in the
// semi-stochastic routine already
if (!schd.semiStochInit) {
if (schd.trialInitFCIQMC) {
initWalkerListTrialWF(wave, walk, walkers, spawn, core, work);
} else {
initWalkerListHF(wave, walk, walkers, spawn, core, work, HFDet, DetLenMin);
}
}
if (commrank == 0) {
cout << "Hartree--Fock energy: " << HFEnergy << endl << endl;
}
if (schd.heatBathExGen || schd.heatBathUniformSingExGen) {
if (commrank == 0) cout << "Starting heat bath excitation generator construction..." << endl << flush;
hb.createArrays(norbs, I2);
if (commrank == 0) cout << "Heat bath excitation generator construction finished." << endl << flush;
}
// The default excitation generator is the uniform one. If
// the user has specified another, then turn this off.
if (schd.heatBathExGen || schd.heatBathUniformSingExGen) {
schd.uniformExGen = false;
}
}
// This routine places all intial walkers on the Hartree--Fock determinant,
// and sets all attributes in the walkersFCIQMC object as appropriate for
// this state.
template<typename Wave, typename TrialWalk>
void initWalkerListHF(Wave& wave, TrialWalk& walk, walkersFCIQMC<TrialWalk>& walkers,
spawnFCIQMC& spawn, semiStoch& core, workingArray& work,
Determinant& HFDet, const int DetLenMin) {
// Processor that the HF determinant lives on
int proc = getProc(HFDet, DetLenMin);
// Add a walker to the spawning array, on the HF determinant
if (proc == commrank) {
int ind = spawn.currProcSlots[proc];
spawn.dets[ind] = HFDet.getSimpleDet();
// Set the amplitude on the correct replica
for (int iSgn=0; iSgn<schd.nreplicas; iSgn++) {
spawn.amps[ind][iSgn] = schd.initialPop;
}
spawn.currProcSlots[proc] += 1;
}
// Move the walker to the main list, using the communication and
// annihilation procedures
vector<double> nAnnihil;
spawn.communicate();
spawn.compress(nAnnihil);
spawn.mergeIntoMain_NoInitiator(wave, walk, walkers, core, nAnnihil, 0.0, work);
}
// This routine creates the initial walker distribution by sampling the
// VMC wave function, using the CTMC algorithm. These are placed in the
// spawned array, and then communicated to the correct process,
// compressed (annihilating repeated determinants), and then moved to
// the walker array (merged). The walker population is then corrected
// with a constant multiplicative factor.
template<typename Wave, typename TrialWalk>
void initWalkerListTrialWF(Wave& wave, TrialWalk& walk, walkersFCIQMC<TrialWalk>& walkers,
spawnFCIQMC& spawn, semiStoch& core, workingArray& work) {
double ham, ovlp;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
// Split the generation of determinants across processes
int nDetsThisProc = schd.initialNDets / commsize;
// Select a new walker every 5 iterations
const int nitersPerWalker = 5;
int niter = nitersPerWalker * nDetsThisProc * schd.nreplicas;
for (int iter=0; iter<niter; iter++) {
wave.HamAndOvlp(walk, ovlp, ham, work);
// If importance sampling is in use then the initial wave function
// to sample has coefficients psi_i^2. If not, then the wave
// function to sample has coefficients psi_i. In this latter case,
// we sample psi_i^2 then include a factor of 1/ovlp (=1/psi_i)
// to get the desired initial WF.
double ISFactor = 1.0;
if (! schd.importanceSampling) {
ISFactor = 1/ovlp;
}
double cumOvlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++)
{
cumOvlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumOvlpRatio;
}
if ((iter+1) % nitersPerWalker == 0) {
// Put the current walker in the FCIQMC walker list. This
// needs top be put in the spawning list to correctly perform
// annihilation and send walkers to the correct processor.
int proc = getProc(walk.d, spawn.DetLenMin);
// The position in the spawned list for the walker
int ind = spawn.currProcSlots[proc];
int iReplica = iter / (nitersPerWalker * nDetsThisProc);
spawn.dets[ind] = walk.d.getSimpleDet();
// Set the amplitude on the correct replica
for (int iSgn=0; iSgn<schd.nreplicas; iSgn++) {
if (iSgn == iReplica) {
spawn.amps[ind][iSgn] = ISFactor/cumOvlpRatio;
} else {
spawn.amps[ind][iSgn] = 0.0;
}
}
spawn.currProcSlots[proc] += 1;
}
double nextDetRandom = random()*cumOvlpRatio;
int nextDet = std::lower_bound(
work.ovlpRatio.begin(),
work.ovlpRatio.begin()+work.nExcitations,
nextDetRandom
) - work.ovlpRatio.begin();
walk.updateWalker(
wave.getRef(),
wave.getCorr(),
work.excitation1[nextDet],
work.excitation2[nextDet]
);
}
// Communicate and compress spawned walkers, then move them
// to the main walker list
vector<double> nAnnihil;
spawn.communicate();
spawn.compress(nAnnihil);
spawn.mergeIntoMain_NoInitiator(wave, walk, walkers, core, nAnnihil, 0.0, work);
vector<double> walkerPop, walkerPopTot;
walkerPop.resize(schd.nreplicas, 0.0);
walkerPopTot.resize(schd.nreplicas, 0.0);
walkers.calcPop(walkerPop, walkerPopTot);
// The population we want divided by the population we have
vector<double> popFactor;
popFactor.resize(schd.nreplicas, 0.0);
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
popFactor[iReplica] = schd.initialPop / walkerPopTot[iReplica];
}
// Renormalize the walkers to get the correct initial population
for (int iDet=0; iDet<walkers.nDets; iDet++) {
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
walkers.amps[iDet][iReplica] *= popFactor[iReplica];
}
}
}
// Perform the main FCIQMC loop
template<typename Wave, typename TrialWalk>
void runFCIQMC(Wave& wave, TrialWalk& walk, const int norbs, const int nel,
const int nalpha, const int nbeta) {
// Objects needed for the FCIQMC simulation, which will be
// initialized in initFCIQMC
double HFEnergy;
Determinant HFDet;
heatBathFCIQMC hb;
walkersFCIQMC<TrialWalk> walkers;
spawnFCIQMC spawn;
semiStoch core;
// Needed for calculating local energies
workingArray work;
initFCIQMC(wave, walk, norbs, nel, nalpha, nbeta, HFDet,
HFEnergy, hb, walkers, spawn, core, work);
// ----- FCIQMC data -----
double initEshift = HFEnergy + schd.initialShift;
dataFCIQMC dat(schd.nreplicas, initEshift);
double time_start = 0.0, time_end = 0.0, iter_time = 0.0, total_time = 0.0;
int nDetsTot, nSpawnedDetsTot;
// -----------------------
// Get the initial stats
walkers.calcStats(dat, HFDet, I1, I2, coreE);
communicateEstimates(dat, walkers.nDets, spawn.nDets, nDetsTot, nSpawnedDetsTot);
if (schd.nreplicas == 2) {
if (schd.semiStoch) {
core.copyWalkerAmps(walkers);
core.determProjection(schd.tau);
}
calcVarEnergy(walkers, spawn, core, I1, I2, coreE, schd.tau, dat.EVarNumAll, dat.EVarDenomAll);
}
dat.walkerPopOldTot = dat.walkerPopTot;
// Print the initial stats
printDataTableHeader();
printDataTable(dat, 0, nDetsTot, nSpawnedDetsTot, iter_time);
// Main FCIQMC loop
for (int iter = 1; iter <= schd.maxIterFCIQMC; iter++) {
time_start = getTime();
walkers.firstEmpty = 0;
walkers.lastEmpty = -1;
spawn.nDets = 0;
spawn.currProcSlots = spawn.firstProcSlots;
fill(dat.walkerPop.begin(), dat.walkerPop.end(), 0.0);
fill(dat.EProj.begin(), dat.EProj.end(), 0.0);
fill(dat.HFAmp.begin(), dat.HFAmp.end(), 0.0);
fill(dat.nAnnihil.begin(), dat.nAnnihil.end(), 0.0);
// Check whether to release the fixed node
if (schd.releaseNodeFCIQMC) {
if (iter == schd.releaseNodeIter) {
schd.applyNodeFCIQMC = false;
schd.diagonalDumping = false;
}
}
//cout << walkers << endl;
// The number of core determinants found, accumulated during the
// loop over walkers
int nCoreFound = 0;
// Loop over all walkers/determinants
for (int iDet=0; iDet<walkers.nDets; iDet++) {
// Check if this is a core determinant, if doing semi-stochastic
bool coreDet = false;
if (schd.semiStoch) {
simpleDet parentSimpleDet = walkers.dets[iDet].getSimpleDet();
if (core.ht.find(parentSimpleDet) != core.ht.end()) {
coreDet = true;
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
core.amps[nCoreFound][iReplica] = walkers.amps[iDet][iReplica];
}
// Store the position of this core determinant in the main list
core.indices[nCoreFound] = iDet;
nCoreFound += 1;
}
}
// Is this unoccupied for all replicas? If so, add to the list of
// empty slots
if (walkers.allUnoccupied(iDet)) {
// Never remove core dets from the main list
if (!coreDet) {
walkers.lastEmpty += 1;
walkers.emptyDets[walkers.lastEmpty] = iDet;
}
continue;
}
TrialWalk& parentWalk = walkers.trialWalk[iDet];
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
// Update the initiator flag, if necessary
int parentFlags = 0;
if (schd.initiator) {
double amp = walkers.amps[iDet][iReplica];
// Condition for this det to be an initiator:
bool initDet = abs(amp) > schd.initiatorThresh || coreDet;
if (initDet) {
// This walker is an initiator, so set the flag for the
// appropriate replica
parentFlags |= 1 << iReplica;
}
}
// Number of spawnings to attempt
int nAttempts = max(1.0, round(abs(walkers.amps[iDet][iReplica]) * schd.nAttemptsEach));
double parentAmp = walkers.amps[iDet][iReplica] * schd.nAttemptsEach / nAttempts;
// Perform one spawning attempt for each 'walker' of weight parentAmp
for (int iAttempt=0; iAttempt<nAttempts; iAttempt++) {
double pgen = 0.0, pgen2 = 0.0;
int ex1, ex2;
Determinant childDet, childDet2;
generateExcitation(hb, I1, I2, walkers.dets[iDet], nel, childDet, childDet2,
pgen, pgen2, ex1, ex2);
// pgen=0 is set when a null excitation is returned
if (pgen > 1.e-15) {
// If the parent is a core determinant, check if we need to
// cancel the spawning
bool allowSpawn = true;
if (coreDet) {
simpleDet childSimpleDet = childDet.getSimpleDet();
if (core.ht.find(childSimpleDet) != core.ht.end()) {
allowSpawn = false;
}
}
if (allowSpawn) {
attemptSpawning(wave, parentWalk, walkers.dets[iDet], childDet, spawn, I1, I2,
coreE, schd.nAttemptsEach, parentAmp, parentFlags, iReplica,
schd.tau, schd.minSpawn, pgen, ex1, ex2);
}
}
if (pgen2 > 1.e-15) {
bool allowSpawn = true;
if (coreDet) {
simpleDet childSimpleDet2 = childDet2.getSimpleDet();
if (core.ht.find(childSimpleDet2) != core.ht.end()) {
allowSpawn = false;
}
}
if (allowSpawn) {
attemptSpawning(wave, parentWalk, walkers.dets[iDet], childDet2, spawn, I1, I2,
coreE, schd.nAttemptsEach, parentAmp, parentFlags, iReplica,
schd.tau, schd.minSpawn, pgen2, ex1, ex2);
}
}
} // Loop over spawning attempts
} // Loop over replicas
}
if (schd.semiStoch) {
core.determProjection(schd.tau);
}
// Perform annihilation of spawned walkers
spawn.communicate();
spawn.compress(dat.nAnnihil);
// Calculate energies involving multiple replicas
if (schd.nreplicas == 2) {
calcVarEnergy(walkers, spawn, core, I1, I2, coreE, schd.tau,
dat.EVarNumAll, dat.EVarDenomAll);
if (schd.calcEN2) {
calcEN2Correction(walkers, spawn, I1, I2, coreE, schd.tau,
dat.EVarNumAll, dat.EVarDenomAll, dat.EN2All);
}
}
performDeathAllWalkers(walkers, I1, I2, core, coreE, dat.Eshift, schd.tau);
if (schd.semiStoch) {
core.determAnnihilation(walkers.amps, dat.nAnnihil);
}
spawn.mergeIntoMain(wave, walk, walkers, core, dat.nAnnihil, schd.minPop, schd.initiator, work);
// Stochastic rounding of small walkers
walkers.stochasticRoundAll(schd.minPop, core.ht);
walkers.calcStats(dat, HFDet, I1, I2, coreE);
communicateEstimates(dat, walkers.nDets, spawn.nDets, nDetsTot, nSpawnedDetsTot);
updateShift(dat.Eshift, dat.varyShift, dat.walkerPopTot, dat.walkerPopOldTot,
schd.targetPop, schd.shiftDamping, schd.tau);
printDataTable(dat, iter, nDetsTot, nSpawnedDetsTot, iter_time);
dat.walkerPopOldTot = dat.walkerPopTot;
time_end = getTime();
iter_time = time_end - time_start;
}
total_time = getTime() - startofCalc;
printFinalStats(dat.walkerPop, walkers.nDets, spawn.nDets, total_time);
}
// Find the weight of the spawned walker
// If it is above a minimum threshold, then always spawn
// Otherwsie, stochastically round it up to the threshold or down to 0
template<typename Wave, typename TrialWalk>
void attemptSpawning(Wave& wave, TrialWalk& walk, Determinant& parentDet, Determinant& childDet,
spawnFCIQMC& spawn, oneInt &I1, twoInt &I2, double& coreE,
const int nAttemptsEach, const double parentAmp, const int parentFlags,
const int iReplica, const double tau, const double minSpawn,
const double pgen, const int ex1, const int ex2)
{
bool childSpawned = true;
double HElem = Hij(parentDet, childDet, I1, I2, coreE);
double overlapRatio;
if (schd.applyNodeFCIQMC || schd.importanceSampling) {
// Calculate the ratio of overlaps, and the parity factor
int norbs = Determinant::norbs;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
overlapRatio = wave.getOverlapFactor(I, J, A, B, walk, false);
double parityFac = wave.parityFactor(parentDet, ex2, I, J, A, B);
overlapRatio *= parityFac;
}
// Apply the fixed/partial node approximation
if (schd.applyNodeFCIQMC) {
if (HElem * overlapRatio > 0.0) {
HElem *= (1.0 - schd.partialNodeFactor);
}
}
if (schd.importanceSampling) {
HElem *= overlapRatio;
}
double pgen_tot = pgen * nAttemptsEach;
double childAmp = - tau * parentAmp * HElem / pgen_tot;
if (abs(childAmp) < minSpawn) {
stochastic_round(minSpawn, childAmp, childSpawned);
}
if (childSpawned) {
int proc = getProc(childDet, spawn.DetLenMin);
// Find the appropriate place in the spawned list for the processor
// of the newly-spawned walker
int ind = spawn.currProcSlots[proc];
spawn.dets[ind] = childDet.getSimpleDet();
// Set the child amplitude for the correct replica - all others are 0
for (int i=0; i<schd.nreplicas; i++) {
if (i == iReplica) {
spawn.amps[ind][i] = childAmp;
} else {
spawn.amps[ind][i] = 0.0;
}
}
if (schd.initiator) spawn.flags[ind] = parentFlags;
spawn.currProcSlots[proc] += 1;
}
}
// Calculate and return the numerator and denominator of the variational
// energy estimator. This can be used in replicas FCIQMC simulations.
template<typename TrialWalk>
void calcVarEnergy(walkersFCIQMC<TrialWalk>& walkers, const spawnFCIQMC& spawn,
semiStoch& core, const oneInt& I1, const twoInt& I2, double& coreE,
const double tau, double& varEnergyNumAll, double& varEnergyDenomAll)
{
double varEnergyNum = 0.0;
double varEnergyDenom = 0.0;
// Contributions from the diagonal of the Hamiltonian
for (int iDet=0; iDet<walkers.nDets; iDet++) {
double HDiag = walkers.dets[iDet].Energy(I1, I2, coreE);
varEnergyNum += HDiag * walkers.amps[iDet][0] * walkers.amps[iDet][1];
varEnergyDenom += walkers.amps[iDet][0] * walkers.amps[iDet][1];
}
// Contributions from the off-diagonal of the Hamiltonian
for (int j=0; j<spawn.nDets; j++) {
Determinant det_j = Determinant(spawn.dets[j]);
if (walkers.ht.find(det_j) != walkers.ht.end()) {
int iDet = walkers.ht[det_j];
double spawnAmp1 = spawn.amps[j][0];
double spawnAmp2 = spawn.amps[j][1];
double currAmp1 = walkers.amps[iDet][0];
double currAmp2 = walkers.amps[iDet][1];
varEnergyNum -= ( currAmp1 * spawnAmp2 + spawnAmp1 * currAmp2 ) / ( 2.0 * tau);
}
}
// Semi-stochastic contributions
if (schd.semiStoch) {
for (int j=0; j<core.nDetsThisProc; j++) {
double spawnAmp1 = core.amps[j][0];
double spawnAmp2 = core.amps[j][1];
double currAmp1 = walkers.amps[core.indices[j]][0];
double currAmp2 = walkers.amps[core.indices[j]][1];
varEnergyNum -= ( currAmp1 * spawnAmp2 + spawnAmp1 * currAmp2 ) / ( 2.0 * tau);
}
}
#ifdef SERIAL
varEnergyNumAll = varEnergyNum;
varEnergyDenomAll = varEnergyDenom;
#else
MPI_Allreduce(&varEnergyNum, &varEnergyNumAll, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&varEnergyDenom, &varEnergyDenomAll, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
}
// Calculate the numerator of the second-order Epstein-Nesbet correction
// to the energy. This is for use in replica initiator simulations.
template<typename TrialWalk>
void calcEN2Correction(walkersFCIQMC<TrialWalk>& walkers, const spawnFCIQMC& spawn, const oneInt& I1,
const twoInt& I2, double& coreE, const double tau, const double varEnergyNum,
const double varEnergyDenom, double& EN2All)
{
double EN2 = 0.0;
double EVar = varEnergyNum / varEnergyDenom;
// Loop over all spawned walkers
for (int j=0; j<spawn.nDets; j++) {
// If this determinant is not already occupied, then we may need
// to cancel the spawning due to initiator rules:
if (walkers.ht.find(spawn.dets[j]) == walkers.ht.end()) {
// If the initiator flag is not set on both replicas, then both
// spawnings are about to be cancelled
bitset<max_nreplicas> initFlags(spawn.flags[j]);
if ( (!initFlags.test(0)) && (!initFlags.test(1)) ) {
double spawnAmp1 = spawn.amps[j][0];
double spawnAmp2 = spawn.amps[j][1];
Determinant fullDet(spawn.dets[j]);
double HDiag = fullDet.Energy(I1, I2, coreE);
EN2 += ( spawnAmp1 * spawnAmp2 ) / ( EVar - HDiag );
}
}
}
EN2 /= tau*tau;
#ifdef SERIAL
EN2All = EN2;
#else
MPI_Allreduce(&EN2, &EN2All, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
}
// Perform the death step for the determinant at position iDet in
// the walkers.det array
template<typename TrialWalk>
void performDeath(const int iDet, walkersFCIQMC<TrialWalk>& walkers, oneInt &I1, twoInt &I2,
semiStoch& core, double& coreE, const vector<double>& Eshift, const double tau)
{
bool coreDet = false;
if (schd.semiStoch) {
simpleDet parentSimpleDet = walkers.dets[iDet].getSimpleDet();
coreDet = core.ht.find(parentSimpleDet) != core.ht.end();
}
if ( walkers.validWalker(iDet) || coreDet ) {
double parentE;
if (schd.diagonalDumping) {
parentE = walkers.diagH[iDet] + walkers.SVTotal[iDet] * schd.partialNodeFactor;
} else {
parentE = walkers.diagH[iDet];
}
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
double fac = tau * ( parentE - Eshift[iReplica] );
if (schd.expApprox && fac > 1.0) {
expApproxLogging(walkers, iDet, iReplica, fac);
walkers.amps[iDet][iReplica] *= exp(-fac);
} else {
walkers.amps[iDet][iReplica] -= fac * walkers.amps[iDet][iReplica];
}
}
// If the population is now 0 on all replicas then remove the ht entry
if (walkers.allUnoccupied(iDet) && !coreDet) {
walkers.ht.erase(walkers.dets[iDet]);
walkers.lastEmpty += 1;
walkers.emptyDets[walkers.lastEmpty] = iDet;
}
}
}
template<typename TrialWalk>
void expApproxLogging(walkersFCIQMC<TrialWalk>& walkers, int iDet, int iReplica, double fac) {
if (abs(walkers.amps[iDet][iReplica]) > 1.0e-12) {
cout << "# Exponential approximation applied." << endl;
cout << "# Determinant: " << walkers.dets[iDet] << endl;
cout << "# Population: " << walkers.amps[iDet][iReplica] << endl;
cout << "# Overlap: " << walkers.ovlp[iDet] << endl;
cout << "# Sign-flip potential: " << walkers.SVTotal[iDet] << endl;
cout << "# Total diagonal contribution: " << -fac << endl;
}
}
// Perform death for *all* walkers in the walker array, held in
// walkers.dets
template<typename TrialWalk>
void performDeathAllWalkers(walkersFCIQMC<TrialWalk>& walkers, oneInt &I1, twoInt &I2,
semiStoch& core, double& coreE, const vector<double>& Eshift, const double tau)
{
for (int iDet=0; iDet<walkers.nDets; iDet++) {
bool coreDet = false;
if (schd.semiStoch) {
simpleDet parentSimpleDet = walkers.dets[iDet].getSimpleDet();
coreDet = core.ht.find(parentSimpleDet) != core.ht.end();
}
if ( walkers.validWalker(iDet) || coreDet ) {
double parentE;
if (schd.diagonalDumping) {
parentE = walkers.diagH[iDet] + walkers.SVTotal[iDet] * schd.partialNodeFactor;
} else {
parentE = walkers.diagH[iDet];
}
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
double fac = tau * ( parentE - Eshift[iReplica] );
if (schd.expApprox && fac > 1.0) {
expApproxLogging(walkers, iDet, iReplica, fac);
walkers.amps[iDet][iReplica] *= exp(-fac);
} else {
walkers.amps[iDet][iReplica] -= fac * walkers.amps[iDet][iReplica];
}
}
// If the population is now 0 on all replicas then remove the ht entry
if (walkers.allUnoccupied(iDet) && !coreDet) {
walkers.ht.erase(walkers.dets[iDet]);
walkers.lastEmpty += 1;
walkers.emptyDets[walkers.lastEmpty] = iDet;
}
}
}
}
// For values which are calculated on each MPI process, sum these
// quantities over all processes to obtain the final total values.
void communicateEstimates(dataFCIQMC& dat, const int nDets, const int nSpawnedDets,
int& nDetsTot, int& nSpawnedDetsTot)
{
#ifdef SERIAL
dat.walkerPopTot = dat.walkerPop;
dat.EProjTot = dat.EProj;
dat.HFAmpTot = dat.HFAmp;
dat.trialEProjTot = dat.trialEProj;
dat.ampSumTot = dat.ampSum;
nDetsTot = nDets;
nSpawnedDetsTot = nSpawnedDets;
#else
MPI_Allreduce(&dat.walkerPop.front(), &dat.walkerPopTot.front(), schd.nreplicas, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&dat.EProj.front(), &dat.EProjTot.front(), schd.nreplicas, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&dat.HFAmp.front(), &dat.HFAmpTot.front(), schd.nreplicas, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&dat.trialEProj.front(), &dat.trialEProjTot.front(), schd.nreplicas, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&dat.ampSum.front(), &dat.ampSumTot.front(), schd.nreplicas, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&dat.nAnnihil.front(), &dat.nAnnihilTot.front(), schd.nreplicas, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&nDets, &nDetsTot, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&nSpawnedDets, &nSpawnedDetsTot, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
#endif
}
// If the shift has started to vary (if varyShift is true) then update
// the shift estimator here. If not, then check if we should now start to
// vary the shift (if the walker population is above the target).
void updateShift(vector<double>& Eshift, vector<bool>& varyShift,
const vector<double>& walkerPop,
const vector<double>& walkerPopOld, const double targetPop,
const double shiftDamping, const double tau)
{
for (int iReplica = 0; iReplica<schd.nreplicas; iReplica++) {
if ((!varyShift.at(iReplica)) && walkerPop[iReplica] > targetPop) {
varyShift.at(iReplica) = true;
}
if (varyShift.at(iReplica)) {
Eshift.at(iReplica) = Eshift.at(iReplica) -
(shiftDamping/tau) * log(walkerPop.at(iReplica)/walkerPopOld.at(iReplica));
}
}
}
// Print the column labels for the main data table
void printDataTableHeader()
{
if (commrank == 0) {
cout << "# 1. Iter";
cout << " 2. nDets";
cout << " 3. nSpawned";
// This is the column label
int label;
int nColPerReplica;
int annihilInd;
if (schd.printAnnihilStats) {
if (schd.trialWFEstimator) {
nColPerReplica = 7;
annihilInd = 6;
} else {
nColPerReplica = 5;
annihilInd = 4;
}
} else {
if (schd.trialWFEstimator) {
nColPerReplica = 6;
} else {
nColPerReplica = 4;
}
}
// This loop is for properties printed on each replica
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
for (int j=0; j<nColPerReplica; j++) {
string header;
label = nColPerReplica*iReplica + j + 4;
header.append(to_string(label));
if (j==0) {
header.append(". Shift_");
} else if (j==1) {
header.append(". nWalkers_");
} else if (j==2) {
header.append(". Energy_Num_");
} else if (j==3) {
header.append(". Energy_Denom_");
}
if (schd.trialWFEstimator) {
if (j==4) {
header.append(". Trial_E_Num_");
} else if (j==5) {
header.append(". Trial_E_Denom_");
}
}
if (schd.printAnnihilStats) {
if (j==annihilInd) {
header.append(". nAnnihil_");
}
}
header.append(to_string(iReplica+1));
cout << right << setw(21) << header;
}
}
if (schd.nreplicas == 2) {
label += 1;
cout << right << setw(6) << label << ". Var_Energy_Num";
label += 1;
cout << right << setw(4) << label << ". Var_Energy_Denom";
if (schd.calcEN2) {
label += 1;
cout << right << setw(6) << label << ". EN2_Numerator";
}
}
label += 1;
cout << right << setw(5) << label << ". Time\n";
}
}
void printDataTable(const dataFCIQMC& dat, const int iter, const int nDets,
const int nSpawned, const double iter_time)
{
if (commrank == 0) {
printf ("%10d ", iter);
printf ("%10d ", nDets);
printf ("%10d ", nSpawned);
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
printf ("%18.10f ", dat.Eshift[iReplica]);
printf ("%18.10f ", dat.walkerPopTot[iReplica]);
printf ("%18.10f ", dat.EProjTot[iReplica]);
printf ("%18.10f ", dat.HFAmpTot[iReplica]);
if (schd.trialWFEstimator) {
printf ("%18.10f ", dat.trialEProjTot[iReplica]);
printf ("%18.10f ", dat.ampSumTot[iReplica]);
}
if (schd.printAnnihilStats) {
printf ("%18.10f ", dat.nAnnihilTot[iReplica]);
}
}
if (schd.nreplicas == 2) {
printf ("%.12e ", dat.EVarNumAll);
printf ("%.12e ", dat.EVarDenomAll);
if (schd.calcEN2) {
printf ("%.12e ", dat.EN2All);
}
}
printf ("%8.4f\n", iter_time);
}
}
void printFinalStats(const vector<double>& walkerPop, const int nDets,
const int nSpawnDets, const double total_time)
{
int parallelReport[commsize];
double parallelReportD[commsize];
if (commrank == 0) {
cout << "# Total time: " << getTime() - startofCalc << endl;
}
#ifndef SERIAL
MPI_Gather(&walkerPop[0], 1, MPI_DOUBLE, ¶llelReportD, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if (commrank == 0) {
cout << "# Min # walkers on proc: " << *min_element(parallelReportD, parallelReportD + commsize) << endl;
cout << "# Max # walkers on proc: " << *max_element(parallelReportD, parallelReportD + commsize) << endl;
}
MPI_Gather(&nDets, 1, MPI_INT, ¶llelReport, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (commrank == 0) {
cout << "# Min # determinants on proc: " << *min_element(parallelReport, parallelReport + commsize) << endl;
cout << "# Max # determinants on proc: " << *max_element(parallelReport, parallelReport + commsize) << endl;
}
MPI_Gather(&nSpawnDets, 1, MPI_INT, ¶llelReport, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (commrank == 0) {
cout << "# Min # determinants spawned on proc: " << *min_element(parallelReport, parallelReport + commsize) << endl;
cout << "# Max # determinants spawned on proc: " << *max_element(parallelReport, parallelReport + commsize) << endl;
}
#endif
}
// Instantiate needed templates
template void runFCIQMC(TrivialWF& wave, TrivialWalk& walk,
const int norbs, const int nel,
const int nalpha, const int nbeta);
template void runFCIQMC(CorrelatedWavefunction<Jastrow, AGP>& wave,
Walker<Jastrow, AGP>& walk,
const int norbs, const int nel,
const int nalpha, const int nbeta);
template void runFCIQMC(CorrelatedWavefunction<Jastrow, Slater>& wave,
Walker<Jastrow, Slater>& walk,
const int norbs, const int nel,
const int nalpha, const int nbeta);
template void runFCIQMC(SelectedCI& wave, SimpleWalker& walk,
const int norbs, const int nel,
const int nalpha, const int nbeta);
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef _CX_MEMORYSTACK_H
#define _CX_MEMORYSTACK_H
#include <cstddef> // for std::size_t
#include <string.h> // for memset
using std::size_t;
typedef unsigned int
uint;
namespace ct {
/// An object managing a continuous block of memory. Used for allocation-free
/// temporary work space storage.
/// Notes:
/// - Deallocations must occur in reverse allocation order. A deallocation
/// FREES ALL MEMORY ALLOCATED AFTER THE ALLOCATION POINT.
/// - Both alloc and free are effectively non-ops in terms of computational
/// cost. Any work space, no matter how large or small, can be allocated
/// at will.
/// - There is no memory fragmentation.
struct FMemoryStack
{
/// allocate nSizeInBytes bytes off the stack. Return pointer to start.
virtual void* Alloc( size_t nSizeInBytes ) = 0;
/// Free pointer p on stack. Should be an address returned by Alloc.
virtual void Free( void *p ) = 0;
/// return amount of memory left (in bytes).
virtual size_t MemoryLeft() = 0;
/// allocate nObjects objects of size sizeof(T). Store pointer in p.
/// Usage:
/// MyType *p;
/// Mem.Alloc(p, 10); // allocate array of 10 objects of type MyType.
template<class T>
inline void Alloc( T *&p, std::size_t nObjects = 1 ){
p = reinterpret_cast<T*>( this->Alloc( sizeof(T) * nObjects ) );
// note: objects are not constructed. Use only for PODs!
}
/// as Alloc(), but set allocated memory to zero.
template<class T>
inline void ClearAlloc( T *&p, std::size_t nObjects = 1 ){
Alloc(p, nObjects);
::memset(p, 0, sizeof(T) * nObjects);
}
template<class T>
inline T* AllocN(std::size_t nObjects, T const &){
return reinterpret_cast<T*>( this->Alloc(sizeof(T) * nObjects) );
}
template<class T>
inline T* ClearAllocN(std::size_t nObjects, T const &){
T *p;
this->Alloc(p, nObjects);
::memset(p, 0, sizeof(T) * nObjects);
return p;
}
/// align stack to next 'Boundary' (must be power of two)-boundary .
void Align( uint Boundary );
virtual ~FMemoryStack();
};
/// A memory stack defined by a base pointer and a size. Can own
/// the memory managed, but can also be put on memory allocated from
/// elsewhere.
struct FMemoryStack2 : public FMemoryStack {
/// creates a stack of 'nInitialSize' bytes on the global heap.
/// If nInitialSize is 0, the stack is created empty and a storage
/// area can be later assigned by AssignMemory() or Create().
explicit FMemoryStack2( std::size_t nInitialSize = 0 ) : m_pData(0) { Create(nInitialSize); }
/// if pBase != 0 && nActualSize >= nNeededSize:
/// creates a stack of 'nActualSize' bytes at memory pBase (i.e., at a memory location given from the outside)
/// otherwise
/// construction equivalent to FMemoryStack2((nNeededSize != 0)? nNeededSize : nActualSize).
FMemoryStack2( char *pBase, std::size_t nActualSize, std::size_t nNeededSize = 0 );
inline void PushTopMark();
inline void PopTopMark();
void* Alloc( size_t nSizeInBytes ); // override
using FMemoryStack::Alloc;
void Free( void *p ); // override
size_t MemoryLeft(); // override
~FMemoryStack2(); // override
/// create a new stack of size 'nSize' bytes on the global heap.
void Create( std::size_t nSize );
/// create a new stack in the storage area marked by 'pBase',
/// of 'nSize' bytes. This assumes that pBase is already allocated
/// from elsewhere.
void AssignMemory( char *pBase_, std::size_t nSize );
void Destroy();
//private:
std::size_t
m_Pos, m_Size;
char *m_pData;
bool m_bOwnMemory; // if true, we allocated m_pData and need to free it on Destroy().
private:
FMemoryStack2(FMemoryStack2 const &); // not implemented
void operator = (FMemoryStack2 const &); // not implemented
};
/// split a base memory stack into sub-stacks, one for each openmp thread.
struct FMemoryStackArray
{
explicit FMemoryStackArray( FMemoryStack &BaseStack );
~FMemoryStackArray();
FMemoryStack2
*pSubStacks;
FMemoryStack
*pBaseStack;
uint
nThreads;
// return substack for the calling openmp thread.
FMemoryStack2 &GetStackOfThread();
// destroy this object (explicitly) already now
void Release();
char
*pStackBase;
private:
FMemoryStackArray(FMemoryStackArray const &); // not implemented
void operator = (FMemoryStackArray const &); // not implemented
};
} // namespace ct
#endif // _CX_MEMORYSTACK_H
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Correlator_HEADER_H
#define Correlator_HEADER_H
#include <Eigen/Dense>
#include <vector>
#include <iostream>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
class Determinant;
class BigDeterminant;
/**
* A correlator contains a tuple of local sites and contains
* a set of 4^n parameters, where n is the number of sites in the
* correlator
*/
class Correlator {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & asites & bsites & Variables;
}
public:
std::vector<int> asites,
bsites; // Separately store the alpha and beta sites, although in current version they are always the same
std::vector<double> Variables; //the total number of variables in a single Correlator 2^{na+nb} number of variables
//Dummy constructor
Correlator () {};
/**
* Takes the set of alpha sites and beta sites and initial set of parameters
* Internally these sites are always arranges in asending order
*/
Correlator (std::vector<int>& pasites, std::vector<int>& pbsites, double iv=1.0);
/**
* Takes an occupation number representation of a determinant
* in the local orbital basis and calculates the overlap with
* the correlator
* PARAMS:
*
* Determinant: the occupation number representation as an input
*
* RETURN:
* <d|correlator>
*/
double Overlap (const Determinant& d) const;
double Overlap (const BigDeterminant& d) const;
/**
* Takes an occupation number representation of two determinants
* in the local orbital basis and calculates the ratio of overlaps
* <d1|correlator>/<d2|correlator>
* PARAMS:
*
* Determinant: the occupation number representation as an input
*
* RETURN:
* <d1|correlator>/<d2|correlator>
*/
double OverlapRatio(const Determinant& d1, const Determinant& d2) const;
double OverlapRatio(const BigDeterminant& d1, const BigDeterminant& d2) const;
/**
* Takes an occupation number representation of a determinant
* in the local orbital basis and calculates the overlap
* the correlator and also the overlap of the determinant
* with the tangent vector w.r.t to all the
* parameters in this correlator
*
* PARAMS:
*
* Determinant: the occupation number representation of the determinant
* grad : the vector of the gradient. This vector is long and contains
* the space for storing gradients with respect to all the parameters
* in the wavefunction and not just this correlator and so the index startIndex
* is needed to indentify at what index should we start populating the
* gradient w.r.t to this correlator in the vector
* ovlp : <d|correlator>
* startIndex : The location in the vector gradient from where to start populating
* the gradient w.r.t to the current correlator
*/
void OverlapWithGradient (const Determinant& d,
Eigen::VectorBlock<Eigen::VectorXd>& grad,
const double& ovlp,
const long& startIndex) const;
friend std::ostream& operator<<(std::ostream& os, const Correlator& c);
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
//#define EIGEN_USE_MKL_ALL
#include <algorithm>
#include <random>
#include <chrono>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Core>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include <boost/function.hpp>
#include <boost/functional.hpp>
#include <boost/bind.hpp>
#include "evaluateE.h"
#include "Determinants.h"
#include "input.h"
#include "integral.h"
#include "SHCIshm.h"
#include "math.h"
#include "Profile.h"
#include "CIWavefunction.h"
#include "CorrelatedWavefunction.h"
#include "JastrowMultiSlater.h"
#include "ResonatingWavefunction.h"
#include "ResonatingTRWavefunction.h"
#include "TRWavefunction.h"
#include "PermutedWavefunction.h"
#include "PermutedTRWavefunction.h"
#include "NNBS.h"
#include "SelectedCI.h"
#include "SimpleWalker.h"
#include "Lanczos.h"
#include "SCCI.h"
#include "SCPT.h"
#include "MRCI.h"
#include "EOM.h"
#include "runVMC.h"
using namespace Eigen;
using namespace boost;
using namespace std;
int main(int argc, char *argv[])
{
#ifndef SERIAL
boost::mpi::environment env(argc, argv);
boost::mpi::communicator world;
#endif
startofCalc = getTime();
initSHM();
//license();
if (commrank == 0) {
std::system("echo User:; echo $USER");
std::system("echo Hostname:; echo $HOSTNAME");
std::system("echo CPU info:; lscpu | head -15");
std::system("echo Computation started at:; date");
cout << "git commit: " << GIT_HASH << ", branch: " << GIT_BRANCH << ", compiled at: " << COMPILE_TIME << endl << endl;
cout << "nproc used: " << commsize << " (NB: stochasticIter below is per proc)" << endl << endl;
}
string inputFile = "input.dat";
if (argc > 1)
inputFile = string(argv[1]);
readInput(inputFile, schd, false);
generator = std::mt19937(schd.seed + commrank);
readIntegralsAndInitializeDeterminantStaticVariables("FCIDUMP");
if (schd.numActive == -1) schd.numActive = Determinant::norbs;
//calculate the hessian/gradient
if (schd.wavefunctionType == "cpsslater") {
CorrelatedWavefunction<CPS, Slater> wave; Walker<CPS, Slater> walk;
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cpsagp") {
CorrelatedWavefunction<CPS, AGP> wave; Walker<CPS, AGP> walk;
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cpspfaffian") {
CorrelatedWavefunction<CPS, Pfaffian> wave; Walker<CPS, Pfaffian> walk;
runVMC(wave, walk);
}
if (schd.wavefunctionType == "jastrowslater") {
CorrelatedWavefunction<Jastrow, Slater> wave; Walker<Jastrow, Slater> walk;
runVMC(wave, walk);
if (schd.printJastrow && commrank==0) wave.printCorrToFile();
}
if (schd.wavefunctionType == "jastrowmultislater") {
CorrelatedWavefunction<Jastrow, MultiSlater> wave; Walker<Jastrow, MultiSlater> walk;
runVMC(wave, walk);
}
if (schd.wavefunctionType == "jastrowmultislater2") {
JastrowMultiSlater wave; JastrowMultiSlaterWalker walk;
runVMC(wave, walk);
if (commrank == 0 && schd.printLevel >= 9) {
cout << "intermediate build time: " << wave.intermediateBuildTime << endl;
cout << "ci iteration time: " << wave.ciIterationTime << endl;
cout << "walker update time: " << walk.updateTime << endl;
}
}
if (schd.wavefunctionType == "resonatingwavefunction") {
ResonatingWavefunction wave; ResonatingWalker walk;
runVMC(wave, walk);
}
if (schd.wavefunctionType == "resonatingtrwavefunction") {
ResonatingTRWavefunction wave; ResonatingTRWalker walk;
runVMC(wave, walk);
}
if (schd.wavefunctionType == "trwavefunction") {
TRWavefunction wave; TRWalker walk;
runVMC(wave, walk);
}
if (schd.wavefunctionType == "permutedwavefunction") {
PermutedWavefunction wave; PermutedWalker walk;
runVMC(wave, walk);
}
if (schd.wavefunctionType == "permutedtrwavefunction") {
PermutedTRWavefunction wave; PermutedTRWalker walk;
runVMC(wave, walk);
}
if (schd.wavefunctionType == "nnbs") {
NNBS wave; NNBSWalker walk;
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "jastrowagp") {
CorrelatedWavefunction<Jastrow, AGP> wave; Walker<Jastrow, AGP> walk;
runVMC(wave, walk);
if (schd.printJastrow && commrank==0) wave.printCorrToFile();
}
else if (schd.wavefunctionType == "jastrowpfaffian") {
CorrelatedWavefunction<Jastrow, Pfaffian> wave; Walker<Jastrow, Pfaffian> walk;
runVMC(wave, walk);
if (schd.printJastrow && commrank==0) wave.printCorrToFile();
}
else if (schd.wavefunctionType == "rbm") {
CorrelatedWavefunction<RBM, Slater> wave; Walker<RBM, Slater> walk;
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "jrbms") {
CorrelatedWavefunction<JRBM, Slater> wave; Walker<JRBM, Slater> walk;
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "jrbmp") {
CorrelatedWavefunction<JRBM, Pfaffian> wave; Walker<JRBM, Pfaffian> walk;
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cicpsslater") {
CIWavefunction<CorrelatedWavefunction<CPS, Slater>, Walker<CPS, Slater>, SpinFreeOperator> wave; Walker<CPS, Slater> walk;
wave.appendSinglesToOpList(0.0); wave.appendScreenedDoublesToOpList(0.0);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cicpsagp") {
CIWavefunction<CorrelatedWavefunction<CPS, AGP>, Walker<CPS, AGP>, SpinFreeOperator> wave; Walker<CPS, AGP> walk;
wave.appendSinglesToOpList(0.0); wave.appendScreenedDoublesToOpList(0.0);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cicpspfaffian") {
CIWavefunction<CorrelatedWavefunction<CPS, Pfaffian>, Walker<CPS, Pfaffian>, SpinFreeOperator> wave; Walker<CPS, Pfaffian> walk;
wave.appendSinglesToOpList(0.0); wave.appendScreenedDoublesToOpList(0.0);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cijastrowslater") {
//CIWavefunction<CorrelatedWavefunction<Jastrow, Slater>, Walker<Jastrow, Slater>, SpinFreeOperator> wave; Walker<Jastrow, Slater> walk;
CIWavefunction<CorrelatedWavefunction<Jastrow, Slater>, Walker<Jastrow, Slater>, Operator> wave; Walker<Jastrow, Slater> walk;
wave.appendSinglesToOpList(0.0); wave.appendScreenedDoublesToOpList(0.0);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cijastrowagp") {
CIWavefunction<CorrelatedWavefunction<Jastrow, AGP>, Walker<Jastrow, AGP>, SpinFreeOperator> wave; Walker<Jastrow, AGP> walk;
wave.appendSinglesToOpList(0.0); wave.appendScreenedDoublesToOpList(0.0);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "cijastrowpfaffian") {
CIWavefunction<CorrelatedWavefunction<Jastrow, Pfaffian>, Walker<Jastrow, Pfaffian>, SpinFreeOperator> wave; Walker<Jastrow, Pfaffian> walk;
wave.appendSinglesToOpList(0.0); wave.appendScreenedDoublesToOpList(0.0);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "sci") {
CIWavefunction<SelectedCI, SimpleWalker, Operator> wave; SimpleWalker walk;
wave.appendSinglesToOpList(0.0); wave.appendScreenedDoublesToOpList(0.0);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "lanczoscpslater") {
Lanczos<CorrelatedWavefunction<CPS, Slater>> wave; Walker<CPS, Slater> walk;
wave.initWalker(walk);
wave.optimizeWave(walk);
wave.writeWave();
}
else if (schd.wavefunctionType == "lanczoscpsagp") {
Lanczos<CorrelatedWavefunction<CPS, AGP>> wave; Walker<CPS, AGP> walk;
wave.initWalker(walk);
wave.optimizeWave(walk);
wave.writeWave();
}
else if (schd.wavefunctionType == "lanczoscpspfaffian") {
Lanczos<CorrelatedWavefunction<CPS, Pfaffian>> wave; Walker<CPS, Pfaffian> walk;
wave.initWalker(walk);
wave.optimizeWave(walk);
wave.writeWave();
}
else if (schd.wavefunctionType == "lanczosjastrowslater") {
Lanczos<CorrelatedWavefunction<Jastrow, Slater>> wave; Walker<Jastrow, Slater> walk;
wave.initWalker(walk);
wave.optimizeWave(walk, schd.alpha);
wave.writeWave();
}
else if (schd.wavefunctionType == "lanczospermutedtrwavefunction") {
Lanczos<PermutedTRWavefunction> wave; PermutedTRWalker walk;
wave.initWalker(walk);
wave.optimizeWave(walk, schd.alpha);
wave.writeWave();
}
else if (schd.wavefunctionType == "lanczosjastrowagp") {
Lanczos<CorrelatedWavefunction<Jastrow, AGP>> wave; Walker<Jastrow, AGP> walk;
wave.initWalker(walk);
wave.optimizeWave(walk);
wave.writeWave();
}
else if (schd.wavefunctionType == "lanczosjastrowpfaffian") {
Lanczos<CorrelatedWavefunction<Jastrow, Pfaffian>> wave; Walker<Jastrow, Pfaffian> walk;
wave.initWalker(walk);
wave.optimizeWave(walk);
wave.writeWave();
}
else if (schd.wavefunctionType == "lanczossci") {
Lanczos<SelectedCI> wave; SimpleWalker walk;
wave.initWalker(walk);
double alpha = wave.optimizeWave(walk, schd.alpha);
wave.writeWave();
}
else if (schd.wavefunctionType == "scci") {
schd.usingFOIS = true;
SCCI<SelectedCI> wave; SimpleWalker walk;
wave.initWalker(walk);
if (schd.method == linearmethod) {
wave.optimizeWaveCTDirect(walk);
wave.optimizeWaveCTDirect(walk);
}
else {
runVMC(wave, walk);
wave.calcEnergy(walk);
}
wave.writeWave();
}
else if (schd.wavefunctionType == "MRCI") {
schd.usingFOIS = true;
MRCI<Jastrow, Slater> wave; MRCIWalker<Jastrow, Slater> walk;
//wave.initWalker(walk);
runVMC(wave, walk);
}
else if (schd.wavefunctionType == "eom") {
EOM<Jastrow, Slater> wave; Walker<Jastrow, Slater> walk;
//cout << "detetrministic\n\n";
if (schd.deterministic) wave.optimizeWaveDeterministic(walk);
else {
wave.initWalker(walk);
wave.optimizeWaveCT(walk);
}
//wave.calcPolDeterministic(walk);
//wave.calcPolCT(walk);
//wave.initWalker(walk);
//runVMC(wave, walk);
}
else if (schd.wavefunctionType == "pol") {
EOM<Jastrow, Slater> wave; Walker<Jastrow, Slater> walk;
//cout << "detetrministic\n\n";
//wave.optimizeWaveDeterministic(walk);
//cout << "stochastic\n\n";
//wave.optimizeWaveCT(walk);
if (schd.deterministic) wave.calcPolDeterministic(walk);
else {
wave.initWalker(walk);
wave.calcPolCT(walk);
}
//wave.initWalker(walk);
//runVMC(wave, walk);
}
else if (schd.wavefunctionType == "scpt") {
initNEVPT_Wrapper();
}
else if (schd.wavefunctionType == "slaterrdm") {
CorrelatedWavefunction<Jastrow, Slater> wave; Walker<Jastrow, Slater> walk;
wave.readWave();
MatrixXd oneRdm0, oneRdm1, corr;
//getOneRdmDeterministic(wave, walk, oneRdm0, 0);
//getOneRdmDeterministic(wave, walk, oneRdm1, 1);
//getDensityCorrelationsDeterministic(wave, walk, corr);
getStochasticOneRdmContinuousTime(wave, walk, oneRdm0, 0, schd.stochasticIter);
getStochasticOneRdmContinuousTime(wave, walk, oneRdm1, 1, schd.stochasticIter);
getStochasticDensityCorrelationsContinuousTime(wave, walk, corr, schd.stochasticIter);
if (commrank == 0) {
cout << "oneRdm0\n" << oneRdm0 << endl << endl;
cout << "oneRdm1\n" << oneRdm1 << endl << endl;
cout << "Density correlations\n" << corr << endl << endl;
}
}
else if (schd.wavefunctionType == "agprdm") {
CorrelatedWavefunction<Jastrow, AGP> wave; Walker<Jastrow, AGP> walk;
wave.readWave();
MatrixXd oneRdm0, oneRdm1, corr;
//getOneRdmDeterministic(wave, walk, oneRdm0, 0);
//getOneRdmDeterministic(wave, walk, oneRdm1, 1);
//getDensityCorrelationsDeterministic(wave, walk, corr);
getStochasticOneRdmContinuousTime(wave, walk, oneRdm0, 0, schd.stochasticIter);
getStochasticOneRdmContinuousTime(wave, walk, oneRdm1, 1, schd.stochasticIter);
getStochasticDensityCorrelationsContinuousTime(wave, walk, corr, schd.stochasticIter);
if (commrank == 0) {
cout << "oneRdm0\n" << oneRdm0 << endl << endl;
cout << "oneRdm1\n" << oneRdm1 << endl << endl;
cout << "Density correlations\n" << corr << endl << endl;
}
}
else if (schd.wavefunctionType == "pfaffianrdm") {
CorrelatedWavefunction<Jastrow, Pfaffian> wave; Walker<Jastrow, Pfaffian> walk;
wave.readWave();
MatrixXd oneRdm0, oneRdm1, corr;
//getOneRdmDeterministic(wave, walk, oneRdm0, 0);
//getOneRdmDeterministic(wave, walk, oneRdm1, 1);
//getDensityCorrelationsDeterministic(wave, walk, corr);
getStochasticOneRdmContinuousTime(wave, walk, oneRdm0, 0, schd.stochasticIter);
getStochasticOneRdmContinuousTime(wave, walk, oneRdm1, 1, schd.stochasticIter);
getStochasticDensityCorrelationsContinuousTime(wave, walk, corr, schd.stochasticIter);
if (commrank == 0) {
cout << "oneRdm0\n" << oneRdm0 << endl << endl;
cout << "oneRdm1\n" << oneRdm1 << endl << endl;
cout << "Density correlations\n" << corr << endl << endl;
}
}
//else if (schd.wavefunctionType == "LanczosCPSSlater") {
// //CIWavefunction<CPSSlater, HFWalker, Operator> wave;
// CPSSlater wave; HFWalker walk;
// wave.readWave();
// wave.initWalker(walk);
// Eigen::VectorXd stddev = Eigen::VectorXd::Zero(4);
// Eigen::VectorXd rk = Eigen::VectorXd::Zero(4);
// //double rk = 0;
// Eigen::VectorXd lanczosCoeffs = Eigen::VectorXd::Zero(4);
// double alpha = 0.1;
// if (schd.deterministic) getLanczosCoeffsDeterministic(wave, walk, alpha, lanczosCoeffs);
// else getLanczosCoeffsContinuousTime(wave, walk, alpha, lanczosCoeffs, stddev, rk, schd.stochasticIter, 1.e-5);
// //getLanczosMatrixContinuousTime(wave, walk, lanczosMat, stddev, rk, schd.stochasticIter, 1.e-5);
// double a = lanczosCoeffs[2]/lanczosCoeffs[3];
// double b = lanczosCoeffs[1]/lanczosCoeffs[3];
// double c = lanczosCoeffs[0]/lanczosCoeffs[3];
// double delta = pow(a, 2) + 4 * pow(b, 3) - 6 * a * b * c - 3 * pow(b * c, 2) + 4 * a * pow(c, 3);
// double numP = a - b * c + pow(delta, 0.5);
// double numM = a - b * c - pow(delta, 0.5);
// double denom = 2 * pow(b, 2) - 2 * a * c;
// double alphaP = numP/denom;
// double alphaM = numM/denom;
// double eP = (a * pow(alphaP, 2) + 2 * b * alphaP + c) / (b * pow(alphaP, 2) + 2 * c * alphaP + 1);
// double eM = (a * pow(alphaM, 2) + 2 * b * alphaM + c) / (b * pow(alphaM, 2) + 2 * c * alphaM + 1);
// if (commrank == 0) {
// cout << "lanczosCoeffs\n";
// cout << lanczosCoeffs << endl;
// cout << "stddev\n";
// cout << stddev << endl;
// cout << "rk\n";
// cout << rk << endl;
// cout << "alpha(+/-) " << alphaP << " " << alphaM << endl;
// cout << "energy(+/-) " << eP << " " << eM << endl;
// //cout << "rk\n" << rk << endl << endl;
// //cout << "stddev\n" << stddev << endl << endl;
// }
// //vector<double> alpha{0., 0.1, 0.2, -0.1, -0.2};
// //vector<double> Ealpha{0., 0., 0., 0., 0.};
// //double stddev, rk;
// //for (int i = 0; i < alpha.size(); i++) {
// // vars[0] = alpha[i];
// // wave.updateVariables(vars);
// // wave.initWalker(walk);
// // getStochasticEnergyContinuousTime(wave, walk, Ealpha[i], stddev, rk, schd.stochasticIter, 1.e-5);
// // if (commrank == 0) cout << alpha[i] << " " << Ealpha[i] << " " << stddev << endl;
// //}
// //getGradientWrapper<CIWavefunction<CPSSlater, HFWalker, Operator>, HFWalker> wrapper(wave, walk, schd.stochasticIter);
// //getGradientWrapper<Lanczos<CPSSlater, HFWalker>, HFWalker> wrapper(wave, walk, schd.stochasticIter);
// // functor1 getStochasticGradient = boost::bind(&getGradientWrapper<Lanczos<CPSSlater, HFWalker>, HFWalker>::getGradient, &wrapper, _1, _2, _3, _4, _5, schd.deterministic);
// //if (schd.method == amsgrad) {
// // AMSGrad optimizer(schd.stepsize, schd.decay1, schd.decay2, schd.maxIter);
// // //functor1 getStochasticGradient = boost::bind(&getGradientWrapper<CIWavefunction<CPSSlater, HFWalker, Operator>, HFWalker>::getGradient, &wrapper, _1, _2, _3, _4, _5, schd.deterministic);
// // optimizer.optimize(vars, getStochasticGradient, schd.restart);
// // //if (commrank == 0) wave.printVariables();
// //}
// //else if (schd.method == sgd) {
// // SGD optimizer(schd.stepsize, schd.maxIter);
// // optimizer.optimize(vars, getStochasticGradient, schd.restart);
// //}
//}
boost::interprocess::shared_memory_object::remove(shciint2.c_str());
boost::interprocess::shared_memory_object::remove(shciint2shm.c_str());
boost::interprocess::shared_memory_object::remove(shciint2shmcas.c_str());
return 0;
}
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "SimpleWalker.h"
void SimpleWalker::updateA(int i, int a)
{
d.setoccA(i, false);
d.setoccA(a, true);
}
void SimpleWalker::updateA(int i, int j, int a, int b)
{
d.setoccA(i, false);
d.setoccA(a, true);
d.setoccA(j, false);
d.setoccA(b, true);
}
void SimpleWalker::updateB(int i, int a)
{
d.setoccB(i, false);
d.setoccB(a, true);
}
void SimpleWalker::updateB(int i, int j, int a, int b)
{
d.setoccB(i, false);
d.setoccB(a, true);
d.setoccB(j, false);
d.setoccB(b, true);
}
void SimpleWalker::updateEnergyIntermediate(const oneInt& I1, const twoInt& I2, int I, int A)
{
int norbs = Determinant::norbs;
for (int i = 0; i < norbs; i++) {
energyIntermediates[0][i] += (I2.Direct(i, A/2) - I2.Direct(i, I/2));
energyIntermediates[1][i] += (I2.Direct(i, A/2) - I2.Direct(i, I/2));
energyIntermediates[I%2][i] -= (I2.Exchange(i, A/2) - I2.Exchange(i, I/2));
}
}
void SimpleWalker::updateEnergyIntermediate(const oneInt& I1, const twoInt& I2, int I, int A, int J, int B)
{
int norbs = Determinant::norbs;
for (int i = 0; i < norbs; i++) {
energyIntermediates[0][i] += (I2.Direct(i, A/2) - I2.Direct(i, I/2) + I2.Direct(i, B/2) - I2.Direct(i, J/2));
energyIntermediates[1][i] += (I2.Direct(i, A/2) - I2.Direct(i, I/2) + I2.Direct(i, B/2) - I2.Direct(i, J/2));
energyIntermediates[I%2][i] -= (I2.Exchange(i, A/2) - I2.Exchange(i, I/2));
energyIntermediates[J%2][i] -= (I2.Exchange(i, B/2) - I2.Exchange(i, J/2));
}
}
//assumes valid excitations
//the energyIntermediates should only be updated for outer walker updates
void SimpleWalker::updateWalker(const Determinant &ref, const Determinant &corr, int ex1, int ex2, bool updateIntermediate)
{
int norbs = Determinant::norbs;
int I = ex1 / (2 * norbs), A = ex1 % (2 * norbs);
if (I < 2*schd.nciCore) excitedHoles.insert(I);
if (A < 2*schd.nciCore) excitedHoles.erase(A);
if (I >= 2*(schd.nciCore+schd.nciAct)) excitedOrbs.erase(I);
if (A >= 2*(schd.nciCore+schd.nciAct)) excitedOrbs.insert(A);
if (I % 2 == 0) {
updateA(I / 2, A / 2);
}
else {
updateB(I / 2, A / 2);
}
//if (ex2 == 0 && updateIntermediate) {
// updateEnergyIntermediate(I1, I2, I, A);
//}
if (ex2 != 0)
{
int J = ex2 / (2 * norbs), B = ex2 % (2 * norbs);
if (J < 2*schd.nciCore) excitedHoles.insert(J);
if (B < 2*schd.nciCore) excitedHoles.erase(B);
if (J >= 2*(schd.nciCore+schd.nciAct)) excitedOrbs.erase(J);
if (B >= 2*(schd.nciCore+schd.nciAct)) excitedOrbs.insert(B);
if (J % 2 == 0)
updateA(J / 2, B / 2);
else
updateB(J / 2, B / 2);
//if (updateIntermediate) {
// updateEnergyIntermediate(I1, I2, I, A, J, B);
//}
}
getExcitationClass();
}
//not implemented for SimpleWalker
void SimpleWalker::exciteWalker(const Determinant &ref, const Determinant &corr, int excite1, int excite2, int norbs)
{
int I1 = excite1 / (2 * norbs), A1 = excite1 % (2 * norbs);
if (I1 % 2 == 0) {
updateA(I1 / 2, A1 / 2);
}
else {
updateB(I1 / 2, A1 / 2);
}
if (excite2 != 0)
{
int I2 = excite2 / (2 * norbs), A2 = excite2 % (2 * norbs);
if (I2 % 2 == 0)
updateA(I2 / 2, A2 / 2);
else
updateB(I2 / 2, A2 / 2);
}
}
void SimpleWalker::getExcitationClass()
{
// Find the excitation class
if (excitedHoles.size() == 0) {
// 0 core orbitals
if (excitedOrbs.size() == 0) {
excitation_class = 0;
} else if (excitedOrbs.size() == 1) {
excitation_class = 1;
} else if (excitedOrbs.size() == 2) {
excitation_class = 2;
} else {
excitation_class = -1;
}
} else if (excitedHoles.size() == 1) {
// 1 core orbitals
if (excitedOrbs.size() == 0) {
excitation_class = 3;
} else if (excitedOrbs.size() == 1) {
excitation_class = 4;
} else if (excitedOrbs.size() == 2) {
excitation_class = 5;
} else {
excitation_class = -1;
}
} else if (excitedHoles.size() == 2) {
// 2 core orbitals
if (excitedOrbs.size() == 0) {
excitation_class = 6;
} else if (excitedOrbs.size() == 1) {
excitation_class = 7;
} else if (excitedOrbs.size() == 2) {
excitation_class = 8;
} else {
excitation_class = -1;
}
// More than 2 core orbitals
} else {
excitation_class = -1;
}
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CIWavefunction_HEADER_H
#define CIWavefunction_HEADER_H
#include <vector>
#include <set>
#include "Determinants.h"
#include "workingArray.h"
#include "excitationOperators.h"
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/array.hpp>
#include <utility>
using namespace std;
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
/**
* This is the wavefunction, that extends a given wavefunction by doing
* a CI expansion on it
* |Psi> = \sum_i d_i O_i ||phi>
* where d_i are the coefficients and O_i are the list of operators
* these operators O_i can be of type Operators or SpinFreeOperators
*/
template <typename Wfn, typename Walker, typename OpType>
class CIWavefunction
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & wave
& oplist
& ciCoeffs;
//& excitedOvlps;
}
public:
Wfn wave;
std::vector<OpType> oplist;
std::vector<double> ciCoeffs;
//Eigen::VectorXd excitedOvlps; //stores overlaps: <n|oplist[i]|phi0> for the current walker |n>, filled during Overlap call
CIWavefunction() {
wave.readWave();
oplist.resize(1);
ciCoeffs.resize(1, 1.0);
}
CIWavefunction(Wfn &w1, std::vector<OpType> &pop) : wave(w1), oplist(pop)
{
ciCoeffs.resize(oplist.size(), 0.0);
ciCoeffs[0] = 1.0;
}
typename Wfn::ReferenceType& getRef() { return wave.getRef(); }
typename Wfn::CorrType& getCorr() { return wave.getCorr(); }
void appendSinglesToOpList(double screen = 1.0)
{
OpType::populateSinglesToOpList(oplist, ciCoeffs, screen);
ciCoeffs.resize(oplist.size(), 0.0);
//excitedOvlps.resize(oplist.size(), 0.0);
}
void appendScreenedDoublesToOpList(double screen)
{
OpType::populateScreenedDoublesToOpList(oplist, ciCoeffs, screen);
//OpType::populateDoublesToOpList(oplist, ciCoeffs);
ciCoeffs.clear(); ciCoeffs.resize(oplist.size(), 0.0); ciCoeffs[0] = 1.;
//excitedOvlps = Eigen::VectorXd::Zero(oplist.size());
if (schd.ciCeption) {
uniform_real_distribution<double> dist(0.005,0.006);
for (int i = 1; i<ciCoeffs.size(); i++) ciCoeffs[i] = dist(generator);
}
}
void getVariables(VectorXd& vars) {
if (vars.rows() != getNumVariables())
vars = VectorXd::Zero(getNumVariables());
for (int i=0; i<ciCoeffs.size(); i++)
vars[i] = ciCoeffs[i];
}
void printVariables() {
for (int i=0;i<oplist.size(); i++)
cout << oplist[i]<<" "<<ciCoeffs[i]<<endl;
}
void updateVariables(VectorXd& vars) {
for (int i=0; i<vars.rows(); i++)
ciCoeffs[i] = vars[i];
}
long getNumVariables() {
return ciCoeffs.size();
}
double calculateOverlapRatioWithUnderlyingWave(Walker &walk, Determinant &dcopy)
{
double ovlpdetcopy;
int excitationDistance = dcopy.ExcitationDistance(walk.d);
if (excitationDistance == 0)
{
ovlpdetcopy = 1.0;
}
else if (excitationDistance == 1)
{
int I, A;
getDifferenceInOccupation(walk.d, dcopy, I, A);
ovlpdetcopy = wave.getOverlapFactor(I, A, walk, false);
}
else if (excitationDistance == 2)
{
int I, J, A, B;
getDifferenceInOccupation(walk.d, dcopy, I, J, A, B);
bool doparity = false;
//cout << I<<" "<<J<<" "<<A<<" "<<B<<endl;
ovlpdetcopy = wave.getOverlapFactor(I, J, A, B, walk, doparity);
}
else
{
cout << "higher than triple excitation not yet supported." << endl;
exit(0);
}
return ovlpdetcopy;
}
double getOverlapFactor(int I, int J, int A, int B, Walker& walk, bool doparity=false) {
int norbs = Determinant::norbs;
if (J == 0 && B == 0) {
Walker walkcopy = walk;
walkcopy.exciteWalker(wave.getRef(), wave.getCorr(), I*2*norbs+A, 0, norbs);
return Overlap(walkcopy)/Overlap(walk);
}
else {
Walker walkcopy = walk;
walkcopy.exciteWalker(wave.getRef(), wave.getCorr(), I*2*norbs+A, J*2*norbs+B, norbs);
return Overlap(walkcopy)/Overlap(walk);
}
}
double Overlap(Walker& walk) {
double totalovlp = 0.0;
double ovlp0 = wave.Overlap(walk);
//excitedOvlps.setZero();
//excitedOvlps[0] = ovlp0;
totalovlp += ciCoeffs[0] * ovlp0;
Determinant dcopy = walk.d;
int opSize = oplist.size();
//int nops = 1;//change if using spin-free operators
for (int i = 1; i < opSize; i++) {
for (int j = 0; j < oplist[i].nops; j++) {
//for (int j=0; j<nops; j++) {
dcopy = walk.d;
bool valid = 0;
double ovlpdetcopy = 0.;
if (schd.ciCeption) { //uncomment to work with non-sci waves
//for (int k = 0; k < op.n; k++) if (op.cre[k] >= 2*schd.nciAct) valid = 1;
//if (valid) continue;
valid = oplist[i].apply(dcopy, walk.excitedOrbs);
if (valid) {
Walker walkcopy(wave.getCorr(), wave.getRef(), dcopy);
ovlpdetcopy = wave.Overlap(walkcopy);
//excitedOvlps[i] = ovlpdetcopy;
totalovlp += ciCoeffs[i] * ovlpdetcopy;
}
}
else {
valid = oplist[i].apply(dcopy, j);
if (valid) {
ovlpdetcopy = calculateOverlapRatioWithUnderlyingWave(walk, dcopy);
totalovlp += ciCoeffs[i] * ovlpdetcopy * ovlp0;
}
}
}
}
return totalovlp;
}
double OverlapWithGradient(Walker &walk,
double &factor,
Eigen::VectorXd &grad)
{
VectorXd gradcopy = grad;
gradcopy.setZero();
double ovlp0 = Overlap(walk);
//double ovlp0 = excitedOvlps[0];
if (ovlp0 == 0.) return 0.;
for (int i = 0; i < oplist.size(); i++) {
for (int j=0; j<oplist[i].nops; j++) {
Determinant dcopy = walk.d;
bool valid = 0;
double ovlpdetcopy = 0.;
if (schd.ciCeption) {
valid = oplist[i].apply(dcopy, walk.excitedOrbs);
if (valid) {
Walker walkcopy(wave.getCorr(), wave.getRef(), dcopy);
ovlpdetcopy = wave.Overlap(walkcopy) / ovlp0;
}
//ovlpdetcopy = excitedOvlps[i] / ovlp0;
}
else {
valid = oplist[i].apply(dcopy, j);
if (valid) {
ovlpdetcopy = calculateOverlapRatioWithUnderlyingWave(walk, dcopy);
}
}
gradcopy[i] += ovlpdetcopy;
}
}
double totalOvlp = 0.0;
if (schd.ciCeption) totalOvlp = 1.;
else {
for (int i=0; i<grad.rows(); i++) {
totalOvlp += ciCoeffs[i] * gradcopy[i];
}
}
for (int i=0; i<grad.rows(); i++) {
grad[i] += gradcopy[i]/totalOvlp;
}
return totalOvlp;
}
void HamAndOvlp(Walker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true)
{
work.setCounterToZero();
int norbs = Determinant::norbs;
ovlp = Overlap(walk);
if (ovlp == 0.) return;
ham = walk.d.Energy(I1, I2, coreE);
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, !schd.ciCeption);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, !schd.ciCeption);
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
Walker walkcopy = walk;
if (ex2 == 0) walkcopy.updateWalker(wave.getRef(), wave.getCorr(), ex1, ex2, true);
else walkcopy.updateWalker(wave.getRef(), wave.getCorr(), ex1, ex2, false);
if (schd.ciCeption && (walkcopy.excitedOrbs.size() > 2)) continue;
double parity = 1.0;
if (schd.ciCeption) {
Determinant dcopy = walk.d;
if (A > I) parity *= -1. * dcopy.parity(A/2, I/2, I%2);
else parity *= dcopy.parity(A/2, I/2, I%2);
dcopy.setocc(I, false); dcopy.setocc(A, true);
if (ex2 != 0) {
if (B > J) parity *= -1 * dcopy.parity(B/2, J/2, J%2);
else parity *= dcopy.parity(B/2, J/2, J%2);
}
}
double ovlpdetcopy = Overlap(walkcopy);
if (schd.debug) {
cout << "walkCopy " << walkcopy << endl;
cout << "det energy " << ham << endl;
cout << ex1 << " " << ex2 << " tia " << tia << " ovlpRatio " << parity * ovlpdetcopy / ovlp << endl;
}
ham += tia * parity * ovlpdetcopy / ovlp;
work.ovlpRatio[i] = ovlpdetcopy/ovlp;
}
}
void initWalker(Walker& walk)
{
wave.initWalker(walk);
}
void initWalker(Walker& walk, Determinant& d)
{
wave.initWalker(walk, d);
}
string getfileName() const {
return "ci"+wave.getfileName();
}
void writeWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
#endif
}
// not used
//template<typename Walker>
//bool checkWalkerExcitationClass(Walker &walk) {
// return true;
//}
};
/*
template <typename Wfn, typename Walker>
class Lanczos : public CIWavefunction<Wfn, Walker, Operator>
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::base_object<CIWavefunction<Wfn, Walker, Operator>>(*this)
& alpha;
}
public:
double alpha;
Lanczos()
{
CIWavefunction<Wfn, Walker, Operator>();
alpha = 0.;
}
Lanczos(Wfn &w1, std::vector<Operator> &pop, double alpha0) : alpha(alpha0)
{
CIWavefunction<Wfn, Walker, Operator>(w1, pop);
}
typename Wfn::ReferenceType& getRef() { return wave.getRef(); }
typename Wfn::CorrType& getCPS() { return wave.getCPS(); }
void appendSinglesToOpList(double screen = 0.0)
{
Operator::populateSinglesToOpList(this->oplist, this->ciCoeffs);
//ciCoeffs.resize(oplist.size(), 0.0);
}
void appendScreenedDoublesToOpList(double screen)
{
Operator::populateScreenedDoublesToOpList(this->oplist, this->ciCoeffs, screen);
//ciCoeffs.resize(oplist.size(), 0.0);
}
void initWalker(Walker& walk) {
this->wave.initWalker(walk);
}
void initWalker(Walker& walk, Determinant& d) {
this->wave.initWalker(walk, d);
}
void getVariables(VectorXd& vars) {
if (vars.rows() != getNumVariables())
{
vars = VectorXd::Zero(getNumVariables());
}
vars[0] = alpha;
}
void printVariables() {
cout << "alpha " << alpha << endl;
//for (int i=0; i<this->oplist.size(); i++)
// cout << this->oplist[i] << " " << this->ciCoeffs[i] << endl;
}
void updateVariables(VectorXd& vars) {
alpha = vars[0];
}
long getNumVariables() {
return 1;
}
double Overlap(Walker& walk) {
double totalovlp = 0.0;
double ovlp0 = this->wave.Overlap(walk);
totalovlp += ovlp0;
for (int i=1; i<this->oplist.size(); i++)
{
for (int j=0; j<this->oplist[i].nops; j++) {
Determinant dcopy = walk.d;
bool valid =this-> oplist[i].apply(dcopy, j);
if (valid) {
double ovlpdetcopy = calculateOverlapRatioWithUnderlyingWave(walk, dcopy);
totalovlp += alpha * this->ciCoeffs[i] * ovlpdetcopy * ovlp0;
}
}
}
return totalovlp;
}
double OverlapWithGradient(Walker &walk,
double &factor,
Eigen::VectorXd &grad)
{
double num = 0.;
for (int i=1; i<this->oplist.size(); i++)
{
for (int j=0; j<this->oplist[i].nops; j++) {
Determinant dcopy = walk.d;
bool valid = this->oplist[i].apply(dcopy, j);
if (valid) {
double ovlpdetcopy = calculateOverlapRatioWithUnderlyingWave(walk, dcopy);
num += this->ciCoeffs[i] * ovlpdetcopy;
}
}
}
grad[0] += num/(alpha * num + 1);
return (alpha * num + 1);
}
void HamAndOvlp(Walker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations = true)
{
work.setCounterToZero();
double TINY = schd.screen;
double THRESH = schd.epsilon;
Determinant &d = walk.d;
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
//noexcitation
{
double E0 = d.Energy(I1, I2, coreE);
ovlp = Overlap(walk);
ham = E0;
}
//Single alpha-beta excitation
{
double time = getTime();
for (int i = 0; i < closed.size(); i++)
{
for (int a = 0; a < open.size(); a++)
{
if (closed[i] % 2 == open[a] % 2 && abs(I2hb.Singles(closed[i], open[a])) > THRESH)
{
prof.SinglesCount++;
int I = closed[i] / 2, A = open[a] / 2;
double tia = 0;
Determinant dcopy = d;
bool Alpha = closed[i] % 2 == 0 ? true : false;
bool doparity = true;
if (schd.Hamiltonian == HUBBARD)
{
tia = I1(2 * A, 2 * I);
double sgn = 1.0;
if (Alpha)
sgn *= d.parityA(A, I);
else
sgn *= d.parityB(A, I);
tia *= sgn;
}
else
{
tia = I1(2 * A, 2 * I);
int X = max(I, A), Y = min(I, A);
int pairIndex = X * (X + 1) / 2 + Y;
size_t start = I2hb.startingIndicesSingleIntegrals[pairIndex];
size_t end = I2hb.startingIndicesSingleIntegrals[pairIndex + 1];
float *integrals = I2hb.singleIntegrals;
short *orbIndices = I2hb.singleIntegralsPairs;
for (size_t index = start; index < end; index++)
{
if (fabs(integrals[index]) < TINY)
break;
int j = orbIndices[2 * index];
if (closed[i] % 2 == 1 && j % 2 == 1)
j--;
else if (closed[i] % 2 == 1 && j % 2 == 0)
j++;
if (d.getocc(j))
{
tia += integrals[index];
}
//cout << tia<<" "<<a<<" "<<integrals[index]<<endl;
}
double sgn = 1.0;
if (Alpha)
sgn *= d.parityA(A, I);
else
sgn *= d.parityB(A, I);
tia *= sgn;
}
double localham = 0.0;
if (abs(tia) > THRESH)
{
Walker walkcopy = walk;
walkcopy.exciteWalker(this->wave.getRef(), this->wave.getCPS(), closed[i]*2*norbs+open[a], 0, norbs);
double ovlpdetcopy = Overlap(walkcopy);
ham += ovlpdetcopy * tia / ovlp;
if (fillExcitations)
work.appendValue(ovlpdetcopy/ovlp, closed[i] * 2 * norbs + open[a], 0, tia);
}
}
}
}
prof.SinglesTime += getTime() - time;
}
if (schd.Hamiltonian == HUBBARD)
return;
//Double excitation
{
double time = getTime();
int nclosed = closed.size();
for (int ij = 0; ij < nclosed * nclosed; ij++)
{
int i = ij / nclosed, j = ij % nclosed;
if (i <= j)
continue;
int I = closed[i] / 2, J = closed[j] / 2;
int X = max(I, J), Y = min(I, J);
int pairIndex = X * (X + 1) / 2 + Y;
size_t start = closed[i] % 2 == closed[j] % 2 ? I2hb.startingIndicesSameSpin[pairIndex] : I2hb.startingIndicesOppositeSpin[pairIndex];
size_t end = closed[i] % 2 == closed[j] % 2 ? I2hb.startingIndicesSameSpin[pairIndex + 1] : I2hb.startingIndicesOppositeSpin[pairIndex + 1];
float *integrals = closed[i] % 2 == closed[j] % 2 ? I2hb.sameSpinIntegrals : I2hb.oppositeSpinIntegrals;
short *orbIndices = closed[i] % 2 == closed[j] % 2 ? I2hb.sameSpinPairs : I2hb.oppositeSpinPairs;
// for all HCI integrals
for (size_t index = start; index < end; index++)
{
// if we are going below the criterion, break
if (fabs(integrals[index]) < THRESH)
break;
// otherwise: generate the determinant corresponding to the current excitation
int a = 2 * orbIndices[2 * index] + closed[i] % 2, b = 2 * orbIndices[2 * index + 1] + closed[j] % 2;
if (!(d.getocc(a) || d.getocc(b)))
{
int A = a / 2, B = b / 2;
double tiajb = integrals[index];
Walker walkcopy = walk;
walkcopy.exciteWalker(this->wave.getRef(), this->wave.getCPS(), closed[i] * 2 * norbs + a, closed[j] * 2 * norbs + b, norbs);
double ovlpdetcopy = Overlap(walkcopy);
double parity = 1.0;
if (closed[i] % 2 == closed[j] % 2 && closed[i] % 2 == 0)
parity = walk.d.parityAA(I, J, A, B);
else if (closed[i] % 2 == closed[j] % 2 && closed[i] % 2 == 1)
parity = walk.d.parityBB(I, J, A, B);
else if (closed[i] % 2 != closed[j] % 2 && closed[i] % 2 == 0)
parity = walk.d.parityA(A, I) * walk.d.parityB(B, J);
else
parity = walk.d.parityB(A, I) * walk.d.parityA(B, J);
ham += ovlpdetcopy * tiajb * parity / ovlp;
if (fillExcitations)
work.appendValue(ovlpdetcopy/ovlp, closed[i] * 2 * norbs + a,
closed[j] * 2 * norbs + b , tiajb);
}
}
}
prof.DoubleTime += getTime() - time;
}
}
void writeWave()
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, "lanczoswave.bkp");
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, "lanczoswave.bkp");
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
#endif
}
};
*/
#endif
<file_sep>#include "CalculateSphHarmonics.h"
#include <Eigen/Dense>
#include <boost/math/special_functions/spherical_harmonic.hpp>
using namespace std;
using namespace Eigen;
double factorialRatio(int l, int m) {
double ratio = 1.0;
for (int k = -m + 1 ; k < m+1 ; k++)
ratio *= 1./(1.*l + 1.*k);
return ratio;
}
//calculate all the spherical harmonics at theta phi
void CalculateSphHarmonics::populate(double theta, double phi) {
double x = cos(theta);
//fill out all the legendre polynomial values for positive m
for (int m = 0; m < lmax; m++) {
double vallm1 = boost::math::legendre_p(m , m, x);
double vall = boost::math::legendre_p(m+1, m, x);
getval(m , m) = vallm1;
getval(m+1, m) = vall;
for (int l = m+1 ; l<lmax; l++) {
double temp = boost::math::legendre_next(l, m, x, vall, vallm1);
vallm1 = vall;
vall = temp;
getval(l+1, m) = vall;
}
}
getval(lmax, lmax) = boost::math::legendre_p(lmax, lmax, x);
//use the legendre polynomial values to get the spherical harmonics
double sqrt2 = sqrt(2.0);
for (int m=0; m<lmax+1; m++) {
double sinphi = pow(-1., m) * sin(m*phi), cosphi = pow(-1., m) * cos(m*phi);
for (int l=m; l<lmax+1; l++) {
double leg = sqrt2 * sqrt( (2*l+1) * factorialRatio(l, m) / 4./M_PI) * getval(l, m);
getval(l, m) = leg * cosphi;
if (m != 0)
getval(l,-m) = leg * sinphi;
else
getval(l, m) /= sqrt2;
}
}
}
/*
int main(int argc, char* argv[]) {
double val[100];
double theta = M_PI/2.3, phi = 1.3*M_PI;
int l = 4;
cin >> l ;
CalculateSphHarmonics sph(l);
for (int i=0; i<50000; i++)
sph.populate(theta, phi);
cout << sph.values[0]<<" - "<<sph.getval(l,0)<<endl;
cout <<0<<" "<< sph.getval(l, 0)<<" "<< boost::math::spherical_harmonic(l, 0, theta, phi)<<endl;
for (int m=1; m<l+1; m++) {
double val1 = sph.getval(l,m),
val2 = sqrt(2.0)* boost::math::spherical_harmonic(l, m, theta, phi).real() * pow(-1,m);
double val3 = sph.getval(l, -m),
val4 = sqrt(2.0)* boost::math::spherical_harmonic(l, m, theta, phi).imag() * pow(-1,m);
if (abs(val1-val2) > 1.e-14)
cout <<m<<" "<< val1<<" "<<val2<<endl;
if (abs(val3-val4) > 1.e-14)
cout <<-m<<" "<< val3<<" "<<val4<<endl;
}
}
*/
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef EvalE_HEADER_H
#define EvalE_HEADER_H
#include <Eigen/Dense>
#include <vector>
#include "Determinants.h"
#include "workingArray.h"
#include "statistics.h"
#include "sr.h"
#include "global.h"
#include "Deterministic.h"
#include "ContinuousTime.h"
#include "Metropolis.h"
#include <iostream>
#include <fstream>
#include <boost/serialization/serialization.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <algorithm>
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace Eigen;
using namespace std;
using namespace boost;
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
//############################################################Deterministic Evaluation############################################################################
template<typename Wfn, typename Walker>
void getEnergyDeterministic(Wfn &w, Walker& walk, double &Energy)
{
Deterministic<Wfn, Walker> D(w, walk);
Energy = 0.0;
for (int i = commrank; i < D.allDets.size(); i += commsize)
{
D.LocalEnergy(D.allDets[i]);
D.UpdateEnergy(Energy);
}
D.FinishEnergy(Energy);
}
template<typename Wfn, typename Walker> void getOneRdmDeterministic(Wfn &w, Walker& walk, MatrixXd &oneRdm, bool sz)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
double Overlap = 0;
oneRdm = MatrixXd::Constant(norbs, norbs, 0.);
MatrixXd localOneRdm = MatrixXd::Constant(norbs, norbs, 0.);
for (int i = commrank; i < allDets.size(); i += commsize) {
w.initWalker(walk, allDets[i]);
localOneRdm.setZero(norbs, norbs);
vector<int> open;
vector<int> closed;
allDets[i].getOpenClosed(sz, open, closed);
for (int p = 0; p < closed.size(); p++) {
localOneRdm(closed[p], closed[p]) = 1.;
for (int q = 0; q < open.size() && open[q] < closed[p]; q++) {
localOneRdm(closed[p], open[q]) = w.getOverlapFactor(2*closed[p] + sz, 2*open[q] + sz, walk, 0);
}
}
double ovlp = w.Overlap(walk);
Overlap += ovlp * ovlp;
oneRdm += ovlp * ovlp * localOneRdm;
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(Overlap), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, oneRdm.data(), norbs*norbs, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
oneRdm = oneRdm / Overlap;
}
template<typename Wfn, typename Walker> void getDensityCorrelationsDeterministic(Wfn &w, Walker& walk, MatrixXd &corr)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
double Overlap = 0;
corr = MatrixXd::Constant(2*norbs, 2*norbs, 0.);
MatrixXd localCorr = MatrixXd::Constant(2*norbs, 2*norbs, 0.);
for (int i = commrank; i < allDets.size(); i += commsize) {
w.initWalker(walk, allDets[i]);
localCorr.setZero(2*norbs, 2*norbs);
vector<int> open;
vector<int> closed;
allDets[i].getOpenClosed(open, closed);
for (int p = 0; p < closed.size(); p++) {
localCorr(closed[p], closed[p]) = 1.;
for (int q = 0; q < p; q++) {
int P = max(closed[p], closed[q]), Q = min(closed[p], closed[q]);
localCorr(P, Q) = 1.;
}
}
double ovlp = w.Overlap(walk);
Overlap += ovlp * ovlp;
corr += ovlp * ovlp * localCorr;
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(Overlap), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, corr.data(), 4*norbs*norbs, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
corr = corr / Overlap;
}
template<typename Wfn, typename Walker>
void getGradientDeterministic(Wfn &w, Walker &walk, double &Energy, VectorXd &grad)
{
Deterministic<Wfn, Walker> D(w, walk);
Energy = 0.0;
grad.setZero();
VectorXd grad_ratio_bar = VectorXd::Zero(grad.rows());
for (int i = commrank; i < D.allDets.size(); i += commsize)
{
//if (schd.debug) cout << "det " << D.allDets[i] << endl;
D.LocalEnergy(D.allDets[i]);
D.LocalGradient();
D.UpdateEnergy(Energy);
D.UpdateGradient(grad, grad_ratio_bar);
}
D.FinishEnergy(Energy);
D.FinishGradient(grad, grad_ratio_bar, Energy);
}
template<typename Wfn, typename Walker>
void getGradientMetricDeterministic(Wfn &w, Walker &walk, double &Energy, VectorXd &grad, VectorXd &H, DirectMetric &S)
{
Deterministic<Wfn, Walker> D(w, walk);
Energy = 0.0;
grad.setZero();
VectorXd grad_ratio_bar = VectorXd::Zero(grad.rows());
for (int i = commrank; i < D.allDets.size(); i += commsize)
{
D.LocalEnergy(D.allDets[i]);
D.LocalGradient();
D.UpdateEnergy(Energy);
D.UpdateGradient(grad, grad_ratio_bar);
D.UpdateSR(S);
}
D.FinishEnergy(Energy);
D.FinishGradient(grad, grad_ratio_bar, Energy);
D.FinishSR(grad, grad_ratio_bar, H);
}
template<typename Wfn, typename Walker>
void getGradientHessianDeterministic(Wfn &w, Walker& walk, double &E0, int &nalpha, int &nbeta, int &norbs, oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb, double &coreE, VectorXd &grad, MatrixXd& Hessian, MatrixXd &Smatrix)
{
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
vector<double> ovlpRatio;
vector<size_t> excitation1, excitation2;
vector<double> HijElements;
int nExcitations;
double Overlap = 0, Energy = 0;
grad.setZero();
VectorXd diagonalGrad = VectorXd::Zero(grad.rows());
VectorXd localdiagonalGrad = VectorXd::Zero(grad.rows());
VectorXd localgrad = VectorXd::Zero(grad.rows());
double temp = 0.;
for (int i = commrank; i < allDets.size(); i += commsize)
{
w.initWalker(walk, allDets[i]);
double ovlp = 0, ham = 0;
{
E0 = 0.;
double scale = 1.0;
localgrad.setZero();
localdiagonalGrad.setZero();
w.HamAndOvlpGradient(walk, ovlp, ham, localgrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, true, false);
double tmpovlp = 1.0;
w.OverlapWithGradient(walk, ovlp, localdiagonalGrad);
}
//grad += localgrad * ovlp * ovlp;
grad += localdiagonalGrad * ham * ovlp * ovlp;
diagonalGrad += localdiagonalGrad * ovlp * ovlp;
Overlap += ovlp * ovlp;
Energy += ham * ovlp * ovlp;
Hessian.block(1, 1, grad.rows(), grad.rows()) += localgrad * localdiagonalGrad.transpose() * ovlp * ovlp;
Smatrix.block(1, 1, grad.rows(), grad.rows()) += localdiagonalGrad * localdiagonalGrad.transpose() * ovlp * ovlp;
Hessian.block(0, 1, 1, grad.rows()) += ovlp * ovlp * localgrad.transpose();
Hessian.block(1, 0, grad.rows(), 1) += ovlp * ovlp * localgrad;
Smatrix.block(0, 1, 1, grad.rows()) += ovlp * ovlp * localdiagonalGrad.transpose();
Smatrix.block(1, 0, grad.rows(), 1) += ovlp * ovlp * localdiagonalGrad;
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(grad[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(diagonalGrad[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Overlap), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Energy), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Hessian(0,0)), Hessian.rows()*Hessian.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Smatrix(0,0)), Hessian.rows()*Hessian.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
E0 = Energy / Overlap;
grad = (grad - E0 * diagonalGrad) / Overlap;
Hessian = Hessian/Overlap;
Smatrix = Smatrix/Overlap;
Smatrix(0,0) = 1.0;
Hessian(0,0) = E0;
}
template<typename Wfn, typename Walker>
void getLanczosCoeffsDeterministic(Wfn &w, Walker &walk, double &alpha, Eigen::VectorXd &lanczosCoeffs)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
workingArray work, moreWork;
double overlapTot = 0.;
Eigen::VectorXd coeffs = Eigen::VectorXd::Zero(4);
//w.printVariables();
for (int i = commrank; i < allDets.size(); i += commsize)
{
w.initWalker(walk, allDets[i]);
Eigen::VectorXd coeffsSample = Eigen::VectorXd::Zero(4);
double overlapSample = 0.;
w.HamAndOvlpLanczos(walk, coeffsSample, overlapSample, work, moreWork, alpha);
if (schd.debug) {
cout << "walker\n" << walk << endl;
cout << "coeffsSample\n" << coeffsSample << endl;
}
//cout << "ham " << ham[0] << " " << ham[1] << " " << ham[2] << endl;
//cout << "ovlp " << ovlp[0] << " " << ovlp[1] << " " << ovlp[2] << endl << endl;
//grad += localgrad * ovlp * ovlp;
overlapTot += overlapSample * overlapSample;
coeffs += (overlapSample * overlapSample) * coeffsSample;
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, coeffs.data(), 4, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
lanczosCoeffs = coeffs / overlapTot;
}
//############################################################Continuous Time Evaluation############################################################################
template<typename Wfn, typename Walker>
void getStochasticEnergyContinuousTime(Wfn &w, Walker &walk, double &Energy, double &stddev, double &rk, int niter)
{
ContinuousTime<Wfn, Walker> CTMC(w, walk, niter);
Energy = 0.0, stddev = 0.0, rk = 0.0;
CTMC.LocalEnergy();
for (int iter = 0; iter < niter; iter++)
{
CTMC.MakeMove();
CTMC.UpdateEnergy(Energy);
//CTMC.LocalEnergy();
CTMC.LocalEnergy();
//CTMC.UpdateBestDet();
//CTMC.UpdateEnergy(Energy);
}
CTMC.FinishEnergy(Energy, stddev, rk);
//CTMC.FinishBestDet();
}
template<typename Wfn, typename Walker>
void getStochasticGradientContinuousTime(Wfn &w, Walker &walk, double &Energy, double &stddev, VectorXd &grad, double &rk, int niter)
{
ContinuousTime<Wfn, Walker> CTMC(w, walk, niter);
Energy = 0.0, stddev = 0.0, rk = 0.0;
grad.setZero();
VectorXd grad_ratio_bar = VectorXd::Zero(grad.rows());
CTMC.LocalEnergy();
CTMC.LocalGradient();
for (int iter = 0; iter < schd.burnIter; iter++)
{
CTMC.MakeMove();
CTMC.LocalEnergy();
CTMC.LocalGradient();
CTMC.UpdateBestDet();
}
for (int iter = 0; iter < niter; iter++)
{
CTMC.MakeMove();
CTMC.UpdateEnergy(Energy);
CTMC.UpdateGradient(grad, grad_ratio_bar);
//CTMC.LocalEnergy();
//CTMC.LocalGradient();
CTMC.LocalEnergy();
CTMC.LocalGradient();
CTMC.UpdateBestDet();
//CTMC.UpdateEnergy(Energy);
//CTMC.UpdateGradient(grad, grad_ratio_bar);
}
CTMC.FinishEnergy(Energy, stddev, rk);
CTMC.FinishGradient(grad, grad_ratio_bar, Energy);
CTMC.FinishBestDet();
}
template<typename Wfn, typename Walker>
void getStochasticGradientMetricContinuousTime(Wfn &w, Walker& walk, double &Energy, double &stddev, VectorXd &grad, VectorXd &H, DirectMetric &S, double &rk, int niter)
{
ContinuousTime<Wfn, Walker> CTMC(w, walk, niter);
Energy = 0.0, stddev = 0.0, rk = 0.0;
grad.setZero();
VectorXd grad_ratio_bar = VectorXd::Zero(grad.rows());
for (int iter = 0; iter < niter; iter++)
{
CTMC.LocalEnergy();
CTMC.LocalGradient();
CTMC.MakeMove();
CTMC.UpdateEnergy(Energy);
CTMC.UpdateGradient(grad, grad_ratio_bar);
CTMC.UpdateSR(S);
CTMC.UpdateBestDet();
}
CTMC.FinishEnergy(Energy, stddev, rk);
CTMC.FinishGradient(grad, grad_ratio_bar, Energy);
CTMC.FinishSR(grad, grad_ratio_bar, H);
CTMC.FinishBestDet();
}
template<typename Wfn, typename Walker>
void getStochasticOneRdmContinuousTime(Wfn &w, Walker &walk, MatrixXd &oneRdm, bool sz, int niter)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
workingArray work;
int iter = 0;
double ovlp = 0.;
oneRdm = MatrixXd::Constant(norbs, norbs, 0.);
MatrixXd localOneRdm = MatrixXd::Constant(norbs, norbs, 0.);
double bestOvlp = 0.;
double cumdeltaT = 0., cumdeltaT2 = 0.;
w.initWalker(walk);
Determinant bestDet = walk.d;
while (iter < niter) {
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
cumovlpRatio += abs(w.getOverlapFactor(I, J, A, B, walk, false));
work.ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations), nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
double ratio = deltaT / cumdeltaT;
localOneRdm.setZero(norbs, norbs);
vector<int> open;
vector<int> closed;
walk.d.getOpenClosed(sz, open, closed);
for (int p = 0; p < closed.size(); p++) {
localOneRdm(closed[p], closed[p]) = 1.;
for (int q = 0; q < open.size() && open[q] < closed[p]; q++) {
localOneRdm(closed[p], open[q]) = w.getOverlapFactor(2*closed[p] + sz, 2*open[q] + sz, walk, 0);
}
}
oneRdm += deltaT * (localOneRdm - oneRdm) / (cumdeltaT); //running average of energy
iter++;
walk.updateWalker(w.getRef(), w.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
double ovlp = w.Overlap(walk);
if (abs(ovlp) > bestOvlp)
{
bestOvlp = abs(ovlp);
bestDet = walk.getDet();
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, oneRdm.data(), norbs*norbs, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
oneRdm = oneRdm / commsize;
if (commrank == 0)
{
char file[5000];
sprintf(file, "BestDeterminant.txt");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << bestDet;
}
}
template<typename Wfn, typename Walker>
void getStochasticDensityCorrelationsContinuousTime(Wfn &w, Walker &walk, MatrixXd &corr, int niter)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
workingArray work;
int iter = 0;
double ovlp = 0.;
corr = MatrixXd::Constant(2*norbs, 2*norbs, 0.);
MatrixXd localCorr = MatrixXd::Constant(2*norbs, 2*norbs, 0.);
double bestOvlp = 0.;
double cumdeltaT = 0., cumdeltaT2 = 0.;
w.initWalker(walk);
Determinant bestDet = walk.d;
while (iter < niter) {
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
cumovlpRatio += abs(w.getOverlapFactor(I, J, A, B, walk, false));
work.ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations), nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
double ratio = deltaT / cumdeltaT;
localCorr.setZero(2*norbs, 2*norbs);
vector<int> open;
vector<int> closed;
walk.d.getOpenClosed(open, closed);
for (int p = 0; p < closed.size(); p++) {
localCorr(closed[p], closed[p]) = 1.;
for (int q = 0; q < p; q++) {
int P = max(closed[p], closed[q]), Q = min(closed[p], closed[q]);
localCorr(P, Q) = 1.;
}
}
corr += deltaT * (localCorr - corr) / (cumdeltaT); //running average of energy
iter++;
walk.updateWalker(w.getRef(), w.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
double ovlp = w.Overlap(walk);
if (abs(ovlp) > bestOvlp)
{
bestOvlp = abs(ovlp);
bestDet = walk.getDet();
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, corr.data(), 4*norbs*norbs, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
corr = corr / commsize;
if (commrank == 0)
{
char file[5000];
sprintf(file, "BestDeterminant.txt");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << bestDet;
}
}
template<typename Wfn, typename Walker>
void getLanczosCoeffsContinuousTime(Wfn &w, Walker &walk, double &alpha, Eigen::VectorXd &lanczosCoeffs, Eigen::VectorXd &stddev,
Eigen::VectorXd &rk, int niter, double targetError)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
int iter = 0;
Eigen::VectorXd S1 = Eigen::VectorXd::Zero(4);
Eigen::VectorXd coeffs = Eigen::VectorXd::Zero(4);
Eigen::VectorXd coeffsSample = Eigen::VectorXd::Zero(4);
double ovlpSample = 0.;
double bestOvlp = 0.;
Determinant bestDet = walk.getDet();
workingArray work, moreWork;
w.HamAndOvlpLanczos(walk, coeffsSample, ovlpSample, work, moreWork, alpha);
int nstore = 1000000 / commsize;
int gradIter = min(nstore, niter);
std::vector<std::vector<double>> gradError;
gradError.resize(4);
//std::vector<double> gradError(gradIter * commsize, 0.);
vector<double> tauError(gradIter * commsize, 0.);
for (int i = 0; i < 4; i++)
gradError[i] = std::vector<double>(gradIter * commsize, 0.);
double cumdeltaT = 0.;
double cumdeltaT2 = 0.;
int transIter = 0, nTransIter = schd.burnIter;
while (transIter < nTransIter) {
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
transIter++;
walk.updateWalker(w.getRef(), w.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
w.HamAndOvlpLanczos(walk, coeffsSample, ovlpSample, work, moreWork, alpha);
}
while (iter < niter) {
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
//double deltaT = -log(random())/(cumovlpRatio);
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
cumdeltaT2 += deltaT * deltaT;
double ratio = deltaT / cumdeltaT;
Eigen::VectorXd coeffsOld = coeffs;
coeffs += ratio * (coeffsSample - coeffs);
S1 += deltaT * (coeffsSample - coeffsOld).cwiseProduct(coeffsSample - coeffs);
if (iter < gradIter) {
tauError[iter + commrank * gradIter] = deltaT;
for (int i = 0; i < 4; i++)
gradError[i][iter + commrank * gradIter] = coeffsSample[i];
}
iter++;
walk.updateWalker(w.getRef(), w.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
w.HamAndOvlpLanczos(walk, coeffsSample, ovlpSample, work, moreWork, alpha);
}
coeffs *= cumdeltaT;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(gradError[0][0]), gradError[0].size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradError[1][0]), gradError[1].size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradError[2][0]), gradError[2].size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradError[3][0]), gradError[3].size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(tauError[0]), tauError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, coeffs.data(), 4, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
for (int i = 0; i < 4; i++)
{
vector<double> b_size, r_x;
block(b_size, r_x, gradError[i], tauError);
rk[i] = corrTime(gradError.size(), b_size, r_x);
S1[i] /= cumdeltaT;
}
double n_eff = commsize * (cumdeltaT * cumdeltaT) / cumdeltaT2;
for (int i = 0; i < 4; i++) {
stddev[i] = sqrt(S1[i] * rk[i] / n_eff);
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
lanczosCoeffs = coeffs / cumdeltaT;
}
/*
template<typename Wfn, typename Walker>
void getStochasticGradientHessianContinuousTime(Wfn &w, Walker& walk, double &E0, double &stddev, oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb, double &coreE, VectorXd &grad, MatrixXd& Hessian, MatrixXd& Smatrix, double &rk, int niter, double targetError)
{
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
int maxTerms = 1000000;
vector<double> ovlpRatio(maxTerms);
vector<size_t> excitation1( maxTerms), excitation2( maxTerms);
vector<double> HijElements(maxTerms);
int nExcitations = 0;
stddev = 1.e4;
int iter = 0;
double M1 = 0., S1 = 0., Eavg = 0.;
double Eloc = 0.;
double ham = 0., ovlp = 0.;
grad.setZero();
Hessian.setZero(); Smatrix.setZero();
VectorXd hamiltonianRatio = grad;
double scale = 1.0;
VectorXd diagonalGrad = VectorXd::Zero(grad.rows());
VectorXd localdiagonalGrad = VectorXd::Zero(grad.rows());
double bestOvlp =0.;
Determinant bestDet=walk.getDet();
nExcitations = 0;
E0 = 0.0;
w.HamAndOvlpGradient(walk, ovlp, ham, hamiltonianRatio, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, true, true);
w.OverlapWithGradient(walk, scale, localdiagonalGrad);
int nstore = 1000000/commsize;
int gradIter = min(nstore, niter);
std::vector<double> gradError(gradIter*commsize, 0);
std::vector<double> tauError(gradIter*commsize, 0);
double cumdeltaT = 0., cumdeltaT2 = 0.;
while (iter < niter && stddev > targetError)
{
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < nExcitations; i++)
{
cumovlpRatio += abs(ovlpRatio[i]);
ovlpRatio[i] = cumovlpRatio;
}
//double deltaT = -log(random())/(cumovlpRatio);
double deltaT = 1.0 / (cumovlpRatio);
int nextDet = std::lower_bound(ovlpRatio.begin(), (ovlpRatio.begin()+nExcitations),
random() * cumovlpRatio) -
ovlpRatio.begin();
cumdeltaT += deltaT;
cumdeltaT2 += deltaT * deltaT;
double Elocold = Eloc;
diagonalGrad = diagonalGrad + deltaT * (localdiagonalGrad - diagonalGrad) / (cumdeltaT);
grad = grad + deltaT * (localdiagonalGrad * ham - grad) / (cumdeltaT); //running average of grad
Eloc = Eloc + deltaT * (ham - Eloc) / (cumdeltaT); //running average of energy
Hessian.block(1, 1, grad.rows(), grad.rows()) += deltaT * (hamiltonianRatio * localdiagonalGrad.transpose() - Hessian.block(1, 1, grad.rows(), grad.rows())) / cumdeltaT;
Smatrix.block(1, 1, grad.rows(), grad.rows()) += deltaT * (localdiagonalGrad * localdiagonalGrad.transpose() - Smatrix.block(1, 1, grad.rows(), grad.rows())) / cumdeltaT;
Hessian.block(0, 1, 1, grad.rows()) += deltaT * (hamiltonianRatio.transpose() - Hessian.block(0, 1, 1, grad.rows())) / cumdeltaT;
Hessian.block(1, 0, grad.rows(), 1) += deltaT * (hamiltonianRatio - Hessian.block(1, 0, grad.rows(), 1)) / cumdeltaT;
Smatrix.block(0, 1, 1, grad.rows()) += deltaT * (localdiagonalGrad.transpose() - Smatrix.block(0, 1, 1, grad.rows())) / cumdeltaT;
Smatrix.block(1, 0, grad.rows(), 1) += deltaT * (localdiagonalGrad - Smatrix.block(1, 0, grad.rows(), 1)) / cumdeltaT;
S1 = S1 + deltaT * (ham - Elocold) * (ham - Eloc);
if (iter < gradIter)
{
gradError[iter + commrank*gradIter] = ham;
tauError[iter + commrank * gradIter] = deltaT;
}
iter++;
walk.updateWalker(w.getRef(), w.getCorr(), excitation1[nextDet], excitation2[nextDet]);
nExcitations = 0;
hamiltonianRatio.setZero();
localdiagonalGrad.setZero();
w.HamAndOvlpGradient(walk, ovlp, ham, hamiltonianRatio, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, true, true);
w.OverlapWithGradient(walk, ovlp, localdiagonalGrad);
if (abs(ovlp) > bestOvlp) {
bestOvlp = abs(ovlp);
bestDet = walk.getDet();
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(gradError[0]), gradError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(tauError[0]), tauError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(diagonalGrad[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Hessian(0,0)), Hessian.rows()*Hessian.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Smatrix(0,0)), Smatrix.rows()*Smatrix.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(grad[0]), grad.rows(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &Eloc, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
vector<double> b_size, r_x;
block(b_size,r_x,gradError,tauError);
rk = corr_time(gradError.size(), b_size, r_x);
//rk = calcTcorr(gradError);
diagonalGrad /= (commsize);
grad /= (commsize);
E0 = Eloc / commsize;
grad = grad - E0 * diagonalGrad;
Hessian = Hessian/(commsize);
Smatrix = Smatrix/(commsize);
S1 /= cumdeltaT
double n_eff = commsize * (cumdeltaT * cumdeltaT) / cumdeltaT2;
stddev = sqrt(S1 * rk / n_eff);
#ifndef SERIAL
MPI_Bcast(&stddev, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
Smatrix(0,0) = 1.0;
Hessian(0,0) = E0;
if (commrank == 0) {
char file[5000];
sprintf(file, "BestDeterminant.txt");
std::ofstream ofs(file, std::ios::binary);
boost::archive::binary_oarchive save(ofs);
save << bestDet;
}
}
*/
//############################################################Metropolis Evaluation############################################################################
template<typename Wfn, typename Walker>
void getStochasticGradientMetropolis(Wfn &w, Walker &walk, double &Energy, double &stddev, VectorXd &grad, double &rk, int niter)
{
Metropolis<Wfn, Walker> M(w, walk, niter);
Energy = 0.0, stddev = 0.0, rk = 0.0;
grad.setZero();
VectorXd grad_ratio_bar = VectorXd::Zero(grad.rows());
for (int iter = 0; iter < niter; iter++)
{
M.LocalEnergy();
M.LocalGradient();
//if (schd.usingFOIS)
// M.MakeMoveFOIS();
//else
M.MakeMove();
M.UpdateEnergy(Energy);
M.UpdateGradient(grad, grad_ratio_bar);
}
M.FinishEnergy(Energy, stddev, rk);
M.FinishGradient(grad, grad_ratio_bar, Energy);
}
template <typename Wfn, typename Walker>
class getGradientWrapper
{
public:
Wfn &w;
Walker &walk;
int stochasticIter;
bool ctmc;
getGradientWrapper(Wfn &pw, Walker &pwalk, int niter, bool pctmc) : w(pw), walk(pwalk)
{
stochasticIter = niter;
ctmc = pctmc;
};
void getGradient(VectorXd &vars, VectorXd &grad, double &E0, double &stddev, double &rt, bool deterministic)
{
w.updateVariables(vars);
w.initWalker(walk);
if (schd.debug) cout << "vars\n" << vars << endl << endl;
if (!deterministic)
{
if (ctmc)
{
getStochasticGradientContinuousTime(w, walk, E0, stddev, grad, rt, stochasticIter);
}
else
{
getStochasticGradientMetropolis(w, walk, E0, stddev, grad, rt, stochasticIter);
}
}
else
{
stddev = 0.0;
rt = 1.0;
getGradientDeterministic(w, walk, E0, grad);
}
w.writeWave();
};
void getMetric(VectorXd &vars, VectorXd &grad, VectorXd &H, DirectMetric &S, double &E0, double &stddev, double &rt, bool deterministic)
{
w.updateVariables(vars);
w.initWalker(walk);
if (!deterministic)
{
getStochasticGradientMetricContinuousTime(w, walk, E0, stddev, grad, H, S, rt, stochasticIter);
}
else
{
stddev = 0.0;
rt = 1.0;
getGradientMetricDeterministic(w, walk, E0, grad, H, S);
}
w.writeWave();
};
/*
void getHessian(VectorXd &vars, VectorXd &grad, MatrixXd &Hessian, MatrixXd &smatrix, double &E0, double &stddev, oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb, double &coreE, double &rt, bool deterministic)
{
if (!deterministic)
{
w.updateVariables(vars);
w.initWalker(walk);
getStochasticGradientHessianContinuousTime(w, walk, E0, stddev, I1, I2, I2hb, coreE, grad, Hessian, Smatrix, rt, stochasticIter, 0.5e-3);
}
else
{
w.updateVariables(vars);
w.initWalker(walk);
stddev = 0.0;
rt = 1.0;
getGradientHessianDeterministic(w, walk, E0, nalpha, nbeta, norbs, I1, I2, I2hb, coreE, grad, Hessian, Smatrix)
}
w.writeWave();
};
*/
};
#endif
<file_sep>#pragma once
#include "tensor.h"
double calc1DOvlp(int n1, double A, double expA,
int n2, double B, double expB,
tensor& S) ;
double calc1DOvlpPeriodic(int n1, double A, double expA,
int n2, double B, double expB,
double t, int AdditionalDeriv,
double L,
tensor& S, double* workArray,
tensor& powPiOverL, tensor& pow1OverExpA,
tensor& pow1OverExpB) ;
//actually it is \sqrt(pi/t) Theta3[z, exp(-pi*pi/t)]
double JacobiTheta(double z, double t, bool includeZero = true);
void JacobiThetaDerivative(double z, double t, double* workArray, int nderiv, bool includeZero=true) ;
double nChoosek( size_t n, size_t k );
double doubleFact(size_t n) ;
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef JastrowMultiSlater_HEADER_H
#define JastrowMultiSlater_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <unordered_set>
#include "igl/slice.h"
#include <unsupported/Eigen/CXX11/Tensor>
#include "JastrowMultiSlaterWalker.h"
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
class workingArray;
class Determinant;
struct JastrowMultiSlater {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & corr
& ref;
}
public:
Jastrow corr; //The jastrow factors
MultiSlater ref; //reference
//MatrixXcd intermediate, s;
double intermediateBuildTime, ciIterationTime;
JastrowMultiSlater() {
//intermediate = MatrixXcd::Zero(Determinant::nalpha + Determinant::nbeta, 2*Determinant::norbs);
//s = MatrixXcd::Zero(Determinant::nalpha + Determinant::nbeta, 2*Determinant::norbs);
//int nelec = Determinant::nalpha + Determinant::nbeta;
//int nholes = 2*Determinat::norbs - nelec;
//intermediate = MatrixXcd::Zero(nelec, 2*Determinant::norbs);
//s = MatrixXcd::Zero(Determinant::nalpha + Determinant::nbeta, 2*Determinant::norbs);
intermediateBuildTime = 0.;
ciIterationTime = 0.;
};
MultiSlater& getRef() { return ref; }
Jastrow& getCorr() { return corr; }
void initWalker(JastrowMultiSlaterWalker &walk)
{
walk = JastrowMultiSlaterWalker(corr, ref);
}
void initWalker(JastrowMultiSlaterWalker &walk, Determinant &d)
{
walk = JastrowMultiSlaterWalker(corr, ref, d);
}
/**
*This calculates the overlap of the walker with the
*jastrow and the ciexpansion
*/
double Overlap(const JastrowMultiSlaterWalker &walk) const
{
return corr.Overlap(walk.d) * walk.getDetOverlap(ref);
}
// these det ratio functions won't work for rdm calculations, they are only meant to be used in hamandoverlap below
// used in hamandvolp below
// returns < m | psi_0 > / < n | psi_0 > with complex projection
double getOverlapFactor(int i, int a, const JastrowMultiSlaterWalker& walk, bool doparity) const
{
return walk.walker.corrHelper.OverlapRatio(i, a, corr, walk.d, walk.d)
* walk.getDetFactor(i, a, ref);
}
double getOverlapFactor(int I, int J, int A, int B, const JastrowMultiSlaterWalker& walk, bool doparity) const
{
return 0.;
}
double getOverlapFactor(const JastrowMultiSlaterWalker& walk, std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to) const
{
//cout << "\ndet " << walk.getDetFactor(from, to) << " corr " << walk.corrHelper.OverlapRatio(from, to, corr) << endl;
return 0.;
}
/**
* This basically calls the overlapwithgradient(determinant, factor, grad)
*/
void OverlapWithGradient(const JastrowMultiSlaterWalker &walk,
double &factor,
Eigen::VectorXd &grad) const
{
double factor1 = 1.0;
Eigen::VectorBlock<VectorXd> gradhead = grad.head(corr.getNumVariables());
corr.OverlapWithGradient(walk.d, gradhead, factor1);
gradhead *= walk.walker.refHelper.totalOverlap / walk.walker.refHelper.refOverlap.real();
Eigen::VectorBlock<VectorXd> gradtail = grad.tail(grad.rows() - corr.getNumVariables());
walk.OverlapWithGradient(ref, gradtail);
}
void printVariables() const
{
corr.printVariables();
ref.printVariables();
}
void updateVariables(Eigen::VectorXd &v)
{
Eigen::VectorBlock<VectorXd> vhead = v.head(corr.getNumVariables());
corr.updateVariables(vhead);
Eigen::VectorBlock<VectorXd> vtail = v.tail(v.rows() - corr.getNumVariables());
ref.updateVariables(vtail);
}
void getVariables(Eigen::VectorXd &v) const
{
if (v.rows() != getNumVariables())
v = VectorXd::Zero(getNumVariables());
Eigen::VectorBlock<VectorXd> vhead = v.head(corr.getNumVariables());
corr.getVariables(vhead);
Eigen::VectorBlock<VectorXd> vtail = v.tail(v.rows() - corr.getNumVariables());
ref.getVariables(vtail);
}
long getNumJastrowVariables() const
{
return corr.getNumVariables();
}
//factor = <psi|w> * prefactor;
long getNumVariables() const
{
int norbs = Determinant::norbs;
long numVars = 0;
numVars += getNumJastrowVariables();
numVars += ref.getNumVariables();
return numVars;
}
string getfileName() const {
return ref.getfileName() + corr.getfileName();
}
void writeWave() const
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
//if (commrank == 0)
//{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
//}
#ifndef SERIAL
//boost::mpi::communicator world;
//boost::mpi::broadcast(world, *this, 0);
#endif
}
// this needs to be cleaned up, some of the necessary functions already exist
void HamAndOvlpDouble(const JastrowMultiSlaterWalker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true)
{
int norbs = Determinant::norbs;
int nelec = Determinant::nalpha + Determinant::nbeta;
int nholes = 2*norbs - nelec;
double refOverlap = walk.walker.refHelper.refOverlap.real(); // < n | phi_0 >
double j_n = corr.Overlap(walk.d); // J[n]
ovlp = j_n * refOverlap; // < n | psi_0 >
double ratio = walk.walker.refHelper.totalOverlap / refOverlap; // < n | psi > / < n | psi_0 >
//double ratio = walk.walker.refHelper.totalOverlap * j_n / refOverlap; // < n | psi > / < n | phi_0 >
ham = walk.d.Energy(I1, I2, coreE) * ratio;
double ham1 = 0.; // < n | H' | psi_0 > / < n | psi_0 > , where H' indicates the one particle part
complex<double> complexHam1(0., 0.); // above ratio without complex projection
double ham2 = 0.; // < n | H''| psi_0 > / < n | psi_0 > , where H'' indicates the two particle part
complex<double> complexHam2(0., 0.); // above ratio without complex projection
//Tensor<complex<double>, 4, RowMajor> h(nelec, nelec, 2*norbs, 2*norbs);
Tensor<complex<double>, 4, RowMajor> h(nelec, nelec, nholes, nholes);
h.setZero();
MatrixXcd intermediate = MatrixXcd::Zero(nelec, nholes);
intermediate.setZero();
work.setCounterToZero();
work.locNorm = ratio; // < psi | psi > / < psi_0 | psi_0 > sample sqrt
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
//MatrixXcd intermediate = MatrixXcd::Zero(Determinant::nalpha + Determinant::nbeta, 2*norbs);
//loop over all the screened excitations
//if (schd.debug) cout << "eloc excitations\nphi0 d.energy " << ham << endl;
double initTime = getTime();
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double jia = 0.;
complex<double> complexRefOverlapRatio(0., 0.);
double ovlpRatio = 0.;
if (ex2 == 0) {
int tableIndexi, tableIndexa;
walk.walker.refHelper.getRelIndices(I/2, tableIndexi, A/2, tableIndexa, I%2);
jia = walk.walker.corrHelper.OverlapRatio(I, A, corr, walk.d, walk.d);
complexRefOverlapRatio = walk.getDetFactorComplex(I, A, ref); // ratio without complex projection
intermediate.row(tableIndexi) += tia * jia * walk.walker.refHelper.rtc_b.row(tableIndexa);
ovlpRatio = jia * (complexRefOverlapRatio * walk.walker.refHelper.refOverlap).real() / refOverlap; // < m | psi_0 > / < n | psi_0 >
//ovlpRatio = (complexRefOverlapRatio * walk.walker.refHelper.refOverlap).real() / refOverlap; // < m | phi_0 > / < n | phi_0 >
ham1 += tia * ovlpRatio;
//ham1 += tia * jia * j_n * ovlpRatio;
complexHam1 += tia * jia * complexRefOverlapRatio;
//complexHam1 += tia * jia * j_n * complexRefOverlapRatio;
}
else {
int tableIndexi, tableIndexa, tableIndexj, tableIndexb;
if (I%2 == J%2) {
int ind00 = min(I/2, J/2), ind01 = min(A/2, B/2);
int ind10 = max(I/2, J/2), ind11 = max(A/2, B/2);
walk.walker.refHelper.getRelIndices(ind00, tableIndexi, ind01, tableIndexa, I%2);
walk.walker.refHelper.getRelIndices(ind10, tableIndexj, ind11, tableIndexb, J%2);
}
else if (I%2 == 0) {
walk.walker.refHelper.getRelIndices(I/2, tableIndexi, A/2, tableIndexa, I%2);
walk.walker.refHelper.getRelIndices(J/2, tableIndexj, B/2, tableIndexb, J%2);
}
else {
walk.walker.refHelper.getRelIndices(J/2, tableIndexi, B/2, tableIndexa, J%2);
walk.walker.refHelper.getRelIndices(I/2, tableIndexj, A/2, tableIndexb, I%2);
}
jia = walk.walker.corrHelper.OverlapRatio(I, J, A, B, corr, walk.d, walk.d);
complexRefOverlapRatio = walk.getDetFactorComplex(I, J, A, B, ref); // ratio without complex projection
ovlpRatio = jia * (complexRefOverlapRatio * walk.walker.refHelper.refOverlap).real() / refOverlap; // < m | psi_0 > / < n | psi_0 >
//ovlpRatio = (complexRefOverlapRatio * walk.walker.refHelper.refOverlap).real() / refOverlap; // < m | phi_0 > / < n | phi_0 >
h(tableIndexi, tableIndexj, tableIndexa, tableIndexb) = tia * jia;
ham2 += tia * ovlpRatio;
complexHam2 += tia * jia * complexRefOverlapRatio;
//ham2 += tia * jia * j_n * ovlpRatio;
//complexHam2 += tia * jia * j_n * complexRefOverlapRatio;
}
//double ovlpRatio = jia * walk.getDetFactor(I, A, ref); // < m | psi_0 > / < n | psi_0 >
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, false);
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, dbig, dbigcopy, false);
if (schd.debug) cout << I << " " << A << " " << J << " " << B << " tia " << tia << " jia " << jia << " ovlpRatio " << ovlpRatio << endl;
work.ovlpRatio[i] = ovlpRatio;
}
MatrixXcd s = walk.walker.refHelper.t * intermediate;
// double excitation intermediates
Tensor<complex<double>, 2, RowMajor> t (nelec, nelec);
Tensor<complex<double>, 2, RowMajor> rt (nholes, nelec);
Tensor<complex<double>, 2, RowMajor> rtc_b (nholes, nholes);
//Tensor<complex<double>, 2, RowMajor> rt (2*norbs, nelec);
//Tensor<complex<double>, 2, RowMajor> rtc_b (2*norbs, 2*norbs);
for (int i = 0; i < nelec; i++)
for (int j = 0; j < nelec; j++)
t(i, j) = walk.walker.refHelper.t(i, j);
for (int i = 0; i < nholes; i++)
for (int j = 0; j < nelec; j++)
rt(i, j) = walk.walker.refHelper.rt(i, j);
for (int i = 0; i < nholes; i++)
for (int j = 0; j < nholes; j++)
rtc_b(i, j) = walk.walker.refHelper.rtc_b(i, j);
//for (int i = 0; i < 2*norbs; i++)
// for (int j = 0; j < nelec; j++)
// rt(i, j) = walk.walker.refHelper.rt(i, j);
//
//for (int i = 0; i < 2*norbs; i++)
// for (int j = 0; j < 2*norbs; j++)
// rtc_b(i, j) = walk.walker.refHelper.rtc_b(i, j);
Eigen::array<IndexPair<int>, 2> prodDims0 = { IndexPair<int>(2, 0), IndexPair<int>(0, 1) };
Eigen::array<IndexPair<int>, 2> prodDims1 = { IndexPair<int>(1, 1), IndexPair<int>(2, 0) };
Tensor<complex<double>, 2, RowMajor> inter0 = h.contract(rt, prodDims0);
Tensor<complex<double>, 2, RowMajor> inter1 = h.contract(rt, prodDims1);
Eigen::array<IndexPair<int>, 1> matProd = { IndexPair<int>(1, 0) };
Tensor<complex<double>, 2, RowMajor> d0 = t.contract(inter0, matProd).contract(rtc_b, matProd) - t.contract(inter1, matProd).contract(rtc_b, matProd);
prodDims0 = { IndexPair<int>(0, 1), IndexPair<int>(3, 0) };
prodDims1 = { IndexPair<int>(1, 1), IndexPair<int>(3, 0) };
inter0 = h.contract(rt, prodDims0);
inter1 = h.contract(rt, prodDims1);
Tensor<complex<double>, 2, RowMajor> d1 = t.contract(inter0, matProd).contract(rtc_b, matProd) - t.contract(inter1, matProd).contract(rtc_b, matProd);
Eigen::array<IndexPair<int>, 1> trans0 = { IndexPair<int>(0, 1) };
Eigen::array<IndexPair<int>, 1> trans1 = { IndexPair<int>(0, 0) };
Tensor<complex<double>, 4, RowMajor> hbar = h.contract(t, trans0).contract(t, trans0).contract(rtc_b, trans1).contract(rtc_b, trans1);
//Tensor<complex<double>, 4, RowMajor> d2 (nelec, nelec, 2*norbs, 2*norbs);
Tensor<complex<double>, 4, RowMajor> d2 (nelec, nelec, nholes, nholes);
for (int i = 0; i < nelec; i++) {
for (int j = 0; j < nelec; j++) {
for (int a = 0; a < nholes; a++) {
for (int b = 0; b < nholes; b++) {
d2(i,j,a,b) = hbar(i,j,a,b) - hbar(i,j,b,a) - hbar(j,i,a,b) + hbar(j,i,b,a);
}
}
}
}
//for (int i = 0; i < nelec; i++) {
// for (int j = 0; j < nelec; j++) {
// for (int a = 0; a < 2*norbs; a++) {
// for (int b = 0; b < 2*norbs; b++) {
// d2(i,j,a,b) = hbar(i,j,a,b) - hbar(i,j,b,a) - hbar(j,i,a,b) + hbar(j,i,b,a);
// }
// }
// }
//}
//
if (schd.debug) {
cout << "s\n" << s << endl << endl;
cout << "d0\n" << d0 << endl << endl;
cout << "d1\n" << d1 << endl << endl;
cout << "h\n\n";
for (int i = 0; i < nelec; i++) {
for (int j = 0; j < nelec; j++) {
cout << "slice " << i << " " << j << endl;
for (int a = 0; a < nholes; a++) {
for (int b = 0; b < nholes; b++) {
cout << h(i, j, a, b) << " ";
}
cout << endl;
}
cout << endl;
}
}
cout << "d2\n\n";
for (int i = 0; i < nelec; i++) {
for (int j = 0; j < nelec; j++) {
cout << "slice " << i << " " << j << endl;
for (int a = 0; a < nholes; a++) {
for (int b = 0; b < nholes; b++) {
cout << d2(i, j, a, b) << " ";
}
cout << endl;
}
cout << endl;
}
}
}
intermediateBuildTime += (getTime() - initTime);
initTime = getTime();
double locES1 = ref.ciCoeffs[0] * ham1; // singles local energy
double locES2 = ref.ciCoeffs[0] * ham2; // doubles local energy
size_t count4 = 0;
for (int i = 1; i < ref.numDets; i++) {
int rank = ref.ciExcitations[i][0].size();
complex<double> laplaceDet1(0., 0.);
complex<double> laplaceDet20(0., 0.);
complex<double> laplaceDet21(0., 0.);
complex<double> laplaceDet22(0., 0.);
if (rank == 1) {
laplaceDet1 = -s(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]);
laplaceDet20 = -d0(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]);
laplaceDet21 = d1(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]);
}
else if (rank == 2) {
laplaceDet1 = -(s(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- s(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0])
+ walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * s(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * s(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0]));
laplaceDet20 = -(d0(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- d0(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0])
+ walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * d0(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * d0(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0]));
laplaceDet21 = d1(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- d1(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0])
+ walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * d1(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * d1(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0]);
laplaceDet22 = d2(ref.ciExcitations[i][0][0], ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0], ref.ciExcitations[i][1][1]);
}
else if (rank == 3) {
Matrix3cd temp;
Matrix3cd tcSlice;
//igl::slice(walk.walker.refHelper.tc, ref.ciExcitations[i][0], ref.ciExcitations[i][1], tcSlice);
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
tcSlice(mu, nu) = walk.walker.refHelper.tc(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][nu]);
for (int mu = 0; mu < rank; mu++) {
temp = tcSlice;
for (int t = 0; t < rank; t++) {
temp(mu, t) = s(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet1 -= temp.determinant();
for (int t = 0; t < rank; t++) {
temp(mu, t) = d0(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet20 -= temp.determinant();
for (int t = 0; t < rank; t++) {
temp(mu, t) = d1(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet21 += temp.determinant();
}
for (int mu = 0; mu < rank; mu++) {
for (int nu = mu + 1; nu < rank; nu++) {
double parity_munu = ((mu + nu + 1)%2 == 0) ? 1. : -1.;
for (int t = 0; t < rank; t++) {
for (int u = t + 1; u < rank; u++) {
double parity_tu = ((t + u + 1)%2 == 0) ? 1. : -1.;
laplaceDet22 += parity_munu * parity_tu * d2(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][0][nu], ref.ciExcitations[i][1][t], ref.ciExcitations[i][1][u])
* tcSlice(3 - mu - nu, 3 - t - u);
}
}
}
}
}
else if (rank == 4) {
Matrix4cd temp;
for (int mu = 0; mu < rank; mu++) {
temp = walk.walker.refHelper.tcSlice[count4];
for (int t = 0; t < rank; t++) {
temp(mu, t) = s(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet1 -= temp.determinant();
for (int t = 0; t < rank; t++) {
temp(mu, t) = d0(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet20 -= temp.determinant();
for (int t = 0; t < rank; t++) {
temp(mu, t) = d1(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet21 += temp.determinant();
}
for (int mu = 0; mu < rank; mu++) {
for (int nu = mu + 1; nu < rank; nu++) {
double parity_munu = ((mu + nu + 1)%2 == 0) ? 1. : -1.;
int mup, nup;
if (mu == 0) {
mup = 3 - nu + nu/3; nup = 6 - nu - mup;
}
else {
mup = 0; nup = 6 - mu - nu;
}
for (int t = 0; t < rank; t++) {
for (int u = t + 1; u < rank; u++) {
double parity_tu = ((t + u + 1)%2 == 0) ? 1. : -1.;
int tp, up;
if (t == 0) {
tp = 3 - u + u/3; up = 6 - u - tp;
}
else {
tp = 0; up = 6 - t - u;
}
laplaceDet22 += parity_munu * parity_tu * d2(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][0][nu], ref.ciExcitations[i][1][t], ref.ciExcitations[i][1][u])
* ( walk.walker.refHelper.tcSlice[count4](mup, tp) * walk.walker.refHelper.tcSlice[count4](nup, up)
- walk.walker.refHelper.tcSlice[count4](mup, up) * walk.walker.refHelper.tcSlice[count4](nup, tp));
}
}
}
}
count4++;
}
else {
MatrixXcd tcSlice = MatrixXcd::Zero(rank, rank);
//igl::slice(walk.walker.refHelper.tc, ref.ciExcitations[i][0], ref.ciExcitations[i][1], tcSlice);
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
tcSlice(mu, nu) = walk.walker.refHelper.tc(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][nu]);
MatrixXcd temp = MatrixXcd::Zero(rank, rank);
for (int mu = 0; mu < rank; mu++) {
temp = tcSlice;
for (int t = 0; t < rank; t++) {
temp(mu, t) = s(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet1 -= temp.determinant();
for (int t = 0; t < rank; t++) {
temp(mu, t) = d0(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet20 -= temp.determinant();
for (int t = 0; t < rank; t++) {
temp(mu, t) = d1(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet21 += temp.determinant();
vector<int> range(rank);
for (int mu = 0; mu < rank; mu++) range[mu] = mu;
for (int mu = 0; mu < rank; mu++) {
for (int nu = mu + 1; nu < rank; nu++) {
double parity_munu = ((mu + nu + 1)%2 == 0) ? 1. : -1.;
vector<int> munu = {mu, nu};
vector<int> diff0;
std::set_difference(range.begin(), range.end(), munu.begin(), munu.end(), std::inserter(diff0, diff0.begin()));
for (int t = 0; t < rank; t++) {
for (int u = t + 1; u < rank; u++) {
double parity_tu = ((t + u + 1)%2 == 0) ? 1. : -1.;
vector<int> tu = {t, u};
vector<int> diff1;
std::set_difference(range.begin(), range.end(), tu.begin(), tu.end(), std::inserter(diff1, diff1.begin()));
MatrixXcd tcSliceSlice = MatrixXcd::Zero(rank - 2, rank - 2);
//igl::slice(walk.walker.refHelper.tc, ref.ciExcitations[i][0], ref.ciExcitations[i][1], tcSlice);
for (int mup = 0; mup < rank - 2; mup++)
for (int nup = 0; nup < rank - 2; nup++)
tcSliceSlice(mup, nup) = tcSlice(diff0[mup], diff1[nup]);
laplaceDet22 += parity_munu * parity_tu * d2(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][0][nu], ref.ciExcitations[i][1][t], ref.ciExcitations[i][1][u])
* tcSliceSlice.determinant();
}
}
}
}
}
}
locES1 += ref.ciCoeffs[i] * ((walk.walker.refHelper.ciOverlapRatios[i] * complexHam1 + complex<double>(ref.ciParity[i]) * laplaceDet1) * walk.walker.refHelper.refOverlap).real() / refOverlap;
locES2 += ref.ciCoeffs[i] * ((walk.walker.refHelper.ciOverlapRatios[i] * complexHam2 + complex<double>(ref.ciParity[i]) * (laplaceDet20 + laplaceDet21 + laplaceDet22)) * walk.walker.refHelper.refOverlap).real() / refOverlap;
}
ciIterationTime += (getTime() - initTime);
ham += (locES1 + locES2);
ham *= ratio;
}
// this needs to be cleaned up, some of the necessary functions already exist
// only single excitations for now
void HamAndOvlpSingle(const JastrowMultiSlaterWalker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true)
{
int norbs = Determinant::norbs;
int nelec = Determinant::nalpha + Determinant::nbeta;
int nholes = 2*norbs - nelec;
double refOverlap = walk.walker.refHelper.refOverlap.real(); // < n | phi_0 >
ovlp = corr.Overlap(walk.d) * refOverlap; // < n | psi_0 >
double ratio = walk.walker.refHelper.totalOverlap / refOverlap; // < n | psi > / < n | psi_0 >
ham = walk.d.Energy(I1, I2, coreE) * ratio;
double ham1 = 0.; // < n | H' | psi_0 > / < n | psi_0 > , where H' indicates the one particle part
complex<double> complexHam1(0., 0.); // above ratio without complex projection
//Tensor<complex<double>, 4, RowMajor> h(nelec, nelec, 2*norbs, 2*norbs);
MatrixXcd intermediate = MatrixXcd::Zero(nelec, nholes);
intermediate.setZero();
work.setCounterToZero();
work.locNorm = ratio; // < psi | psi > / < psi_0 | psi_0 > sample sqrt
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
//MatrixXcd intermediate = MatrixXcd::Zero(Determinant::nalpha + Determinant::nbeta, 2*norbs);
//loop over all the screened excitations
//if (schd.debug) cout << "eloc excitations\nphi0 d.energy " << ham << endl;
double initTime = getTime();
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
double jia = 0.;
complex<double> complexRefOverlapRatio(0., 0.);
double ovlpRatio = 0.;
int tableIndexi, tableIndexa;
walk.walker.refHelper.getRelIndices(I/2, tableIndexi, A/2, tableIndexa, I%2);
jia = walk.walker.corrHelper.OverlapRatio(I, A, corr, walk.d, walk.d);
complexRefOverlapRatio = walk.getDetFactorComplex(I, A, ref); // ratio without complex projection
intermediate.row(tableIndexi) += tia * jia * walk.walker.refHelper.rtc_b.row(tableIndexa);
ovlpRatio = jia * (complexRefOverlapRatio * walk.walker.refHelper.refOverlap).real() / refOverlap; // < m | psi_0 > / < n | psi_0 >
ham1 += tia * ovlpRatio;
complexHam1 += tia * jia * complexRefOverlapRatio;
//double ovlpRatio = jia * walk.getDetFactor(I, A, ref); // < m | psi_0 > / < n | psi_0 >
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, false);
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, dbig, dbigcopy, false);
if (schd.debug) cout << I << " " << A << " tia " << tia << " jia " << jia << " ovlpRatio " << ovlpRatio << endl;
work.ovlpRatio[i] = ovlpRatio;
}
MatrixXcd s = walk.walker.refHelper.t * intermediate;
intermediateBuildTime += (getTime() - initTime);
initTime = getTime();
double locES1 = ref.ciCoeffs[0] * ham1; // singles local energy
size_t count4 = 0;
for (int i = 1; i < ref.numDets; i++) {
int rank = ref.ciExcitations[i][0].size();
complex<double> laplaceDet1(0., 0.);
if (rank == 1) {
laplaceDet1 = -s(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]);
}
else if (rank == 2) {
laplaceDet1 = -(s(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- s(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * walk.walker.refHelper.tc(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0])
+ walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][0]) * s(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][1])
- walk.walker.refHelper.tc(ref.ciExcitations[i][0][0], ref.ciExcitations[i][1][1]) * s(ref.ciExcitations[i][0][1], ref.ciExcitations[i][1][0]));
}
else if (rank == 3) {
Matrix3cd temp;
Matrix3cd tcSlice;
//igl::slice(walk.walker.refHelper.tc, ref.ciExcitations[i][0], ref.ciExcitations[i][1], tcSlice);
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
tcSlice(mu, nu) = walk.walker.refHelper.tc(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][nu]);
for (int mu = 0; mu < rank; mu++) {
temp = tcSlice;
for (int t = 0; t < rank; t++) {
temp(mu, t) = s(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet1 -= temp.determinant();
}
}
else if (rank == 4) {
Matrix4cd temp;
for (int mu = 0; mu < rank; mu++) {
temp = walk.walker.refHelper.tcSlice[count4];
for (int t = 0; t < rank; t++) {
temp(mu, t) = s(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet1 -= temp.determinant();
}
count4++;
}
else {
MatrixXcd tcSlice = MatrixXcd::Zero(rank, rank);
//igl::slice(walk.walker.refHelper.tc, ref.ciExcitations[i][0], ref.ciExcitations[i][1], tcSlice);
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
tcSlice(mu, nu) = walk.walker.refHelper.tc(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][nu]);
MatrixXcd temp = MatrixXcd::Zero(rank, rank);
for (int mu = 0; mu < rank; mu++) {
temp = tcSlice;
for (int t = 0; t < rank; t++) {
temp(mu, t) = s(ref.ciExcitations[i][0][mu], ref.ciExcitations[i][1][t]);
}
laplaceDet1 -= temp.determinant();
}
}
locES1 += ref.ciCoeffs[i] * ((walk.walker.refHelper.ciOverlapRatios[i] * complexHam1 + complex<double>(ref.ciParity[i]) * laplaceDet1) * walk.walker.refHelper.refOverlap).real() / refOverlap;
}
ciIterationTime += (getTime() - initTime);
ham += locES1;
ham *= ratio;
}
void HamAndOvlp(const JastrowMultiSlaterWalker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true)
{
if (schd.Hamiltonian == HUBBARD)
HamAndOvlpSingle(walk, ovlp, ham, work, fillExcitations);
else
HamAndOvlpDouble(walk, ovlp, ham, work, fillExcitations);
}
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MRCI_HEADER_H
#define MRCI_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/array.hpp>
#include <utility>
#include <iomanip>
#include "MRCIWalker.h"
#include "CorrelatedWavefunction.h"
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace std;
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
template<typename Corr, typename Reference>
class MRCI
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & wave
& coeffs;
}
public:
using CorrType = Corr;
using ReferenceType = Reference;
VectorXd coeffs;
CorrelatedWavefunction<Corr, Reference> wave; //reference wavefunction
workingArray morework;
MRCI()
{
//wave = CorrelatedWavefunction<Corr, Reference>();
wave.readWave();
//cout << "JS vars\n"; wave.printVariables();
// Resize coeffs
int numVirt = Determinant::norbs - schd.nciAct;
int numCoeffs = 2 + 2*numVirt + (2*numVirt * (2*numVirt - 1) / 2);
coeffs = VectorXd::Zero(numCoeffs);
//coeffs order: phi0, singly excited (spin orb index), doubly excited (spin orb pair index)
if (commrank == 0) {
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
coeffs(0) = -0.5;
//coeffs(1) = -0.5;
for (int i=1; i < numCoeffs; i++) {
coeffs(i) = 0.2*random() - 0.1;
}
}
#ifndef SERIAL
MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
char file[5000];
sprintf(file, "ciCoeffs.txt");
ifstream ofile(file);
if (ofile) {
for (int i = 0; i < coeffs.size(); i++) {
ofile >> coeffs(i);
}
}
//cout << "ciCoeffs\n" << coeffs << endl;
}
Reference& getRef() { return wave.getRef(); }
Corr& getCorr() { return wave.getCorr(); }
void initWalker(MRCIWalker<Corr, Reference> &walk)
{
walk = MRCIWalker<Corr, Reference>(wave.corr, wave.ref);
}
void initWalker(MRCIWalker<Corr, Reference> &walk, Determinant &d)
{
walk = MRCIWalker<Corr, Reference>(wave.corr, wave.ref, d);
}
void getVariables(VectorXd& vars) {
vars = coeffs;
}
void printVariables() {
cout << "ci coeffs\n" << coeffs << endl;
}
void updateVariables(VectorXd& vars) {
coeffs = vars;
}
long getNumVariables() {
return coeffs.size();
}
//returns the s^(k)_l space index the walker with the given excitedOrbs belongs to
int coeffsIndex(unordered_set<int> &excitedOrbs) {
int norbs = Determinant::norbs;
if (excitedOrbs.size() == 2) {
int i = *excitedOrbs.begin() - 2*schd.nciAct;
int j = *(std::next(excitedOrbs.begin())) - 2*schd.nciAct;
int I = max(i, j) - 1, J = min(i,j);
int numVirt = norbs - schd.nciAct;
return 2 + 2*numVirt + I*(I+1)/2 + J;
}
else if (excitedOrbs.size() == 1) {
return *excitedOrbs.begin() - 2*schd.nciAct + 2;
}
else if (excitedOrbs.size() == 0) return 0;
else return -1;
}
//this could be expensive
//returns the s^(k)_l space index the walker with the given excitedOrbs belongs to
int coeffsIndex(MRCIWalker<Corr, Reference>& walk) {
int norbs = Determinant::norbs;
if (walk.excitedSpinOrbs.size() == 2) {
int i = *walk.excitedSpinOrbs.begin() - 2*schd.nciAct;
int j = *(std::next(walk.excitedSpinOrbs.begin())) - 2*schd.nciAct;
int I = max(i, j) - 1, J = min(i,j);
int numVirt = norbs - schd.nciAct;
return 2 + 2*numVirt + I*(I+1)/2 + J;
}
else if (walk.excitedSpinOrbs.size() == 1) {
return *walk.excitedSpinOrbs.begin() - 2*schd.nciAct + 2;
}
else if (walk.excitedSpinOrbs.size() == 0) return 0;
else return -1;
}
double getOverlapFactor(int i, int a, const MRCIWalker<Corr, Reference>& walk, bool doparity) const
{
return 1.;
}//not used
double getOverlapFactor(int I, int J, int A, int B, const MRCIWalker<Corr, Reference>& walk, bool doparity) const
{
return 1.;
}//not used
void OverlapWithGradient(MRCIWalker<Corr, Reference> &walk,
double &factor,
Eigen::VectorXd &grad)
{
int coeffsIndex = this->coeffsIndex(walk);
double ciCoeff = coeffs(coeffsIndex);
if (coeffsIndex < 0 || ciCoeff == 0) return;
if (coeffsIndex == 0) {
double ham = 0., ovlp = 0.;
morework.setCounterToZero();
wave.HamAndOvlp(walk.activeWalker, ovlp, ham, morework);
grad[0] += 1 / (coeffs(0) + coeffs(1) * ham);
grad[1] += ham / (coeffs(0) + coeffs(1) * ham);
}
else {
int norbs = Determinant::norbs;
//if (abs(ciCoeff) <= 1.e-8) return;
grad(coeffsIndex) += 1 / ciCoeff;
}
}
//updates from and to by combining with excitations ex1 and ex2, also updates excitedOrbs
//used for n -> m
//ex1 assumed to be nonzero and ex2 = 0 for single excitations
void combineExcitations(int ex1, int ex2, unordered_set<int> &excitedOrbs, std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to)
{
int norbs = Determinant::norbs;
int I = ex1 / (2 * norbs), A = ex1 % (2 * norbs);
if (A >= 2*schd.nciAct) excitedOrbs.insert(A);
if (I >= 2*schd.nciAct) excitedOrbs.erase(I);
int i = I / 2, a = A / 2;
bool sz = I%2;
auto itOrbsi = to[sz].find(i);
auto itHolesa = from[sz].find(a);
if (itOrbsi == to[sz].end()) from[sz].insert(i);
else to[sz].erase(itOrbsi);
if (itHolesa == from[sz].end()) to[sz].insert(a);
else from[sz].erase(itHolesa);
if (ex2 != 0) {
int J = ex2 / (2 * norbs), B = ex2 % (2 * norbs);
if (B >= 2*schd.nciAct) excitedOrbs.insert(B);
if (J >= 2*schd.nciAct) excitedOrbs.erase(J);
int j = J / 2, b = B / 2;
sz = J%2;
auto itOrbsj = to[sz].find(j);
auto itHolesb = from[sz].find(b);
if (itOrbsj == to[sz].end()) from[sz].insert(j);
else to[sz].erase(itOrbsj);
if (itHolesb == from[sz].end()) to[sz].insert(b);
else from[sz].erase(itHolesb);
}
}
//updates from and to by combining with excitations ex1 and ex2
//used for m -> m'
//ex1 assumed to be nonzero and ex2 = 0 for single excitations
void combineExcitations(int ex1, int ex2, std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to)
{
int norbs = Determinant::norbs;
int I = ex1 / (2 * norbs), A = ex1 % (2 * norbs);
int i = I / 2, a = A / 2;
bool sz = I%2;
auto itOrbsi = to[sz].find(i);
auto itHolesa = from[sz].find(a);
if (itOrbsi == to[sz].end()) from[sz].insert(i);
else to[sz].erase(itOrbsi);
if (itHolesa == from[sz].end()) to[sz].insert(a);
else from[sz].erase(itHolesa);
if (ex2 != 0) {
int J = ex2 / (2 * norbs), B = ex2 % (2 * norbs);
int j = J / 2, b = B / 2;
sz = J%2;
auto itOrbsj = to[sz].find(j);
auto itHolesb = from[sz].find(b);
if (itOrbsj == to[sz].end()) from[sz].insert(j);
else to[sz].erase(itOrbsj);
if (itHolesb == from[sz].end()) to[sz].insert(b);
else from[sz].erase(itHolesb);
}
}
//returns < m | psi > / < n_0 | phi >
//the walker n contains n_0 and its helpers
//from and to are excitations from n_0 to m
//mEne would be required if the Lanczos term is included
//this is essentially HamAndOvlp with the reference
double ovlpRatio(MRCIWalker<Corr, Reference> &n, Determinant &m, int &coeffsIndex, unordered_set<int> &excitedOrbs, std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to, double mEne, workingArray &work)
{
int norbs = Determinant::norbs;
double ham = 0.; //ovlp sans coeff
if (coeffsIndex == 0) {// < m | psi > = c_0 < m | phi > + c_0^(0) < m | H | phi >
ham += m.Energy(I1, I2, coreE) * wave.getOverlapFactor(n.activeWalker, from, to);
}
work.setCounterToZero();
if (excitedOrbs.size() == 2) {
generateAllScreenedExcitationsCAS_0h2p(m, schd.epsilon, work, *excitedOrbs.begin(), *std::next(excitedOrbs.begin()));
}
else if (excitedOrbs.size() == 1) {
generateAllScreenedSingleExcitationsCAS_0h1p(m, schd.epsilon, schd.screen,
work, *excitedOrbs.begin(), false);
generateAllScreenedDoubleExcitationsCAS_0h1p(m, schd.epsilon, work, *excitedOrbs.begin());
}
else {
generateAllScreenedSingleExcitationsCAS_0h0p(m, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitationsCAS_0h0p(m, schd.epsilon, work);
}
//if (schd.debug) cout << "phi0 d.energy " << ham / ovlp << endl;
//loop over all the screened excitations
//cout << "m " << walk.d << endl;
//cout << "eloc excitations" << endl;
std::array<unordered_set<int>, 2> fromNew = from;
std::array<unordered_set<int>, 2> toNew = to;
//cout << "\ngenerating mp's\n\n";
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
//cout << "ex1 " << ex1 << " ex2 " << ex2 << endl;
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double parity = 1.;
Determinant dcopy = m;
parity *= dcopy.parity(A/2, I/2, I%2);
//if (A > I) parity *= -1. * dcopy.parity(A/2, I/2, I%2);
//else parity *= dcopy.parity(A/2, I/2, I%2);
if (ex2 != 0) {
dcopy.setocc(I, false); //move these insisde the next if
dcopy.setocc(A, true);
parity *= dcopy.parity(B/2, J/2, J%2);
//dcopy.setocc(J, false); //delete these
//dcopy.setocc(B, true);
//if (B > J) parity *= -1 * dcopy.parity(B/2, J/2, J%2);
//else parity *= dcopy.parity(B/2, J/2, J%2);
}
//cout << "m' " << dcopy << endl;
//dcopy = n.activeWalker.d;
combineExcitations(ex1, ex2, fromNew, toNew);
//cout << "from u ";
//copy(fromNew[0].begin(), fromNew[0].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "from d ";
//copy(fromNew[1].begin(), fromNew[1].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "to u ";
//copy(toNew[0].begin(), toNew[0].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "to d ";
//copy(toNew[1].begin(), toNew[1].end(), ostream_iterator<int>(cout, " "));
//cout << endl;
ham += tia * wave.getOverlapFactor(n.activeWalker, fromNew, toNew) * parity;
//ovlpRatio += tia * wave.getOverlapFactor(n.activeWalker, fromNew, toNew);
//cout << "tia " << tia << " ovlpRatio0 " << wave.getOverlapFactor(n.activeWalker, dcopy, fromNew, toNew) << " " << parity << endl << endl;
//cout << "n.parity " << n.parity << endl;
fromNew = from;
toNew = to;
//if (schd.debug) cout << ex1 << " " << ex2 << " tia " << tia << " ovlpRatio " << ovlpcopy * parity << endl;
//work.ovlpRatio[i] = ovlp;
}
if (coeffsIndex == 0) return coeffs(0) * wave.getOverlapFactor(n.activeWalker, from, to) + coeffs(1) * ham;
else return coeffs(coeffsIndex) * ham;
//if (schd.debug) cout << "ham " << ham << " ovlp " << ovlp << endl << endl;
}
// not used
template<typename Walker>
bool checkWalkerExcitationClass(Walker &walk) {
return true;
}
void HamAndOvlp(MRCIWalker<Corr, Reference> &n,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true)
{
if (n.excitedSpinOrbs.size() > 2) return;
//cout << "\nin HamAndOvlp\n";
int norbs = Determinant::norbs;
int coeffsIndex = this->coeffsIndex(n);
//cout << "coeffsIndex " << coeffsIndex << endl;
double ciCoeff = coeffs(coeffsIndex);
double dEne = n.d.Energy(I1, I2, coreE);
double ovlp0 = wave.Overlap(n.activeWalker); // < n_0 | phi >
morework.setCounterToZero();
double ovlpRatio0 = ovlpRatio(n, n.d, coeffsIndex, n.excitedSpinOrbs, n.excitedHoles, n.excitedOrbs, dEne, morework); // < n | psi > / < n_0 | phi >
ovlp = ovlpRatio0 * ovlp0; // < n | psi >
//cout << "ovlp0 " << ovlp0 << " ovlpRatio0 " << ovlpRatio0 << endl;
if (ovlp == 0.) return; //maybe not necessary
ham = dEne * ovlpRatio0;
work.setCounterToZero();
generateAllScreenedSingleExcitation(n.d, schd.epsilon, schd.screen,
work, false);
if (n.excitedSpinOrbs.size() == 0) {
generateAllScreenedDoubleExcitation(n.d, schd.epsilon, schd.screen,
work, false);
}
else {
generateAllScreenedDoubleExcitationsFOIS(n.d, schd.epsilon, schd.screen,
work, false);
}
//loop over all the screened excitations
//cout << "\ngenerating m's\n\n";
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double parity = 1.;
//cout << "ex1 " << ex1 << " ex2 " << ex2 << endl;
unordered_set<int> excitedOrbs = n.excitedSpinOrbs;
std::array<unordered_set<int> , 2> from = n.excitedHoles;
std::array<unordered_set<int> , 2> to = n.excitedOrbs;
combineExcitations(ex1, ex2, excitedOrbs, from, to);
//cout << "excitedOrbs ";
//copy(excitedOrbs.begin(), excitedOrbs.end(), ostream_iterator<int>(cout, " "));
//cout << endl << "from u ";
//copy(from[0].begin(), from[0].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "from d ";
//copy(from[1].begin(), from[1].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "to u ";
//copy(to[0].begin(), to[0].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "to d ";
//copy(to[1].begin(), to[1].end(), ostream_iterator<int>(cout, " "));
//cout << endl;
if (excitedOrbs.size() > 2) continue;
Determinant m = n.d;
parity *= m.parity(A/2, I/2, I%2);
double mEne = 0.;
//if (ex2 == 0) {
// mEne = dEne + n.energyIntermediates[A%2][A/2] - n.energyIntermediates[I%2][I/2]
// - (I2.Direct(I/2, A/2) - I2.Exchange(I/2, A/2));
//}
//else {
m.setocc(I, false);
m.setocc(A, true);
if (ex2 != 0) {
parity *= m.parity(B/2, J/2, J%2);
m.setocc(J, false);
m.setocc(B, true);
//bool sameSpin = (I%2 == J%2);
//mEne = dEne + n.energyIntermediates[A%2][A/2] - n.energyIntermediates[I%2][I/2]
// + n.energyIntermediates[B%2][B/2] - n.energyIntermediates[J%2][J/2]
// + I2.Direct(A/2, B/2) - sameSpin * I2.Exchange(A/2, B/2)
// + I2.Direct(I/2, J/2) - sameSpin * I2.Exchange(I/2, J/2)
// - (I2.Direct(I/2, A/2) - I2.Exchange(I/2, A/2))
// - (I2.Direct(J/2, B/2) - I2.Exchange(J/2, B/2))
// - (I2.Direct(I/2, B/2) - sameSpin * I2.Exchange(I/2, B/2))
// - (I2.Direct(J/2, A/2) - sameSpin * I2.Exchange(J/2, A/2));
}
int coeffsCopyIndex = this->coeffsIndex(excitedOrbs);
//cout << "m " << m << endl;
//cout << "m index " << coeffsCopyIndex << endl;
morework.setCounterToZero();
double ovlpRatiom = ovlpRatio(n, m, coeffsCopyIndex, excitedOrbs, from, to, mEne, morework);// < m | psi > / < n_0 | psi >
work.ovlpRatio[i] = ovlpRatiom / ovlpRatio0;
ham += parity * tia * ovlpRatiom;
//ham += tia * ovlpRatiom;
//cout << "hamSample " << tia * ovlpRatiom << endl;
//cout << "ovlpRatiom " << ovlpRatiom << " tia " << tia << " parity " << parity << endl << endl;
}
ham /= ovlpRatio0;
}
// template<typename Walker>
// double calcEnergy(Walker& walk) {
//
// //sampling
// int norbs = Determinant::norbs;
// auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
// std::ref(generator));
//
//
// double ovlp = 0., locEne = 0., ene = 0., correctionFactor = 0.;
// int coeffsIndex = this->coeffsIndex(walk);
// workingArray work;
// HamAndOvlp(walk, ovlp, locEne, work);
//
// int iter = 0;
// double cumdeltaT = 0.;
//
// while (iter < schd.stochasticIter) {
// double cumovlpRatio = 0;
// for (int i = 0; i < work.nExcitations; i++) {
// cumovlpRatio += abs(work.ovlpRatio[i]);
// work.ovlpRatio[i] = cumovlpRatio;
// }
// double deltaT = 1.0 / (cumovlpRatio);
// double nextDetRandom = random() * cumovlpRatio;
// int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
// nextDetRandom) - work.ovlpRatio.begin();
// cumdeltaT += deltaT;
// double ratio = deltaT / cumdeltaT;
// ene *= (1 - ratio);
// ene += ratio * locEne;
// correctionFactor *= (1 - ratio);
// if (coeffsIndex == 0) {
// correctionFactor += ratio;
// }
// walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
// coeffsIndex = this->coeffsIndex(walk);
// HamAndOvlp(walk, ovlp, locEne, work);
// iter++;
// }
//
// ene *= cumdeltaT;
// correctionFactor *= cumdeltaT;
//
//#ifndef SERIAL
// MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
// MPI_Allreduce(MPI_IN_PLACE, &(ene), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
// MPI_Allreduce(MPI_IN_PLACE, &(correctionFactor), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
//#endif
//
// cumulativeTime = cumdeltaT;
// ene /= cumdeltaT;
// correctionFactor /= cumdeltaT;
// if (commrank == 0) {
// cout << "energy of sampling wavefunction " << setprecision(12) << ene << endl;
// cout << "correctionFactor " << correctionFactor << endl;
// cout << "MRCI+Q energy = ene + (1 - correctionFactor) * (ene - ene0)" << endl;
// if (schd.printVars) cout << endl << "ci coeffs\n" << coeffs << endl;
// }
// }
string getfileName() const {
return "mrci"+wave.getfileName();
}
void writeWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
#endif
}
};
#endif
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef ITF_BLOCK_CONTRACT_H
#define ITF_BLOCK_CONTRACT_H
#include <stddef.h> // for size_t
#include <algorithm>
#include "CxDefs.h"
#include "CxFixedSizeArray.h"
#include "CxMemoryStack.h"
typedef unsigned int
uint;
uint const
// nMaxRank = 8;
nMaxRank = 14;
typedef size_t FArrayOffset;
typedef TArrayFix<FArrayOffset, nMaxRank+1>
FArraySizes;
// note: those things are supposed to be continuous in memory, even if
// they are transposed (i.e., no holes)
struct FNdArrayView
{
FScalar
*pData;
FArraySizes
// strides for each dimension. Might contain an additional element holding
// the total number of values.
Strides,
// sizes in each dimension.
Sizes;
uint Rank() const { assert(Strides.size() >= Sizes.size()); return Sizes.size(); }
inline FArrayOffset nValues(uint iSlot0, uint iSlotsN) const;
inline void SwapSlots(uint iSlot0, uint iSlot1);
inline FArrayOffset nValues() const { return nValues(0, Sizes.size()); }
void ClearData();
// yes, I know.
inline FScalar &operator () (FArrayOffset i)
{ assert(Rank() == 1); return pData[i * Strides[0]]; };
inline FScalar &operator () (FArrayOffset i, FArrayOffset j)
{ assert(Rank() == 2); return pData[i * Strides[0] + j*Strides[1]]; };
inline FScalar &operator () (FArrayOffset i, FArrayOffset j, FArrayOffset k)
{ assert(Rank() == 3); return pData[i * Strides[0] + j*Strides[1] + k*Strides[2]]; };
inline FScalar &operator () (FArrayOffset i, FArrayOffset j, FArrayOffset k, FArrayOffset l)
{ assert(Rank() == 4); return pData[i * Strides[0] + j*Strides[1] + k*Strides[2] + l*Strides[3]]; };
inline FScalar &operator () (FArrayOffset i, FArrayOffset j, FArrayOffset k, FArrayOffset l, FArrayOffset m)
{ assert(Rank() == 5); return pData[i * Strides[0] + j*Strides[1] + k*Strides[2] + l*Strides[3] + m*Strides[4]]; };
inline FScalar &operator () (FArrayOffset i, FArrayOffset j, FArrayOffset k, FArrayOffset l, FArrayOffset m, FArrayOffset n)
{ assert(Rank() == 6); return pData[i * Strides[0] + j*Strides[1] + k*Strides[2] + l*Strides[3] + m*Strides[4] + n*Strides[5]]; };
inline FScalar &operator () (FArrayOffset i, FArrayOffset j, FArrayOffset k, FArrayOffset l, FArrayOffset m, FArrayOffset n, FArrayOffset o)
{ assert(Rank() == 7); return pData[i * Strides[0] + j*Strides[1] + k*Strides[2] + l*Strides[3] + m*Strides[4] + n*Strides[5] + o*Strides[6]]; };
inline FScalar &operator () (FArrayOffset i, FArrayOffset j, FArrayOffset k, FArrayOffset l, FArrayOffset m, FArrayOffset n, FArrayOffset o, FArrayOffset p)
{ assert(Rank() == 8); return pData[i * Strides[0] + j*Strides[1] + k*Strides[2] + l*Strides[3] + m*Strides[4] + n*Strides[5] + o*Strides[6] + p*Strides[7]]; };
};
// perform contraction:
// Dest[AB] += f * \sum_L S[LA] T[LB],
// where L runs over the first nCo slots of S, and of T, and the output is
// ordered as first A, then B.
// This function respects the strides arguments and can thus perform abitrary
// contractions as kernel routine. nCo is implicit: it is (S.Rank() + T.Rank() - Dest.Rank())/2.
void ContractFirst(FNdArrayView D, FNdArrayView S, FNdArrayView T,
FScalar Factor, bool Add, ct::FMemoryStack &Mem);
// do the same as ContractFirst, but explicitly loop over stuff.
void ContractFirst_Naive(FNdArrayView D, FNdArrayView S, FNdArrayView T,
FScalar Factor, bool Add, ct::FMemoryStack &Mem);
// Decl: A string denoting the index associations:
// 'abij,acik,cbkj' means D[abij] = \sum_kc S[acik] T[cbkj].
// Notes:
// - Self-contractions (traces) or contractions involving more than two
// source tensors are not allowed. This is for binary contractions only
// - Index patterns must be sound (each index must occur exactly two times)
// - Spaces in the declaration are not allowed. Apart from ',', '-' and '>',
// all other characters are treated simply as placeholder symbols without
// any particular meaning attached. That is, a pattern like "%.@,:%.->:@"
// is fine.
void ContractBinary(FNdArrayView D, char const *pDecl, FNdArrayView S, FNdArrayView T,
FScalar Factor, bool Add, ct::FMemoryStack &Mem);
void ContractN(FNdArrayView **Ts, char const *pDecl, FScalar Factor, bool Add, ct::FMemoryStack &Mem);
// these here are convenience functions with some runtime overhead.
// They just call the upper ContractN.
void ContractN(FNdArrayView Out, char const *pDecl, FScalar Factor, bool Add, ct::FMemoryStack &Mem,
FNdArrayView const &T1, FNdArrayView const &T2 = FNdArrayView(), FNdArrayView const &T3 = FNdArrayView(), FNdArrayView const &T4 = FNdArrayView(),
FNdArrayView const &T5 = FNdArrayView(), FNdArrayView const &T6 = FNdArrayView(), FNdArrayView const &T7 = FNdArrayView(), FNdArrayView const &T8 = FNdArrayView());
void ContractN(FNdArrayView Out, char const *pDecl, FScalar Factor, bool Add, ct::FMemoryStack &Mem,
FNdArrayView *pT1, FNdArrayView *pT2 = 0, FNdArrayView *pT3 = 0, FNdArrayView *pT4 = 0, FNdArrayView *pT5 = 0,
FNdArrayView *pT6 = 0, FNdArrayView *pT7 = 0, FNdArrayView *pT8 = 0);
void Copy(FNdArrayView &Out, FNdArrayView const &In);
FArrayOffset FNdArrayView::nValues(uint iSlot0, uint iSlotsN) const
{
assert(iSlot0 <= iSlotsN && iSlotsN <= this->Rank());
FArrayOffset r = 1;
for (uint i = iSlot0; i < iSlotsN; ++ i)
r *= Sizes[i];
return r;
};
void FNdArrayView::SwapSlots(uint iSlot0, uint iSlot1)
{
std::swap(this->Strides[iSlot0], this->Strides[iSlot1]);
std::swap(this->Sizes[iSlot0], this->Sizes[iSlot1]);
}
#endif // ITF_BLOCK_CONTRACT_H
<file_sep>#pragma once
#include "tensor.h"
double calcCoulombIntegral(int n1, double Ax, double Ay, double Az,
double expA, double normA,
double expG, double wtG,
int n2, double Bx, double By, double Bz,
double expB, double normB,
tensor& Int);
double calcOvlpMatrix(int LA, double Ax, double Ay, double Az, double expA,
int LB, double Bx, double By, double Bz, double expB,
tensor& S) ;
double calcCoulombIntegralPeriodic(int n1, double Ax, double Ay, double Az,
double expA, double normA,
int n2, double Bx, double By, double Bz,
double expB, double normB,
double Lx, double Ly, double Lz,
tensor& Int, bool IncludeNorm=true);
double calcKineticIntegralPeriodic(int n1, double Ax, double Ay, double Az,
double expA, double normA,
int n2, double Bx, double By, double Bz,
double expB, double normB,
double Lx, double Ly, double Lz,
tensor& Int, bool IncludeNorm=true);
void calcOverlapIntegralPeriodic(int LA, double Ax, double Ay, double Az,
double expA, double normA,
int LB, double Bx, double By, double Bz,
double expB, double normB,
double Lx, double Ly, double Lz,
tensor& Int, bool IncludeNorm=true) ;
void calcShellIntegral_2c(char* Name, double* integrals, int sh1, int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice);
void calcIntegral_2c(char* Name, double* integrals, int* shls, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice);
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "diis.h"
#include <iostream>
#include "global.h"
using namespace Eigen;
using namespace std;
DIIS::DIIS(int pmaxDim, int pvectorDim) : maxDim(pmaxDim), vectorDim(pvectorDim) {
prevVectors = MatrixXd::Zero(pvectorDim, pmaxDim);
errorVectors = MatrixXd::Zero(pvectorDim, pmaxDim);
diisMatrix = MatrixXd::Zero(pmaxDim+1, pmaxDim+1);
iter = 0;
for (int i=0; i<maxDim; i++) {
diisMatrix(i, maxDim) = 1.0;
diisMatrix(maxDim, i) = 1.0;
}
}
void DIIS::init(int pmaxDim, int pvectorDim) {
maxDim = pmaxDim; vectorDim = pvectorDim;
prevVectors = MatrixXd::Zero(pvectorDim, pmaxDim);
errorVectors = MatrixXd::Zero(pvectorDim, pmaxDim);
diisMatrix = MatrixXd::Zero(pmaxDim+1, pmaxDim+1);
iter = 0;
for (int i=0; i<maxDim; i++) {
diisMatrix(i, maxDim) = -1.0;
diisMatrix(maxDim, i) = 1.0;
}
}
void DIIS::update(VectorXd& newV, VectorXd& errorV) {
prevVectors .col(iter%maxDim) = newV;
errorVectors.col(iter%maxDim) = errorV;
int col = iter%maxDim;
for (int i=0; i<maxDim; i++) {
diisMatrix(i , col) = errorV.transpose()*errorVectors.col(i);
diisMatrix(col, i ) = diisMatrix(i, col);
}
iter++;
if (iter < maxDim) {
VectorXd b = VectorXd::Zero(iter+1);
b[iter] = 1.0;
MatrixXd localdiis = diisMatrix.block(0,0,iter+1, iter+1);
for (int i=0; i<iter; i++) {
localdiis(i, iter) = -1.0;
localdiis(iter, i) = 1.0;
}
VectorXd x = localdiis.colPivHouseholderQr().solve(b);
newV = prevVectors.block(0,0,vectorDim,iter)*x.head(iter);
//+ errorVectors.block(0,0,vectorDim,iter)*x.head(iter);
}
else {
VectorXd b = VectorXd::Zero(maxDim+1);
b[maxDim] = 1.0;
VectorXd x = diisMatrix.colPivHouseholderQr().solve(b);
newV = prevVectors*x.head(maxDim);// + errorVectors*x.head(maxDim);
//prevVectors.col((iter-1)%maxDim) = 1.* newV;
}
}
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#include "BlockContract.h"
typedef FArrayOffset
FStride;
template<bool AddToDest, bool UseFactor>
inline void ReorderBaseOpT( FScalar &Out, FScalar &In, FScalar const &DataFactor ) {
if ( AddToDest && UseFactor )
Out += In * DataFactor;
else if ( !AddToDest && UseFactor )
Out = In * DataFactor;
else if ( AddToDest && !UseFactor )
Out += In;
else if ( !AddToDest && !UseFactor )
Out = In;
}
// Out[i,j] <- In[i,j]
template<bool AddToDest, bool UseFactor>
void DirectMove2( FScalar *RESTRICT pOut_, FStride StrideOut,
FScalar *RESTRICT pIn_, FStride StrideIn, FStride nRows, FStride nCols, FScalar const &DataFactor )
{
FScalar
*RESTRICT pIn = pIn_,
*RESTRICT pOut = pOut_;
for ( FStride nCol = 0; nCol < nCols; ++ nCol ){
for ( FStride i = 0; i < (nRows >> 2); ++ i ){
ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor );
ReorderBaseOpT<AddToDest,UseFactor>(pOut[1], pIn[1], DataFactor );
ReorderBaseOpT<AddToDest,UseFactor>(pOut[2], pIn[2], DataFactor );
ReorderBaseOpT<AddToDest,UseFactor>(pOut[3], pIn[3], DataFactor );
pOut += 4; pIn += 4;
}
for ( FStride i = 0; i < (nRows & 3); ++ i ){
ReorderBaseOpT<AddToDest,UseFactor>( pOut[0], pIn[0], DataFactor );
pOut += 1; pIn += 1;
}
pIn += StrideIn - nRows;
pOut += StrideOut - nRows;
}
}
// // Out[i,j] <- In[j,i]
// template<bool AddToDest, bool UseFactor>
// void TransposeMove2( FScalar *RESTRICT pOut_, FStride StrideOut,
// FScalar *RESTRICT pIn_, FStride StrideIn, FStride nRows, FStride nCols, FScalar const &DataFactor )
// {
// FScalar
// *RESTRICT pIn = pIn_,
// *RESTRICT pOut = pOut_;
// FStride
// a = StrideIn, b = a + StrideIn, c = b + StrideIn, d = c + StrideIn;
// for ( FStride nCol = 0; nCol < nCols; ++ nCol ){
// FStride nRow = 0;
// for ( nRow = 0; nRow + 3 < nRows; nRow += 4 ){
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[1], pIn[a], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[2], pIn[b], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[3], pIn[c], DataFactor);
// pOut += 4; pIn += d;
// }
// for ( ; nRow < nRows; ++ nRow ){
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
// pOut += 1; pIn += a;
// }
// pIn += 1 - nRows * a;
// pOut += StrideOut - nRows;
// }
// }
// // Out[i,j] <- In[j,i]
// template<bool AddToDest, bool UseFactor>
// void TransposeMove2( FScalar *RESTRICT pOut_, FStride StrideOut,
// FScalar *RESTRICT pIn_, FStride StrideIn, FStride nRows, FStride nCols, FScalar const &DataFactor )
// {
// FStride
// a = StrideIn, b = a + a, c = b + a, d = c + a;
// FStride const
// nBlk1 = 50;
// for ( FStride nRowStart = 0; nRowStart < nRows; nRowStart += nBlk1 ) {
// FStride
// nRowLen = std::min(nRows - nRowStart, nBlk1);
// FScalar
// *RESTRICT pIn = pIn_ + nRowStart * a,
// *RESTRICT pOut = pOut_ + nRowStart;
//
// for ( FStride nCol = 0; nCol < nCols; ++ nCol ){
// FStride nRow = 0;
// for ( nRow = 0; nRow + 3 < nRowLen; nRow += 4 ){
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[1], pIn[a], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[2], pIn[b], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[3], pIn[c], DataFactor);
// pOut += 4; pIn += d;
// }
// for ( ; nRow < nRowLen; ++ nRow ){
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
// pOut += 1; pIn += a;
// }
// pIn += 1 - nRowLen * a;
// pOut += StrideOut - nRowLen;
// }
// }
// }
// // Out[i,j] <- In[j,i]
// template<bool AddToDest, bool UseFactor>
// void TransposeMove2( FScalar *RESTRICT pOut_, FStride StrideOut,
// FScalar *RESTRICT pIn_, FStride StrideIn, FStride nRows, FStride nCols, FScalar const &DataFactor )
// {
// FStride
// a = StrideIn, b = a + a, c = b + a, d = c + a;
// FStride const
// nBlk1 = 50,
// nBlk2 = nBlk1 * 20;
// for ( FStride nColStart = 0; nColStart < nCols; nColStart += nBlk2 ) {
// FStride
// nColLen = std::min(nCols - nColStart, nBlk2);
// for ( FStride nRowStart = 0; nRowStart < nRows; nRowStart += nBlk1 ) {
// FStride
// nRowLen = std::min(nRows - nRowStart, nBlk1);
// FScalar
// *RESTRICT pIn = pIn_ + nRowStart * a + nColStart,
// *RESTRICT pOut = pOut_ + nRowStart + nColStart * StrideOut;
//
// for ( FStride nCol = 0; nCol < nColLen; ++ nCol ){
// FStride nRow = 0;
// for ( nRow = 0; nRow + 3 < nRowLen; nRow += 4 ){
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[1], pIn[a], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[2], pIn[b], DataFactor);
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[3], pIn[c], DataFactor);
// pOut += 4; pIn += d;
// }
// for ( ; nRow < nRowLen; ++ nRow ){
// ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
// pOut += 1; pIn += a;
// }
// pIn += 1 - nRowLen * a;
// pOut += StrideOut - nRowLen;
// }
// }
// }
// }
template<bool AddToDest, bool UseFactor>
void TransposeMove2x2( FScalar *RESTRICT pOut_, FStride const *pStrideOut,
FScalar *RESTRICT pIn_, FStride const *pStrideIn, FStride nRows, FStride nCols, FScalar const &DataFactor )
{
FStride
a = pStrideIn[0], b = a + a, c = b + a, d = c + a,
u = pStrideOut[0], v = u + u, w = v + u, x = w + u;
FStride const
// blocking over both dimensions because we don't know which
// is the fast one, if any should be.
nBlk1 = 50,
nBlk2 = nBlk1;//20 * nBlk1;
for ( FStride nColStart = 0; nColStart < nCols; nColStart += nBlk2 ) {
FStride
nColLen = std::min(nCols - nColStart, nBlk2);
for ( FStride nRowStart = 0; nRowStart < nRows; nRowStart += nBlk1 ) {
FStride
nRowLen = std::min(nRows - nRowStart, nBlk1),
nIncIn = pStrideIn[1] - nRowLen * a,
nIncOut = pStrideOut[1] - nRowLen * u;
FScalar
*RESTRICT pIn = pIn_ + nRowStart * a + nColStart * pStrideIn[1],
*RESTRICT pOut = pOut_ + nRowStart * u + nColStart * pStrideOut[1];
for ( FStride nCol = 0; nCol < nColLen; ++ nCol ){
FStride nRow = 0;
for ( nRow = 0; nRow + 3 < nRowLen; nRow += 4 ){
ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[u], pIn[a], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[v], pIn[b], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[w], pIn[c], DataFactor);
pOut += x; pIn += d;
}
for ( ; nRow < nRowLen; ++ nRow ){
ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
pOut += u; pIn += a;
}
pIn += nIncIn;
pOut += nIncOut;
}
}
}
}
template<bool AddToDest, bool UseFactor>
static void ReorderData1B( FScalar *RESTRICT pOut, FScalar *RESTRICT pIn,
FStride const *pSize, FStride const *pStrideOut, FStride const *pStrideIn,
FScalar const &DataFactor, uint n )
{
if ( n == 1 ) {
assert( n == 1 );
FStride
nRow = 0,
StrideIn = *pStrideIn,
StrideOut = *pStrideOut;
/* if ( StrideIn * StrideOut == 1 ) {
for ( nRow = 0; nRow + 3 < *pSize; nRow += 4 ){
ReorderBaseOpT<AddToDest,UseFactor>(pOut[0], pIn[0], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[1], pIn[1], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[2], pIn[2], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[3], pIn[3], DataFactor);
pOut += 4; pIn += 4;
}
for ( FStride i = 0; i < *pSize - nRow; ++ i )
ReorderBaseOpT<AddToDest,UseFactor>(pOut[i], pIn[i], DataFactor);
} else {*/
for ( nRow = 0; nRow + 3 < *pSize; nRow += 4 ){
ReorderBaseOpT<AddToDest,UseFactor>(pOut[nRow*StrideOut], pIn[nRow * StrideIn], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[(nRow+1) * StrideOut], pIn[(nRow+1) * StrideIn], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[(nRow+2) * StrideOut], pIn[(nRow+2) * StrideIn], DataFactor);
ReorderBaseOpT<AddToDest,UseFactor>(pOut[(nRow+3) * StrideOut], pIn[(nRow+3) * StrideIn], DataFactor);
}
for ( ; nRow < *pSize; ++ nRow )
ReorderBaseOpT<AddToDest,UseFactor>(pOut[nRow * StrideOut], pIn[nRow * StrideIn], DataFactor);
// }
} else if ( n == 2 ){
if ( *(pStrideOut-1) == 1 && *(pStrideIn-1) == 1 )
return DirectMove2<AddToDest,UseFactor>( pOut, *(pStrideOut),
pIn, *(pStrideIn), *(pSize-1), *(pSize), DataFactor );
else
return TransposeMove2x2<AddToDest,UseFactor>( pOut, pStrideOut-1,
pIn, pStrideIn-1, *(pSize-1), *(pSize), DataFactor );
// TODO: ^- try these again with better compilers or if treating large problem sizes.
// for matrices in the 100..200 dimension the cache blocking simply does not work,
// and we're better of with the smaller code size.
// } else if ( n == 2 && *(pStrideOut-1) == 1 && *(pStrideIn-1) == 1 ){
// return DirectMove2<AddToDest,UseFactor>( pOut, *(pStrideOut),
// pIn, *(pStrideIn), *(pSize-1), *(pSize), DataFactor );
} else {
for ( FStride i = 0; i < *pSize; ++ i )
ReorderData1B<AddToDest,UseFactor>(
pOut + i * (*pStrideOut),
pIn + i * (*pStrideIn),
pSize - 1, pStrideOut - 1, pStrideIn - 1, DataFactor, n - 1 );
}
}
typedef void (*FReorderDataFn)( FScalar *RESTRICT pOut, FScalar *RESTRICT pIn,
FStride const *pSize, FStride const *pStrideOut, FStride const *pStrideIn,
FScalar const &DataFactor, uint n );
#define FN(AddToDest,UseFactor) ReorderData1B<AddToDest,UseFactor>
static FReorderDataFn
s_ReorderDataFns2[2][2] = { {FN(false,false),FN(false,true)}, {FN(true,false),FN(true,true)} };
// s_ReorderDataFns2[2][2] = { {FN(false,true),FN(false,true)}, {FN(true,true),FN(true,true)} };
#undef REORDER_DATA_LINE
#undef FN
void ReorderData1A( FScalar *RESTRICT pOut, FScalar *RESTRICT pIn,
FArraySizes const &StridesOut, FArraySizes const &Sizes, FScalar DataFactor,
bool AddToDest, bool InToOut, FArraySizes const *pStridesIn )
{
assert( StridesOut.size() >= Sizes.size() );
// try to combine continuous dimenions of output array. This is possible
// if iterating over indices n-dim Out(...,i,j,..) is equivalent to iterating
// over (n-1)-dim Out(...,i*j,...).
FArraySizes
StridesIn_,
StridesOut_,
Sizes_;
FStride
nStrideIn = 1;
for ( uint i = 0; i < Sizes.size(); ++ i ){
if ( Sizes[i] != 1 ){
if ( !StridesOut_.empty() && StridesOut[i] == StridesOut_.back() * Sizes_.back() &&
(pStridesIn == 0 || (*pStridesIn)[i] == StridesIn_.back() * Sizes_.back()) ){
// dimension can be combined with last dimension.
Sizes_.back() *= Sizes[i];
} else {
Sizes_.push_back(Sizes[i]);
StridesOut_.push_back(StridesOut[i]);
if ( pStridesIn == 0 )
StridesIn_.push_back(nStrideIn);
else
StridesIn_.push_back((*pStridesIn)[i]);
}
nStrideIn *= Sizes[i];
}
/* Sizes_.push_back(Sizes[i]);
StridesOut_.push_back(StridesOut[i]);
if ( pStridesIn == 0 )
StridesIn_.push_back(nStrideIn);
else
StridesIn_.push_back((*pStridesIn)[i]);
nStrideIn *= Sizes[i];*/
};
uint
n = StridesOut_.size();
if ( n == 0 ) {
// moving a single scalar (0d-array)
if ( AddToDest && InToOut ) { ReorderBaseOpT<true,true>( *pOut, *pIn, DataFactor ); return; }
if ( !AddToDest && InToOut ) { ReorderBaseOpT<false,true>( *pOut, *pIn, DataFactor ); return; }
if ( AddToDest && !InToOut ) { ReorderBaseOpT<true,true>( *pIn, *pOut, DataFactor ); return; }
if ( !AddToDest && !InToOut ) { ReorderBaseOpT<false,true>( *pIn, *pOut, DataFactor ); return; }
return;
}
// if input set has significant size, try to shuffle around the
// strides and sizes to obtain more favorable memory access patterns.
if ( n != 1 && nStrideIn >= 40 ) {
// find fastest dimension in output array (optimally: 1, but might also
// be some larger number). Note that due to the space combination we
// should have at most one of these.
uint iOutLin = 0;
FStride iSmallest = StridesOut_[0];
for ( uint i = 1; i < n; ++ i )
if ( StridesOut_[i] < iSmallest ) {
iSmallest = StridesOut_[i];
iOutLin = i;
}
// unless output dimension is the first one (the most friendly case),
// move it into the second position so that we have a series of interleaved
// matrix transpositions in the two fastest loops.
if ( iOutLin == 0 ) {
// direct sequential move. Input data order probably more or less okay.
} else {
// Transpose1 move.
if ( InToOut ) {
// make fastest loop over pOut linear.
std::swap(StridesIn_[iOutLin],StridesIn_[0]);
std::swap(StridesOut_[iOutLin],StridesOut_[0]);
std::swap(Sizes_[iOutLin],Sizes_[0]);
// make linear pIn loop second-to-fastest.
std::swap(StridesIn_[iOutLin],StridesIn_[1]);
std::swap(StridesOut_[iOutLin],StridesOut_[1]);
std::swap(Sizes_[iOutLin],Sizes_[1]);
} else {
// actual output parameter is pIn. Leave that one linear, but
// move linear pOut strides to second-to-fastest dimension.
std::swap(StridesIn_[iOutLin],StridesIn_[1]);
std::swap(StridesOut_[iOutLin],StridesOut_[1]);
std::swap(Sizes_[iOutLin],Sizes_[1]);
}
};
// try to decrease memory jumping in the remaining dimensions somewhat.
for ( uint i = 2 - ((iOutLin == 0)?1:0); i < Sizes_.size(); ++ i )
for ( uint j = i + 1; j < Sizes_.size(); ++ j )
if ( StridesIn_[j]+StridesOut_[j] < StridesIn_[i]+StridesOut_[i] ){
std::swap(StridesIn_[i],StridesIn_[j]);
std::swap(StridesOut_[i],StridesOut_[j]);
std::swap(Sizes_[i],Sizes_[j]);
}
}
assert( n != 0 );
if ( InToOut )
s_ReorderDataFns2[AddToDest][DataFactor!=1.0]( pOut, pIn, &Sizes_[n-1], &StridesOut_[n-1], &StridesIn_[n-1], DataFactor, n );
else
s_ReorderDataFns2[AddToDest][DataFactor!=1.0]( pIn, pOut, &Sizes_[n-1], &StridesIn_[n-1], &StridesOut_[n-1], DataFactor, n );
}
// kate: space-indent on; tab-indent on; backspace-indent on; tab-width 4; indent-width 4; mixedindent off; indent-mode normal;
<file_sep>#pragma once
#include "tensor.h"
class Coulomb;
void generateCoefficientMatrix(int LA, int LB, double expA, double expB,
double ABx, double p, tensor& Coeff_3d);
void calcCoulombIntegralPeriodic_noTranslations(
int n1, double Ax, double Ay, double Az,
double expA, double normA,
int n2, double Bx, double By, double Bz,
double expB, double normB,
int n3, double Cx, double Cy, double Dz,
double expC, double normC,
double Lx, double Ly, double Lz,
tensor& Int, Coulomb& coulomb,
bool normalize = true);
void calcCoulombIntegralPeriodic_BTranslations(
int n1, double Ax, double Ay, double Az,
double expA, double normA,
int n2, double Bx, double By, double Bz,
double expB, double normB,
int n3, double Cx, double Cy, double Dz,
double expC, double normC,
double Lx, double Ly, double Lz,
tensor& Int, Coulomb& coulomb,
bool normalize = true);
void calcShellIntegral(double* integrals, int sh1, int sh2, int sh3, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice);
void calcIntegral_3c(double* integrals, int* sh1, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice);
void calcShellNuclearIntegral(double* integrals, int sh1, int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice);
void calcNuclearIntegral(double* integrals, int* shls, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice);
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRWavefunction_HEADER_H
#define TRWavefunction_HEADER_H
#include "CorrelatedWavefunction.h"
#include "TRWalker.h"
/**
(1 + TR) | JS >
*/
struct TRWavefunction {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & wave;
}
public:
CorrelatedWavefunction<Jastrow, Slater> wave;
// default constructor
TRWavefunction() {
wave = CorrelatedWavefunction<Jastrow, Slater>();
};
Slater& getRef() { return wave.ref; }
Jastrow& getCorr() { return wave.corr; }
// used at the start of each sampling run
void initWalker(TRWalker &walk)
{
walk = TRWalker(wave.corr, wave.ref);
}
// used in deterministic calculations
void initWalker(TRWalker &walk, Determinant &d)
{
walk = TRWalker(wave.corr, wave.ref, d);
}
// used in rdm calculations
double Overlap(const TRWalker &walk) const
{
return walk.totalOverlap;
}
// used in HamAndOvlp below
double Overlap(const TRWalker &walk, std::array<double, 2> &overlaps) const
{
overlaps[0] = wave.Overlap(walk.walkerPair[0]);
overlaps[1] = wave.Overlap(walk.walkerPair[1]);
return overlaps[0] + overlaps[1];
}
// used in rdm calculations
double getOverlapFactor(int i, int a, const TRWalker& walk, bool doparity) const
{
//array<double, 2> overlaps;
//double totalOverlap = Overlap(walk, overlaps);
double numerator = wave.getOverlapFactor(i, a, walk.walkerPair[0], doparity) * walk.overlaps[0];
int norbs = Determinant::norbs;
if (i%2 == 0) i += 1;
else i -= 1;
if (a%2 == 0) a += 1;
else a -= 1;
numerator += wave.getOverlapFactor(i, a, walk.walkerPair[1], doparity) * walk.overlaps[1];
return numerator / walk.totalOverlap;
}
// used in rdm calculations
double getOverlapFactor(int I, int J, int A, int B, const TRWalker& walk, bool doparity) const
{
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, doparity);
//array<double, 2> overlaps;
//double totalOverlap = Overlap(walk, overlaps);
double numerator = wave.getOverlapFactor(I, J, A, B, walk.walkerPair[0], doparity) * walk.overlaps[0];
int norbs = Determinant::norbs;
if (I%2 == 0) I += 1;
else I -= 1;
if (A%2 == 0) A += 1;
else A -= 1;
if (J%2 == 0) J += 1;
else J -= 1;
if (B%2 == 0) B += 1;
else B -= 1;
numerator += wave.getOverlapFactor(I, J, A, B, walk.walkerPair[1], doparity) * walk.overlaps[1];
return numerator / walk.totalOverlap;
}
double getOverlapFactor(int i, int a, const TRWalker& walk, std::array<double, 2>& overlaps, double& totalOverlap, bool doparity) const
{
double numerator = wave.getOverlapFactor(i, a, walk.walkerPair[0], doparity) * overlaps[0];
int norbs = Determinant::norbs;
if (i%2 == 0) i += 1;
else i -= 1;
if (a%2 == 0) a += 1;
else a -= 1;
numerator += wave.getOverlapFactor(i, a, walk.walkerPair[1], doparity) * overlaps[1];
return numerator / totalOverlap;
}
// used in HamAndOvlp below
double getOverlapFactor(int I, int J, int A, int B, const TRWalker& walk, std::array<double, 2>& overlaps, double& totalOverlap, bool doparity) const
{
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, overlaps, totalOverlap, doparity);
double numerator = wave.getOverlapFactor(I, J, A, B, walk.walkerPair[0], doparity) * overlaps[0];
int norbs = Determinant::norbs;
if (I%2 == 0) I += 1;
else I -= 1;
if (A%2 == 0) A += 1;
else A -= 1;
if (J%2 == 0) J += 1;
else J -= 1;
if (B%2 == 0) B += 1;
else B -= 1;
numerator += wave.getOverlapFactor(I, J, A, B, walk.walkerPair[1], doparity) * overlaps[1];
return numerator / totalOverlap;
}
// gradient overlap ratio, used during sampling
// just calls OverlapWithGradient on the last wave function
void OverlapWithGradient(const TRWalker &walk,
double &factor,
Eigen::VectorXd &grad) const
{
//array<double, 2> overlaps;
//double totalOverlap = Overlap(walk, overlaps);
size_t index = 0;
VectorXd grad_0 = 0. * grad, grad_1 = 0. * grad;
wave.OverlapWithGradient(walk.walkerPair[0], factor, grad_0);
wave.OverlapWithGradient(walk.walkerPair[1], factor, grad_1);
grad = (grad_0 * walk.overlaps[0] + grad_1 * walk.overlaps[1]) / walk.totalOverlap;
}
void printVariables() const
{
wave.printVariables();
}
// update after vmc optimization
// updates the wave function helpers as well
void updateVariables(Eigen::VectorXd &v)
{
wave.updateVariables(v);
}
void getVariables(Eigen::VectorXd &v) const
{
wave.getVariables(v);
}
long getNumVariables() const
{
return wave.getNumVariables();
}
string getfileName() const {
return "TRWavefunction";
}
void writeWave() const
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
//if (commrank == 0)
//{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
//}
#ifndef SERIAL
//boost::mpi::communicator world;
//boost::mpi::broadcast(world, *this, 0);
#endif
}
// calculates local energy and overlap
// used directly during sampling
void HamAndOvlp(const TRWalker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true) const
{
int norbs = Determinant::norbs;
//array<double, 2> overlaps;
//ovlp = Overlap(walk, overlaps);
ovlp = Overlap(walk);
if (schd.debug) {
cout << "overlaps\n";
for (int i = 0; i < walk.overlaps.size(); i++) cout << walk.overlaps[i] << " ";
cout << endl;
}
ham = walk.walkerPair[0].d.Energy(I1, I2, coreE);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.walkerPair[0].d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.walkerPair[0].d, schd.epsilon, schd.screen,
work, false);
//loop over all the screened excitations
if (schd.debug) {
cout << "eloc excitations" << endl;
cout << "phi0 d.energy " << ham << endl;
}
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, overlaps, ovlp, false);
double ovlpRatio = getOverlapFactor(I, J, A, B, walk, false);
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, dbig, dbigcopy, false);
ham += tia * ovlpRatio;
if (schd.debug) cout << ex1 << " " << ex2 << " tia " << tia << " ovlpRatio " << ovlpRatio << endl;
work.ovlpRatio[i] = ovlpRatio;
}
if (schd.debug) cout << endl;
}
};
#endif
<file_sep>#ifndef EvalVar_HEADER_H
#define EvalVar_HEADER_H
#include <vector>
#include <Eigen/Dense>
#include "Wfn.h"
#include <algorithm>
#include "integral.h"
#include "Determinants.h"
#include "Walker.h"
#include <boost/format.hpp>
#include <iostream>
#include "evaluateE.h"
#include "Davidson.h"
#include "Hmult.h"
#include <math.h>
#include "global.h"
#include "input.h"
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace std;
using namespace Eigen;
void getStochasticVarianceGradientContinuousTime(CPSSlater &w, double &E0, double &stddev,
int &nalpha, int &nbeta, int &norbs, oneInt &I1,
twoInt &I2, twoIntHeatBathSHM &I2hb, double &coreE,
Eigen::VectorXd &grad, double &var, double &rk,
int niter, double targetError);
#endif
<file_sep>/* Copyright (c) 2012-2020 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ir/wmme (LICENSE). If not, see http://www.gnu.org/licenses/
*/
#ifndef CX_DEFS_H
#define CX_DEFS_H
#define IR_NO_THROW throw()
#define CX_NO_THROW IR_NO_THROW
#define AIC_NO_THROW IR_NO_THROW
// Define macros for restricted pointer extensions. By defining a pointer as
// ``restricted'', we promise the compiler that the pointer is not aliased in
// the current scope. E.g., that in constructs like
//
// void fn(double *RESTRICT pOut, double const *RESTRICT pIn) {
// pOut[0] = pIn[0];
// pOut[1] = pIn[1];
// },
//
// the two assignments can be scheduled out of order, because pOut[x] and pIn[x]
// can not possibly point to the same memory location.
//
// Note:
// - RESTRICT now univerally goes behind the star ("double *RESTRICT p;").
// That is, the *pointer* is restricted, not the data it points to.
// (in olden tymes this was handled differently in different compilers.)
#ifdef __GNUC__ // g++ or anything which pretends to be g++ (e.g., clang, intel c++ on linux)
#define IR_RP __restrict__
#elif defined(_MSC_VER) // microsoft c++, or anything which pretends to be msvc (e.g., intel c++ on windows)
#define IR_RP __restrict
#elif (defined __SUNPRO_CC || defined __SUNPRO_C) // sun studio/solaris studio
#define RESTRICT __restrict
#elif defined(__INTEL_COMPILER)
// compile with -restrict command line option (linux) or -Qrestrict (windows).
#define IR_RP restrict
#else
#define IR_RP
#endif
#ifndef RESTRICT
#define RESTRICT IR_RP
#endif
// In some cases we need to inline driver functions as a prerequisite
// for inlining virtual functions. If the driver functions are large,
// compilers might be inclined to ignore our ``inline'' directive.
// Set up some macros to tell them that we really mean it.
#ifdef __GNUC__ // g++
#define IR_FORCE_INLINE inline __attribute__((always_inline))
#elif defined(_MSC_VER)
#define IR_FORCE_INLINE __forceinline
#else
#define IR_FORCE_INLINE inline
#endif
// some other assorted defines...
#if (defined __GNUC__ || defined __INTEL_COMPILER)
// tell the compiler that this function will never return
#define DECL_NORETURN __attribute__((noreturn))
// 'insert software breakpoint here'.
#define DEBUG_BREAK __asm__("int $0x03");
#elif defined(_MSC_VER) && !defined(__PGI) // microsoft c++ (other win32 compilers might emulate this syntax)
#define DECL_NORETURN __declspec(noreturn)
//#define RESTRICT __declspec(restrict)
#define DEBUG_BREAK __asm{ int 3 };
#elif (defined __SUNPRO_CC || defined __SUNPRO_C) // sun studio/solaris studio
#define DECL_NORETURN __attribute((noreturn))
#define DEBUG_BREAK __asm__("int $3");
#else
#define DECL_NORETURN
#define DEBUG_BREAK
#endif
// data prefetch for reading and writing.
#ifdef __GNUC__
#define IR_PREFETCH_R(p) __builtin_prefetch(p, 0, 1)
#define IR_PREFETCH_W(p) __builtin_prefetch(p, 1, 1)
#elif defined(_MSC_VER)
#include <xmmintrin.h>
#define IR_PREFETCH_R(p) _mm_prefetch((char*)p, 1)
#define IR_PREFETCH_W(p) _mm_prefetch((char*)p, 1)
#else
#define IR_PREFETCH_R(p) static_cast<void>(0)
#define IR_PREFETCH_W(p) static_cast<void>(0)
#endif
// Adjust NDEBUG macro to _DEBUG macro (i.e., enable NDEBUG unless _DEBUG is set,
// and vice versa). _DEBUG is our custom "enable debug stuff" macro.
// Note:
// - in the standard C world, NDEBUG only relates to assertions, and _DEBUG
// (the VC standard) is unknown. I here decided to use _DEBUG as main debug
// flag, and to adjust NDEBUG accordingly (in case someone re-includes
// <assert.h>).
#if (defined(_DEBUG) && defined(NDEBUG))
#undef NDEBUG
#endif
#if (!defined(_DEBUG) && !defined(NDEBUG))
#define NDEBUG
#endif
// ask the compiler to not warn about a given symbol if it is not actually used
// (for example, because this is only a partial IR core and the symbol is used
// in some code not supplied with the partial version)
#define IR_SUPPRESS_UNUSED_WARNING(x) (void)x
#define IR_SUPPRESS_UNUSED_WARNING2(x,y) {(void)x; (void)y;}
#define IR_SUPPRESS_UNUSED_WARNING3(x,y,z) {(void)x; (void)y; (void)z;}
#define IR_SUPPRESS_UNUSED_WARNING4(x,y,z,w) {(void)x; (void)y; (void)z; (void)w;}
// re-define assert(). The main reason for doing this is that the standard
// version has a habit of hard-crashing MPI executables (e.g., Molpro), in a way
// which makes it impossible to debug them. Additionally, in some compilers
// assert()s do *not* go away, even if you do set NDEBUG.
//
// (And one can put in a debug_break into the assert fail function, which helps
// a lot if using a visual debugger like VC)
#ifdef assert
#undef assert
#endif
#ifdef assert_rt
#undef assert_rt
#endif
void CxAssertFail(char const *pExpr, char const *pFile, int iLine);
#define assert_rt(x) ((x)? static_cast<void>(0) : CxAssertFail(#x,__FILE__,__LINE__))
#ifdef _DEBUG
#define assert(x) assert_rt(x)
#else
#define assert(x) static_cast<void>(0)
#endif
#if (defined __GNUC__ && defined __linux__ && defined(_DEBUG))
// to allow putting "mcheck_check_all();" (glibc's explicit heap consistency check) anywhere.
#include <mcheck.h>
#endif
#endif // CX_DEFS_H
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef EOM_HEADER_H
#define EOM_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/array.hpp>
#include <utility>
#include <iomanip>
#include "CorrelatedWavefunction.h"
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace std;
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
template<typename Corr, typename Reference>
class EOM
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & wave
& coeffs;
}
public:
using CorrType = Corr;
using ReferenceType = Reference;
VectorXd coeffs;
CorrelatedWavefunction<Corr, Reference> wave; //reference wavefunction
EOM()
{
//wave = CorrelatedWavefunction<Corr, Reference>();
wave.readWave();
//cout << "JS vars\n"; wave.printVariables();
// Resize coeffs
int norbs = Determinant::norbs;
int numCoeffs = 1 + 2 * norbs * norbs;
//these are arranged like this: ref, up single excitations, down single excitations
coeffs = VectorXd::Zero(numCoeffs); //for the sampling wave
//coeffs order: phi0, singly excited (spin orb index), doubly excited (spin orb pair index)
if (commrank == 0) {
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
coeffs(0) = -0.5;
//coeffs(1) = -0.5;
for (int i=1; i < numCoeffs; i++) {
coeffs(i) = 0.05*random();
}
}
#ifndef SERIAL
MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
char file[5000];
sprintf(file, "eom.txt");
ifstream ofile(file);
if (ofile) {
for (int i = 0; i < coeffs.size(); i++) {
ofile >> coeffs(i);
}
}
//cout << "ciCoeffs\n" << coeffs << endl;
}
Reference& getRef() { return wave.getRef(); }
Corr& getCorr() { return wave.getCorr(); }
void initWalker(Walker<Corr, Reference> &walk)
{
walk = Walker<Corr, Reference>(wave.corr, wave.ref);
}
void initWalker(Walker<Corr, Reference> &walk, Determinant &d)
{
walk = Walker<Corr, Reference>(wave.corr, wave.ref, d);
}
void getVariables(VectorXd& vars) {
vars = coeffs;
}
void printVariables() {
cout << "eom coeffs\n" << coeffs << endl;
}
void updateVariables(VectorXd& vars) {
coeffs = vars;
}
long getNumVariables() {
return coeffs.size();
}
double getOverlapFactor(int i, int a, const Walker<Corr, Reference>& walk, bool doparity) const
{
return 1.;
}//not used
double getOverlapFactor(int I, int J, int A, int B, const Walker<Corr, Reference>& walk, bool doparity) const
{
return 1.;
}//not used
//updates from and to by combining with excitation ex
//used for m -> m'
void combineExcitations(int ex, std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to)
{
int norbs = Determinant::norbs;
int I = ex / (2 * norbs), A = ex % (2 * norbs);
int i = I / 2, a = A / 2;
bool sz = I%2;
auto itOrbsi = to[sz].find(i);
auto itHolesa = from[sz].find(a);
if (itOrbsi == to[sz].end()) from[sz].insert(i);
else to[sz].erase(itOrbsi);
if (itHolesa == from[sz].end()) to[sz].insert(a);
else from[sz].erase(itHolesa);
}
//generates excitations from the walker due to the eom operators (n -> n')
//and calculates the ovlpRatios for these excitations
//returns squareRatio | < n | psi_0 > / < n | psi_s > |^2
double ovlpRatio(Walker<Corr, Reference>& n, VectorXd& ovlpRation, double &ovlpR) {
int norbs = Determinant::norbs;
ovlpR = 0.;
ovlpRation(0) = 1.;
ovlpR += coeffs(0);
for (int sz = 0; sz < 2; sz++) {
for (int p = 0; p < norbs; p++) {
//q = p
int index = 1 + (sz * norbs * norbs) + (p * norbs) + p;
if (n.d.getocc(p, sz)) ovlpRation(index) = 1.;
ovlpR += coeffs(index);
for (int q = 0; q < p; q++) {
index = 1 + (sz * norbs * norbs) + (p * norbs) + q;
if (n.d.getocc(p, sz) && (!n.d.getocc(q, sz))) ovlpRation(index) = wave.getOverlapFactor(2*p + sz, 2*q + sz, n, false);
ovlpR += coeffs(index) * ovlpRation(index);
}
for (int q = p+1; q < norbs; q++) {
index = 1 + (sz * norbs * norbs) + (p * norbs) + q;
if (n.d.getocc(p, sz) && (!n.d.getocc(q, sz))) ovlpRation(index) = wave.getOverlapFactor(2*p + sz, 2*q + sz, n, false);
ovlpR += coeffs(index) * ovlpRation(index);
}
}
}
return 1 / ovlpR / ovlpR;
}
//generates excitations from the determinant due to the eom operators (m -> m')
//and calculates ovlpRatios for n -> m' excitations
//returns < m | psi_s > / < n | psi_0 >
double ovlpRatio(Walker<Corr, Reference>& n, Determinant m, std::array<unordered_set<int>, 2> &from, std::array<unordered_set<int>, 2> &to, VectorXd& ovlpRatiom) {
int norbs = Determinant::norbs;
double ratio = 0.;
ovlpRatiom(0) = wave.getOverlapFactor(n, from, to);
ratio += coeffs(0) * ovlpRatiom(0);
for (int sz = 0; sz < 2; sz++) {
for (int p = 0; p < norbs; p++) {
int index = 1 + sz * norbs * norbs + p * norbs + p;
if (m.getocc(p, sz)) ovlpRatiom(index) = wave.getOverlapFactor(n, from, to);
ratio += coeffs(index) * ovlpRatiom(index);
for (int q = 0; q < p; q++) {
index = 1 + sz * norbs * norbs + p * norbs + q;
auto fromNew = from;
auto toNew = to;
combineExcitations((2*p +sz) * 2*norbs + (2*q + sz), fromNew, toNew);
if (m.getocc(p, sz) && !m.getocc(q, sz)) ovlpRatiom(index) = m.parity(q, p, sz) * wave.getOverlapFactor(n, fromNew, toNew);
ratio += coeffs(index) * ovlpRatiom(index);
}
for (int q = p+1; q < norbs; q++) {
index = 1 + sz * norbs * norbs + p * norbs + q;
auto fromNew = from;
auto toNew = to;
combineExcitations((2*p +sz) * 2*norbs + (2*q + sz), fromNew, toNew);
if (m.getocc(p, sz) && !m.getocc(q, sz)) ovlpRatiom(index) = m.parity(q, p, sz) * wave.getOverlapFactor(n, fromNew, toNew);
ratio += coeffs(index) * ovlpRatiom(index);
}
}
}
return ratio;
}
void HamAndOvlp(Walker<Corr, Reference> &n,
double &ovlp, MatrixXd &hamSample, MatrixXd &ovlpSample,
workingArray& work)
{
//cout << "\nin HamAndOvlp\n";
int norbs = Determinant::norbs;
double dEne = n.d.Energy(I1, I2, coreE);
double ovlpR = 0.; // < n | psi_s > / < n | psi_0 >
VectorXd ovlpRation = VectorXd::Zero(coeffs.size()); // < n | pq > / < n | psi_0 >
VectorXd hamVec = VectorXd::Zero(coeffs.size()); // < n | H | pq > / < n | psi_0 >
double sampleRatioSquare = ovlpRatio(n, ovlpRation, ovlpR); // | < n | psi_0 > / < n | psi_s > |^2
ovlpSample = sampleRatioSquare * ovlpRation * ovlpRation.transpose();
double ovlp0 = wave.Overlap(n); // < n | psi_0 >
//ovlpSample = ovlpRation * ovlpRation.transpose() * ovlp0 * ovlp0;
ovlp = ovlpR * ovlp0; // < n | psi_s >
//cout << "ovlp0 " << ovlp0 << " ovlps " << ovlp << endl << endl;
//cout << "ovlpRation\n" << ovlpRation << endl << endl;
hamVec += dEne * ovlpRation;
work.setCounterToZero();
generateAllScreenedSingleExcitation(n.d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(n.d, schd.epsilon, schd.screen,
work, false);
//loop over all the screened excitations
//cout << "\ngenerating m's\n\n";
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double parity = 1.;//ham element parity
//cout << "ex1 " << ex1 << " ex2 " << ex2 << endl;
std::array<unordered_set<int> , 2> from, to;
from[0].clear(); to[0].clear();
from[1].clear(); to[1].clear();
from[I%2].insert(I/2);
to[A%2].insert(A/2);
//cout << endl << "from u ";
//copy(from[0].begin(), from[0].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "from d ";
//copy(from[1].begin(), from[1].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "to u ";
//copy(to[0].begin(), to[0].end(), ostream_iterator<int>(cout, " "));
//cout << endl << "to d ";
//copy(to[1].begin(), to[1].end(), ostream_iterator<int>(cout, " "));
//cout << endl;
Determinant m = n.d;
parity *= m.parity(A/2, I/2, I%2);
//if (ex2 == 0) {
// mEne = dEne + n.energyIntermediates[A%2][A/2] - n.energyIntermediates[I%2][I/2]
// - (I2.Direct(I/2, A/2) - I2.Exchange(I/2, A/2));
//}
//else {
m.setocc(I, false);
m.setocc(A, true);
if (ex2 != 0) {
from[J%2].insert(J/2);
to[B%2].insert(B/2);
parity *= m.parity(B/2, J/2, J%2);
m.setocc(J, false);
m.setocc(B, true);
//bool sameSpin = (I%2 == J%2);
//mEne = dEne + n.energyIntermediates[A%2][A/2] - n.energyIntermediates[I%2][I/2]
// + n.energyIntermediates[B%2][B/2] - n.energyIntermediates[J%2][J/2]
// + I2.Direct(A/2, B/2) - sameSpin * I2.Exchange(A/2, B/2)
// + I2.Direct(I/2, J/2) - sameSpin * I2.Exchange(I/2, J/2)
// - (I2.Direct(I/2, A/2) - I2.Exchange(I/2, A/2))
// - (I2.Direct(J/2, B/2) - I2.Exchange(J/2, B/2))
// - (I2.Direct(I/2, B/2) - sameSpin * I2.Exchange(I/2, B/2))
// - (I2.Direct(J/2, A/2) - sameSpin * I2.Exchange(J/2, A/2));
}
//cout << "m " << m << endl;
VectorXd ovlpRatiom = VectorXd::Zero(coeffs.size()); // < m | pq > / < n | psi_0 >
double ratiom = ovlpRatio(n, m, from, to, ovlpRatiom); // < m | psi_s > / < n | psi_0 >
hamVec += parity * tia * ovlpRatiom;
work.ovlpRatio[i] = ratiom * ovlp0 / ovlp; // < m | psi_s> / < n | psi_s >
//ham += tia * ovlpRatiom;
//cout << "hamSample " << tia * ovlpRatiom << endl;
//cout << "ovlpRatiom(0) " << ovlpRatiom(0) << " tia " << tia << " parity " << parity << endl << endl;
}
//cout << "hamVec\n" << hamVec << endl << endl;
hamSample = sampleRatioSquare * ovlpRation * hamVec.transpose();
}
double optimizeWaveDeterministic(Walker<Corr, Reference>& walk) {
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
workingArray work;
double overlapTot = 0.;
MatrixXd hamSample = VectorXd::Zero(coeffs.size());
MatrixXd ovlpSample = VectorXd::Zero(coeffs.size());
MatrixXd ciHam = MatrixXd::Zero(coeffs.size(), coeffs.size());
MatrixXd sMat = MatrixXd::Zero(coeffs.size(), coeffs.size());// + 1.e-6 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//w.printVariables();
for (int i = commrank; i < allDets.size(); i += commsize) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
double ovlp = 0.;
HamAndOvlp(walk, ovlp, hamSample, ovlpSample, work);
//cout << "ham " << ham[0] << " " << ham[1] << " " << ham[2] << endl;
//cout << "ovlp " << ovlp[0] << " " << ovlp[1] << " " << ovlp[2] << endl << endl;
overlapTot += ovlp * ovlp;
ciHam += (ovlp * ovlp) * hamSample;
sMat += (ovlp * ovlp) * ovlpSample;
//sMat += ovlpSample;
hamSample.setZero();
ovlpSample.setZero();
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ciHam.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, sMat.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
double ene0 = 0.;
if (commrank == 0) {
ciHam = ciHam / overlapTot;
sMat = sMat / overlapTot;
ene0 = ciHam(0, 0) / sMat(0,0);
//sMat += 1.e-8 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//cout << "ciHam\n" << ciHam << endl << endl;
//cout << "sMat\n" << sMat << endl << endl;
//GeneralizedEigenSolver<MatrixXd> diag(ciHam, sMat);
//VectorXd::Index minInd;
//double minEne = diag.eigenvalues().real().minCoeff(&minInd);
//coeffs = diag.eigenvectors().col(minInd).real();
cout << "ref energy " << fixed << setprecision(5) << ene0 << endl;
MatrixXd projSMat = sMat.block(1,1,coeffs.size()-1, coeffs.size()-1) - sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
MatrixXd projHam = ciHam.block(1,1,coeffs.size()-1, coeffs.size()-1)- ciHam.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1)
- sMat.block(1,0,coeffs.size()-1,1) * ciHam.block(0,1,1,coeffs.size()-1)
+ ene0 * sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
GeneralizedEigenSolver<MatrixXd> diag(projHam, projSMat);
cout << "eigenvalues\n" << diag.eigenvalues() << endl;
//cout << "eigenvalues\n" << diag.eigenvalues() << endl;
//cout << "ciHam\n" << ciHam << endl;
//cout << "sMat\n" << sMat << endl;
//cout << "coeffs\n" << coeffs << endl;
//EigenSolver<MatrixXd> ovlpDiag(sMat);
//VectorXd norms = ovlpDiag.eigenvalues().real();
//std::vector<int> largeNormIndices;
//for (int i = 0; i < coeffs.size(); i++) {
// if (norms(i) > 1.e-5) {
// largeNormIndices.push_back(i);
// }
//}
//Map<VectorXi> largeNormSlice(&largeNormIndices[0], largeNormIndices.size());
//VectorXd largeNorms;
//igl::slice(norms, largeNormSlice, largeNorms);
//cout << "largeNorms size " << largeNorms.size() << endl;
//DiagonalMatrix<double, Dynamic> largeNormInv;
//largeNormInv.resize(largeNorms.size());
//largeNormInv.diagonal() = largeNorms.cwiseSqrt().cwiseInverse();
////largeNormInv.diagonal() = largeNorms.cwiseInverse();
//MatrixXd largeBasis;
//igl::slice(ovlpDiag.eigenvectors().real(), VectorXi::LinSpaced(coeffs.size(), 0, coeffs.size()-1), largeNormSlice, largeBasis);
//MatrixXd basisChange = largeBasis * largeNormInv;
//MatrixXd largeHam = basisChange.transpose() * ciHam * basisChange;
//EigenSolver<MatrixXd> hamDiag(largeHam);
//cout << "eigenvalues\n" << hamDiag.eigenvalues().real() << endl;
}
#ifndef SERIAL
MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
//MPI_Bcast(&(ene0), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
double calcPolDeterministic(Walker<Corr, Reference>& walk) {
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
workingArray work;
double overlapTot = 0.;
MatrixXd hamSample = VectorXd::Zero(coeffs.size());
MatrixXd ovlpSample = VectorXd::Zero(coeffs.size());
MatrixXd ciHam = MatrixXd::Zero(coeffs.size(), coeffs.size());
MatrixXd sMat = MatrixXd::Zero(coeffs.size(), coeffs.size());// + 1.e-6 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//w.printVariables();
for (int i = commrank; i < allDets.size(); i += commsize) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
double ovlp = 0.;
HamAndOvlp(walk, ovlp, hamSample, ovlpSample, work);
//cout << "ham " << ham[0] << " " << ham[1] << " " << ham[2] << endl;
//cout << "ovlp " << ovlp[0] << " " << ovlp[1] << " " << ovlp[2] << endl << endl;
overlapTot += ovlp * ovlp;
ciHam += (ovlp * ovlp) * hamSample;
sMat += (ovlp * ovlp) * ovlpSample;
//sMat += ovlpSample;
hamSample.setZero();
ovlpSample.setZero();
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ciHam.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, sMat.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
double ene0 = 0.;
if (commrank == 0) {
ciHam = ciHam / overlapTot;
sMat = sMat / overlapTot;
ene0 = ciHam(0, 0) / sMat(0,0);
sMat += 1.e-8 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//cout << "ciHam\n" << ciHam << endl << endl;
//cout << "sMat\n" << sMat << endl << endl;
//GeneralizedEigenSolver<MatrixXd> diag(ciHam, sMat);
//VectorXd::Index minInd;
//double minEne = diag.eigenvalues().real().minCoeff(&minInd);
//coeffs = diag.eigenvectors().col(minInd).real();
cout << "ref energy " << fixed << setprecision(5) << ene0 << endl;
MatrixXd projSMat = sMat.block(1,1,coeffs.size()-1, coeffs.size()-1) - sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
MatrixXd projHam = ciHam.block(1,1,coeffs.size()-1, coeffs.size()-1)- ciHam.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1)
- sMat.block(1,0,coeffs.size()-1,1) * ciHam.block(0,1,1,coeffs.size()-1)
+ ene0 * sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
//cout << "eigenvalues\n" << diag.eigenvalues() << endl;
//cout << "ciHam\n" << ciHam << endl;
//cout << "sMat\n" << sMat << endl;
//cout << "coeffs\n" << coeffs << endl;
//EigenSolver<MatrixXd> ovlpDiag(sMat);
//VectorXd norms = ovlpDiag.eigenvalues().real();
//std::vector<int> largeNormIndices;
//for (int i = 0; i < coeffs.size(); i++) {
// if (norms(i) > 1.e-5) {
// largeNormIndices.push_back(i);
// }
//}
//Map<VectorXi> largeNormSlice(&largeNormIndices[0], largeNormIndices.size());
//VectorXd largeNorms;
//igl::slice(norms, largeNormSlice, largeNorms);
//cout << "largeNorms size " << largeNorms.size() << endl;
//DiagonalMatrix<double, Dynamic> largeNormInv;
//largeNormInv.resize(largeNorms.size());
//largeNormInv.diagonal() = largeNorms.cwiseSqrt().cwiseInverse();
////largeNormInv.diagonal() = largeNorms.cwiseInverse();
//MatrixXd largeBasis;
//igl::slice(ovlpDiag.eigenvectors().real(), VectorXi::LinSpaced(coeffs.size(), 0, coeffs.size()-1), largeNormSlice, largeBasis);
//MatrixXd basisChange = largeBasis * largeNormInv;
//MatrixXd largeHam = basisChange.transpose() * ciHam * basisChange;
//VectorXcd stateOnTheSide = basisChange.transpose() * sMat.col(1);
//for (int i = 0; i < 100; i++) {
// complex<double> w (-0.5 + 0.005 * i, 0.001);
// MatrixXcd aMat = (w - ene0) * MatrixXcd::Identity(largeNorms.size(), largeNorms.size()) + largeHam;
// Eigen::ColPivHouseholderQR<Eigen::MatrixXcd> lin(aMat);
// VectorXcd corr = lin.solve(stateOnTheSide);
// cout << w << " " << (stateOnTheSide.adjoint() * corr).imag() << endl;
//}
VectorXcd stateOnTheSide = VectorXcd::Zero(coeffs.size() - 1);
stateOnTheSide.real() = projSMat.col(0);
for (int i = 0; i < 100; i++) {
complex<double> w (-0.5 + 0.005 * i, 0.001);
MatrixXcd aMat = (w - ene0) * projSMat + projHam;
//Eigen::ColPivHouseholderQR<Eigen::MatrixXcd> lin(aMat);
//Eigen::ConjugateGradient<Eigen::MatrixXcd> lin(aMat);
Eigen::BiCGSTAB<Eigen::MatrixXcd> lin(aMat);
VectorXcd corr = lin.solve(stateOnTheSide);
cout << w << " " << (stateOnTheSide.adjoint() * corr).imag() << endl;
}
}
}
void generalizedJacobiDavidson(const Eigen::MatrixXd &H, const Eigen::MatrixXd &S, double &lambda, Eigen::VectorXd &v)
{
int dim = H.rows(); //dimension of problem
int restart = std::max((int) (0.1 * dim), 30); //20 - 30
int q = std::max((int) (0.04 * dim), 5); //5 - 10
Eigen::MatrixXd V, HV, SV; //matrices storing action of vector on sample space
//Eigen::VectorXd z = Eigen::VectorXd::Random(dim);
//Eigen::VectorXd z = Eigen::VectorXd::Unit(dim, 0);
Eigen::VectorXd z = Eigen::VectorXd::Constant(dim, 0.01);
while (1)
{
int m = V.cols(); //number of vectors in subspace at current iteration
//modified grahm schmidt to orthogonalize sample space with respect to overlap matrix
Eigen::VectorXd Sz = S * z;
for (int i = 0; i < m; i++)
{
double alpha = V.col(i).adjoint() * Sz;
z = z - alpha * V.col(i);
}
//normalize z after orthogonalization and calculate action of matrices on z
Sz = S * z;
double beta = std::sqrt(z.adjoint() * Sz);
Eigen::VectorXd v_m = z / beta;
Eigen::VectorXd Hv_m = H * v_m;
Eigen::VectorXd Sv_m = S * v_m;
//store new vector
V.conservativeResize(H.rows(), m + 1);
HV.conservativeResize(H.rows(), m + 1);
SV.conservativeResize(H.rows(), m + 1);
V.col(m) = v_m;
HV.col(m) = Hv_m;
SV.col(m) = Sv_m;
//solve eigenproblem in subspace
Eigen::MatrixXd A = V.adjoint() * HV;
Eigen::MatrixXd B = V.adjoint() * SV;
Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(A, B);
//if sample space size is too large, restart subspace
if (m == restart)
{
Eigen::MatrixXd N = es.eigenvectors().block(0, 0, A.rows(), q);
V = V * N;
HV = HV * N;
SV = SV * N;
A = V.adjoint() * HV;
B = V.adjoint() * SV;
es.compute(A, B);
}
Eigen::VectorXd s = es.eigenvectors().col(0);
double theta = es.eigenvalues()(0);
//cout << "theta: " << theta << endl;
//transform vector into original space
Eigen::VectorXd u = V * s;
//calculate residue vector
Eigen::VectorXd u_H = HV * s;
Eigen::VectorXd u_S = SV * s;
Eigen::VectorXd r = u_H - theta * u_S;
if (r.squaredNorm() < 1.e-6)
{
lambda = theta;
v = u;
break;
}
Eigen::MatrixXd X = Eigen::MatrixXd::Identity(u.rows(), u.rows());
Eigen::MatrixXd Xleft = X - S * u * u.adjoint();
Eigen::MatrixXd Xright = X - u * u.adjoint() * S;
X = Xleft * (H - theta * S) * Xright;
Eigen::ColPivHouseholderQR<Eigen::MatrixXd> dec(X);
z = dec.solve(-r);
}
}
void optimizeWaveCT(Walker<Corr, Reference>& walk) {
//add noise to avoid zero coeffs
// if (commrank == 0) {
// cout << "starting sampling at " << setprecision(4) << getTime() - startofCalc << endl;
// auto random = std::bind(std::uniform_real_distribution<double>(0., 1.e-8), std::ref(generator));
// for (int i=0; i < coeffs.size(); i++) {
// if (coeffs(i) == 0) coeffs(i) = random();
// }
// }
//
//#ifndef SERIAL
// MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
//#endif
//sampling
int norbs = Determinant::norbs;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
workingArray work;
double ovlp = 0.;
MatrixXd hamSample = VectorXd::Zero(coeffs.size());
MatrixXd ovlpSample = VectorXd::Zero(coeffs.size());
MatrixXd ciHam = MatrixXd::Zero(coeffs.size(), coeffs.size());
MatrixXd sMat = MatrixXd::Zero(coeffs.size(), coeffs.size());
//cout << "walker\n" << walk << endl;
HamAndOvlp(walk, ovlp, hamSample, ovlpSample, work);
int iter = 0;
double cumdeltaT = 0;
int printMod = schd.stochasticIter / 5;
while (iter < schd.stochasticIter) {
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
double ratio = deltaT / cumdeltaT;
sMat *= (1 - ratio);
sMat += ratio * ovlpSample;
ciHam *= (1 - ratio);
ciHam += ratio * hamSample;
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
//cout << "walker\n" << walk << endl;
hamSample.setZero();
ovlpSample.setZero();
HamAndOvlp(walk, ovlp, hamSample, ovlpSample, work);
iter++;
if (commrank == 0 && iter % printMod == 1) cout << "iter " << iter << " t " << getTime() - startofCalc << endl;
}
sMat *= cumdeltaT;
ciHam *= cumdeltaT;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, sMat.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ciHam.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
if (commrank == 0) {
sMat /= cumdeltaT;
ciHam /= cumdeltaT;
//ciHam = (ciHam + ciHam.transpose().eval()) / 2;
double ene0 = ciHam(0, 0) / sMat(0, 0);
cout << "ref energy " << setprecision(12) << ciHam(0, 0) / sMat(0, 0) << endl;
//sMat += 1.e-7 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//cout << "ciHam\n" << ciHam << endl << endl;
//cout << "sMat\n" << sMat << endl << endl;
MatrixXd projSMat = sMat.block(1,1,coeffs.size()-1, coeffs.size()-1) - sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
MatrixXd projHam = ciHam.block(1,1,coeffs.size()-1, coeffs.size()-1)- ciHam.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1)
- sMat.block(1,0,coeffs.size()-1,1) * ciHam.block(0,1,1,coeffs.size()-1)
+ ene0 * sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
EigenSolver<MatrixXd> ovlpDiag(projSMat);
VectorXd norms = ovlpDiag.eigenvalues().real();
std::vector<int> largeNormIndices;
for (int i = 0; i < coeffs.size()-1; i++) {
if (norms(i) > schd.overlapCutoff) {
largeNormIndices.push_back(i);
}
}
Map<VectorXi> largeNormSlice(&largeNormIndices[0], largeNormIndices.size());
VectorXd largeNorms;
igl::slice(norms, largeNormSlice, largeNorms);
cout << "largeNorms size " << largeNorms.size() << endl;
DiagonalMatrix<double, Dynamic> largeNormInv;
largeNormInv.resize(largeNorms.size());
largeNormInv.diagonal() = largeNorms.cwiseSqrt().cwiseInverse();
//largeNormInv.diagonal() = largeNorms.cwiseInverse();
MatrixXd largeBasis;
igl::slice(ovlpDiag.eigenvectors().real(), VectorXi::LinSpaced(coeffs.size()-1, 0, coeffs.size()-2), largeNormSlice, largeBasis);
MatrixXd basisChange = largeBasis * largeNormInv;
MatrixXd largeHam = basisChange.transpose() * projHam * basisChange;
EigenSolver<MatrixXd> hamDiag(largeHam);
cout << "eigenvalues\n" << hamDiag.eigenvalues().real() << endl;
//GeneralizedEigenSolver<MatrixXd> diag(ciHam, sMat);
//VectorXd::Index minInd;
//double minEne = diag.eigenvalues().real().minCoeff(&minInd);
//double ene0 = 0.; VectorXd gs = VectorXd::Zero(coeffs.size());
//generalizedJacobiDavidson(ciHam, sMat, ene0, gs);
//cout << "ene0 " << ene0 << endl;
//coeffs = diag.eigenvectors().col(minInd).real();
//cout << "ciHam\n" << ciHam << endl << endl;
//cout << "sMat\n" << sMat << endl << endl;
//cout << "eigenvalues\n" << diag.eigenvalues() << endl;
}
}
void calcPolCT(Walker<Corr, Reference>& walk) {
//add noise to avoid zero coeffs
// if (commrank == 0) {
// cout << "starting sampling at " << setprecision(4) << getTime() - startofCalc << endl;
// auto random = std::bind(std::uniform_real_distribution<double>(0., 1.e-8), std::ref(generator));
// for (int i=0; i < coeffs.size(); i++) {
// if (coeffs(i) == 0) coeffs(i) = random();
// }
// }
//
//#ifndef SERIAL
// MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
//#endif
//sampling
int norbs = Determinant::norbs;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
workingArray work;
double ovlp = 0.;
MatrixXd hamSample = VectorXd::Zero(coeffs.size());
MatrixXd ovlpSample = VectorXd::Zero(coeffs.size());
MatrixXd ciHam = MatrixXd::Zero(coeffs.size(), coeffs.size());
MatrixXd sMat = MatrixXd::Zero(coeffs.size(), coeffs.size());
//cout << "walker\n" << walk << endl;
HamAndOvlp(walk, ovlp, hamSample, ovlpSample, work);
int iter = 0;
double cumdeltaT = 0;
int printMod = schd.stochasticIter / 5;
while (iter < schd.stochasticIter) {
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
double ratio = deltaT / cumdeltaT;
sMat *= (1 - ratio);
sMat += ratio * ovlpSample;
ciHam *= (1 - ratio);
ciHam += ratio * hamSample;
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
//cout << "walker\n" << walk << endl;
hamSample.setZero();
ovlpSample.setZero();
HamAndOvlp(walk, ovlp, hamSample, ovlpSample, work);
iter++;
if (commrank == 0 && iter % printMod == 1) cout << "iter " << iter << " t " << getTime() - startofCalc << endl;
}
sMat *= cumdeltaT;
ciHam *= cumdeltaT;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, sMat.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ciHam.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
if (commrank == 0) {
sMat /= cumdeltaT;
ciHam /= cumdeltaT;
//ciHam = (ciHam + ciHam.transpose().eval()) / 2;
double ene0 = ciHam(0, 0) / sMat(0, 0);
cout << "ref energy " << setprecision(12) << ciHam(0, 0) / sMat(0, 0) << endl;
MatrixXd projSMat = sMat.block(1,1,coeffs.size()-1, coeffs.size()-1) - sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
MatrixXd projHam = ciHam.block(1,1,coeffs.size()-1, coeffs.size()-1)- ciHam.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1)
- sMat.block(1,0,coeffs.size()-1,1) * ciHam.block(0,1,1,coeffs.size()-1)
+ ene0 * sMat.block(1,0,coeffs.size()-1,1) * sMat.block(0,1,1,coeffs.size()-1);
//sMat += 1.e-7 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//cout << "ciHam\n" << ciHam << endl << endl;
//cout << "sMat\n" << sMat << endl << endl;
//EigenSolver<MatrixXd> ovlpDiag(sMat);
//VectorXd norms = ovlpDiag.eigenvalues().real();
//std::vector<int> largeNormIndices;
//for (int i = 0; i < coeffs.size(); i++) {
// if (norms(i) > schd.overlapCutoff) {
// largeNormIndices.push_back(i);
// }
//}
//Map<VectorXi> largeNormSlice(&largeNormIndices[0], largeNormIndices.size());
//VectorXd largeNorms;
//igl::slice(norms, largeNormSlice, largeNorms);
//cout << "largeNorms size " << largeNorms.size() << endl;
//DiagonalMatrix<double, Dynamic> largeNormInv;
//largeNormInv.resize(largeNorms.size());
//largeNormInv.diagonal() = largeNorms.cwiseSqrt().cwiseInverse();
////largeNormInv.diagonal() = largeNorms.cwiseInverse();
//MatrixXd largeBasis;
//igl::slice(ovlpDiag.eigenvectors().real(), VectorXi::LinSpaced(coeffs.size(), 0, coeffs.size()-1), largeNormSlice, largeBasis);
//MatrixXd basisChange = largeBasis * largeNormInv;
//MatrixXd largeHam = basisChange.transpose() * ciHam * basisChange;
//VectorXcd stateOnTheSide = basisChange.transpose() * sMat.col(2);
//for (int i = 0; i < 100; i++) {
// complex<double> w (-0.5 + 0.005 * i, 0.001);
// MatrixXcd aMat = (w - ene0) * MatrixXcd::Identity(largeNorms.size(), largeNorms.size()) + largeHam;
// Eigen::ColPivHouseholderQR<Eigen::MatrixXcd> lin(aMat);
// VectorXcd corr = lin.solve(stateOnTheSide);
// cout << w << " " << (stateOnTheSide.adjoint() * corr).imag() << endl;
//}
VectorXcd stateOnTheSide = VectorXcd::Zero(coeffs.size()-1);
stateOnTheSide.real() = projSMat.col(0);
for (int i = 0; i < 100; i++) {
complex<double> w (-0.5 + 0.005 * i, 0.001);
MatrixXcd aMat = (w - ene0) * projSMat + projHam;
//Eigen::ColPivHouseholderQR<Eigen::MatrixXcd> lin(aMat);
//Eigen::ConjugateGradient<Eigen::MatrixXcd> lin(aMat);
Eigen::BiCGSTAB<Eigen::MatrixXcd> lin(aMat);
VectorXcd corr = lin.solve(stateOnTheSide);
cout << w << " " << (stateOnTheSide.adjoint() * corr).imag() << endl;
}
}
}
string getfileName() const {
return "eom"+wave.getfileName();
}
void writeWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
#endif
}
};
#endif
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef CX_NUMPY_ARRAY_H
#define CX_NUMPY_ARRAY_H
#include <stdio.h> // for FILE*.
#include <stdexcept>
#include "CxPodArray.h"
#include "CxDefs.h"
// support for reading and writing array data in .npy format.
// (that's what numpy.save() and numpy.load() use)
class FNdArrayView;
namespace ct {
struct FIoExceptionNpy : public std::runtime_error {
explicit FIoExceptionNpy(std::string const &Msg, std::string const &FileName = "");
};
typedef TArray<std::size_t>
FShapeNpy;
// write the continuous array pData[i,j,k,..] to the given file in .npy
// format. pShape[i] gives the number of indices in dimension #i, nDim
// gives the total dimension of the array.
void WriteNpy(FILE *File, FScalar const *pData, std::size_t const pShape[], std::size_t nDim);
void WriteNpy(std::string const &FileName, FScalar const *pData, std::size_t const pShape[], std::size_t nDim);
void WriteNpy(FILE *File, FScalar const *pData, FShapeNpy const &Shape);
void WriteNpy(std::string const &FileName, FScalar const *pData, FShapeNpy const &Shape);
// convenience functions for making array shape objects.
FShapeNpy MakeShape(std::size_t i0);
FShapeNpy MakeShape(std::size_t i0, std::size_t i1);
FShapeNpy MakeShape(std::size_t i0, std::size_t i1, std::size_t i2);
FShapeNpy MakeShape(std::size_t i0, std::size_t i1, std::size_t i2, std::size_t i3);
struct FArrayNpy {
TArray<FScalar>
Data;
FShapeNpy
Shape,
Strides; // <- may be inverted when reading in stuff in C order.
std::size_t Rank() const { return Shape.size(); }
std::size_t Size() const;
enum FCreationFlags {
NPY_OrderFortran = 0x0, // first dimension first
NPY_OrderC = 0x1, // last dimension first
NPY_ClearData = 0x2 // set data to zero
};
FArrayNpy() {}
explicit FArrayNpy(FShapeNpy const &Shape, uint Flags = NPY_OrderC);
void swap(FArrayNpy &Other);
FScalar &operator() (std::size_t i0) { return Data[Strides[0]*i0]; }
FScalar &operator() (std::size_t i0, std::size_t i1) { return Data[Strides[0]*i0 + Strides[1]*i1]; }
FScalar &operator() (std::size_t i0, std::size_t i1, std::size_t i2) { return Data[Strides[0]*i0 + Strides[1]*i1 + Strides[2]*i2]; }
FScalar &operator() (std::size_t i0, std::size_t i1, std::size_t i2, std::size_t i3) { return Data[Strides[0]*i0 + Strides[1]*i1 + Strides[2]*i2 + Strides[3]*i3]; }
FScalar operator() (std::size_t i0) const { return Data[Strides[0]*i0]; }
FScalar operator() (std::size_t i0, std::size_t i1) const { return Data[Strides[0]*i0 + Strides[1]*i1]; }
FScalar operator() (std::size_t i0, std::size_t i1, std::size_t i2) const { return Data[Strides[0]*i0 + Strides[1]*i1 + Strides[2]*i2]; }
FScalar operator() (std::size_t i0, std::size_t i1, std::size_t i2, std::size_t i3) const { return Data[Strides[0]*i0 + Strides[1]*i1 + Strides[2]*i2 + Strides[3]*i3]; }
// flags: bit field of NPY_*.
void Init(FShapeNpy const &Shape_, uint Flags = NPY_OrderC);
};
// read array from File in .npy format.
void ReadNpy(FArrayNpy &Out, FILE *File);
void ReadNpyData(FNdArrayView &Out, FILE *File);
void ReadNpy(FArrayNpy &Out, std::string const &FileName);
void ReadNpyData(FNdArrayView &Out, std::string const &FileName);
} // namespace ct
#endif // CX_NUMPY_ARRAY_H
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace MRLCC_ACVV {
FTensorDecl TensorDecls[31] = {
/* 0*/{"t", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "eeca", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"k", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"k", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"k", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"W", "caca", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 6*/{"W", "caac", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 7*/{"W", "cece", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 8*/{"W", "ceec", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 9*/{"W", "aeae", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 10*/{"W", "aeea", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 11*/{"W", "cccc", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 13*/{"k", "e", "",USAGE_Intermediate, STORAGE_Memory},
/* 14*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S3", "a", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"S1", "AA", "",USAGE_Density, STORAGE_Memory},
/* 18*/{"S2", "aa", "",USAGE_Density, STORAGE_Memory},
/* 19*/{"T", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"b", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"p", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"Ap", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"P", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"AP", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"B", "eeca", "",USAGE_Amplitude, STORAGE_Memory},
/* 26*/{"W", "eeca", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 27*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 29*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 30*/{"Inter", "eeca", "",USAGE_Intermediate, STORAGE_Memory},
};
//Number of terms : 48
FEqInfo EqsRes[46] = {
{"CDJR,IAJC,RQ,ADIQ", -2.0 , 4, {22,7,14,21}}, //Ap[CDJR] += -2.0 W[IAJC] E1[RQ] p[ADIQ]
{"CDJR,IAJD,RQ,ACIQ", 1.0 , 4, {22,7,14,21}}, //Ap[CDJR] += 1.0 W[IAJD] E1[RQ] p[ACIQ]
{"CDJR,IBJC,RQ,DBIQ", 1.0 , 4, {22,7,14,21}}, //Ap[CDJR] += 1.0 W[IBJC] E1[RQ] p[DBIQ]
{"CDJR,IBJD,RQ,CBIQ", -2.0 , 4, {22,7,14,21}}, //Ap[CDJR] += -2.0 W[IBJD] E1[RQ] p[CBIQ]
{"CDJR,ICAJ,RQ,ADIQ", 4.0 , 4, {22,8,14,21}}, //Ap[CDJR] += 4.0 W[ICAJ] E1[RQ] p[ADIQ]
{"CDJR,ICBJ,RQ,DBIQ", -2.0 , 4, {22,8,14,21}}, //Ap[CDJR] += -2.0 W[ICBJ] E1[RQ] p[DBIQ]
{"CDJR,IDAJ,RQ,ACIQ", -2.0 , 4, {22,8,14,21}}, //Ap[CDJR] += -2.0 W[IDAJ] E1[RQ] p[ACIQ]
{"CDJR,IDBJ,RQ,CBIQ", 1.0 , 4, {22,8,14,21}}, //Ap[CDJR] += 1.0 W[IDBJ] E1[RQ] p[CBIQ]
//{"CDJR,ABCD,RQ,ABJQ", 2.0 , 4, {22,13,14,21}}, //Ap[CDJR] += 2.0 W[ABCD] E1[RQ] p[ABJQ]
//{"CDJR,ABDC,RQ,ABJQ", -1.0 , 4, {22,13,14,21}}, //Ap[CDJR] += -1.0 W[ABDC] E1[RQ] p[ABJQ]
{"CDJR,IJ,RQ,CDIQ", -2.0 , 4, {22,2,14,21}}, //Ap[CDJR] += -2.0 k[IJ] E1[RQ] p[CDIQ]
{"CDJR,IJ,RQ,DCIQ", 1.0 , 4, {22,2,14,21}}, //Ap[CDJR] += 1.0 k[IJ] E1[RQ] p[DCIQ]
{"CDJR,AC,RQ,ADJQ", 2.0 , 4, {22,4,14,21}}, //Ap[CDJR] += 2.0 k[AC] E1[RQ] p[ADJQ]
{"CDJR,AD,RQ,ACJQ", -1.0 , 4, {22,4,14,21}}, //Ap[CDJR] += -1.0 k[AD] E1[RQ] p[ACJQ]
{"CDJR,BC,RQ,DBJQ", -1.0 , 4, {22,4,14,21}}, //Ap[CDJR] += -1.0 k[BC] E1[RQ] p[DBJQ]
{"CDJR,BD,RQ,CBJQ", 2.0 , 4, {22,4,14,21}}, //Ap[CDJR] += 2.0 k[BD] E1[RQ] p[CBJQ]
{"CDJR,IJab,RQ,ba,CDIQ", 2.0 , 5, {22,11,14,27,21}}, //Ap[CDJR] += 2.0 W[IJab] E1[RQ] delta[ba] p[CDIQ]
{"CDJR,IJab,RQ,ba,DCIQ", -1.0 , 5, {22,11,14,27,21}}, //Ap[CDJR] += -1.0 W[IJab] E1[RQ] delta[ba] p[DCIQ]
{"CDJR,IaJb,RQ,ba,CDIQ", -4.0 , 5, {22,11,14,27,21}}, //Ap[CDJR] += -4.0 W[IaJb] E1[RQ] delta[ba] p[CDIQ]
{"CDJR,IaJb,RQ,ba,DCIQ", 2.0 , 5, {22,11,14,27,21}}, //Ap[CDJR] += 2.0 W[IaJb] E1[RQ] delta[ba] p[DCIQ]
{"CDJR,aAbC,RQ,ba,ADJQ", 4.0 , 5, {22,7,14,27,21}}, //Ap[CDJR] += 4.0 W[aAbC] E1[RQ] delta[ba] p[ADJQ]
{"CDJR,aAbD,RQ,ba,ACJQ", -2.0 , 5, {22,7,14,27,21}}, //Ap[CDJR] += -2.0 W[aAbD] E1[RQ] delta[ba] p[ACJQ]
{"CDJR,aBbC,RQ,ba,DBJQ", -2.0 , 5, {22,7,14,27,21}}, //Ap[CDJR] += -2.0 W[aBbC] E1[RQ] delta[ba] p[DBJQ]
{"CDJR,aBbD,RQ,ba,CBJQ", 4.0 , 5, {22,7,14,27,21}}, //Ap[CDJR] += 4.0 W[aBbD] E1[RQ] delta[ba] p[CBJQ]
{"CDJR,aCAb,RQ,ba,ADJQ", -2.0 , 5, {22,8,14,27,21}}, //Ap[CDJR] += -2.0 W[aCAb] E1[RQ] delta[ba] p[ADJQ]
{"CDJR,aCBb,RQ,ba,DBJQ", 1.0 , 5, {22,8,14,27,21}}, //Ap[CDJR] += 1.0 W[aCBb] E1[RQ] delta[ba] p[DBJQ]
{"CDJR,aDAb,RQ,ba,ACJQ", 1.0 , 5, {22,8,14,27,21}}, //Ap[CDJR] += 1.0 W[aDAb] E1[RQ] delta[ba] p[ACJQ]
{"CDJR,aDBb,RQ,ba,CBJQ", -2.0 , 5, {22,8,14,27,21}}, //Ap[CDJR] += -2.0 W[aDBb] E1[RQ] delta[ba] p[CBJQ]
{"CDJR,Qa,Ra,CDJQ", -2.0 , 4, {22,3,14,21}}, //Ap[CDJR] += -2.0 k[Qa] E1[Ra] p[CDJQ]
{"CDJR,Qa,Ra,DCJQ", 1.0 , 4, {22,3,14,21}}, //Ap[CDJR] += 1.0 k[Qa] E1[Ra] p[DCJQ]
{"CDJR,aQcb,Rb,ca,CDJQ", -4.0 , 5, {22,5,14,27,21}}, //Ap[CDJR] += -4.0 W[aQcb] E1[Rb] delta[ca] p[CDJQ]
{"CDJR,aQcb,Rb,ca,DCJQ", 2.0 , 5, {22,5,14,27,21}}, //Ap[CDJR] += 2.0 W[aQcb] E1[Rb] delta[ca] p[DCJQ]
{"CDJR,aQbc,Rb,ca,CDJQ", 2.0 , 5, {22,6,14,27,21}}, //Ap[CDJR] += 2.0 W[aQbc] E1[Rb] delta[ca] p[CDJQ]
{"CDJR,aQbc,Rb,ca,DCJQ", -1.0 , 5, {22,6,14,27,21}}, //Ap[CDJR] += -1.0 W[aQbc] E1[Rb] delta[ca] p[DCJQ]
{"CDJR,aAbC,RaQb,ADJQ", 2.0 , 4, {22,9,15,21}}, //Ap[CDJR] += 2.0 W[aAbC] E2[RaQb] p[ADJQ]
{"CDJR,aAbD,RaQb,ACJQ", -1.0 , 4, {22,9,15,21}}, //Ap[CDJR] += -1.0 W[aAbD] E2[RaQb] p[ACJQ]
{"CDJR,aBbC,RaQb,DBJQ", -1.0 , 4, {22,9,15,21}}, //Ap[CDJR] += -1.0 W[aBbC] E2[RaQb] p[DBJQ]
{"CDJR,aBbD,RaQb,CBJQ", 2.0 , 4, {22,9,15,21}}, //Ap[CDJR] += 2.0 W[aBbD] E2[RaQb] p[CBJQ]
{"CDJR,aCAb,RaQb,ADJQ", -1.0 , 4, {22,10,15,21}}, //Ap[CDJR] += -1.0 W[aCAb] E2[RaQb] p[ADJQ]
{"CDJR,aCBb,RabQ,DBJQ", -1.0 , 4, {22,10,15,21}}, //Ap[CDJR] += -1.0 W[aCBb] E2[RabQ] p[DBJQ]
{"CDJR,aDAb,RabQ,ACJQ", -1.0 , 4, {22,10,15,21}}, //Ap[CDJR] += -1.0 W[aDAb] E2[RabQ] p[ACJQ]
{"CDJR,aDBb,RabQ,CBJQ", 2.0 , 4, {22,10,15,21}}, //Ap[CDJR] += 2.0 W[aDBb] E2[RabQ] p[CBJQ]
{"CDJR,IaJb,RaQb,CDIQ", -2.0 , 4, {22,5,15,21}}, //Ap[CDJR] += -2.0 W[IaJb] E2[RaQb] p[CDIQ]
{"CDJR,IaJb,RaQb,DCIQ", 1.0 , 4, {22,5,15,21}}, //Ap[CDJR] += 1.0 W[IaJb] E2[RaQb] p[DCIQ]
{"CDJR,IabJ,RaQb,CDIQ", 1.0 , 4, {22,6,15,21}}, //Ap[CDJR] += 1.0 W[IabJ] E2[RaQb] p[CDIQ]
{"CDJR,IabJ,RabQ,DCIQ", 1.0 , 4, {22,6,15,21}}, //Ap[CDJR] += 1.0 W[IabJ] E2[RabQ] p[DCIQ]
{"CDJR,Qabc,Rabc,CDJQ", -2.0 , 4, {22,12,15,21}}, //Ap[CDJR] += -2.0 W[Qabc] E2[Rabc] p[CDJQ]
{"CDJR,Qabc,Rabc,DCJQ", 1.0 , 4, {22,12,15,21}}, //Ap[CDJR] += 1.0 W[Qabc] E2[Rabc] p[DCJQ]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[2] = {
{"ABIP,RP,ABIR", 2.0, 3, {20, 14, 26}},
{"ABIP,RP,BAIR",-1.0, 3, {20, 14, 26}}
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "MRLCC_ACVV";
Out.perturberClass = "ACVV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 31;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsRes = FEqSet(&EqsRes[0], 46, "MRLCC_ACVV/Res");
Out.Overlap = FEqSet(&Overlap[0], 2, "MRLCC_ACVV/Overlap");
};
};
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "RBM.h"
#include "Correlator.h"
#include "Determinants.h"
#include <boost/container/static_vector.hpp>
#include <fstream>
#include "input.h"
using namespace Eigen;
RBM::RBM () {
int norbs = Determinant::norbs;
numHidden = schd.numHidden;
wMat = MatrixXd::Random(numHidden, 2*norbs) / 50;
bVec = VectorXd::Zero(numHidden);
aVec = VectorXd::Zero(2*norbs);
bool readRBM = false;
char file[5000];
sprintf(file, "RBM.txt");
ifstream ofile(file);
if (ofile)
readRBM = true;
if (readRBM) {
for (int i = 0; i < wMat.rows(); i++) {
for (int j = 0; j < wMat.cols(); j++){
ofile >> wMat(i, j);
}
}
}
};
double RBM::Overlap(const Determinant &d) const
{
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
double ovlp = 1.0;
VectorXd wn = VectorXd::Zero(numHidden);
for (int j = 0; j < closed.size(); j++) {
ovlp *= exp(aVec(closed[j]));
wn += wMat.col(closed[j]);
}
ovlp *= cosh((bVec + wn).array()).prod();
return ovlp;
}
double RBM::OverlapRatio (const Determinant &d1, const Determinant &d2) const {
return Overlap(d1)/Overlap(d2);
}
double RBM::OverlapRatio(int i, int a, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
double RBM::OverlapRatio(int i, int j, int a, int b, const Determinant &dcopy, const Determinant &d) const
{
return OverlapRatio(dcopy, d);
}
//assuming bwn corresponds to d
void RBM::OverlapWithGradient(const Determinant& d,
Eigen::VectorBlock<VectorXd>& grad,
const double& ovlp) const {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
ArrayXd tanhbwn = tanh(bwn.array());
if (schd.optimizeCps) {
grad.segment(numHidden * 2 * norbs, numHidden) = tanhbwn.matrix(); //b derivatives
for (int j = 0; j < closed.size(); j++) {
grad(numHidden * 2 * norbs + numHidden + closed[j]) = 1; //a derivatives
grad.segment(numHidden * closed[j], numHidden) += tanhbwn.matrix();//w derivatives
}
}
}
long RBM::getNumVariables() const
{
return wMat.rows() * wMat.cols() + bVec.size() + aVec.size();
}
void RBM::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
int numVars = 0;
for (int j = 0; j < wMat.cols(); j++) {
for (int i = 0; i < wMat.rows(); i++) {
v[numVars] = wMat(i,j);
numVars++;
}
}
for (int i = 0; i < bVec.size(); i++) {
v[numVars] = bVec(i);
numVars++;
}
for (int i = 0; i < aVec.size(); i++) {
v[numVars] = aVec(i);
numVars++;
}
}
void RBM::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
int numVars = 0;
for (int j = 0; j < wMat.cols(); j++) {
for (int i = 0; i < wMat.rows(); i++) {
wMat(i,j) = v[numVars];
numVars++;
}
}
for (int i = 0; i < bVec.size(); i++) {
bVec(i) = v[numVars];
numVars++;
}
for (int i = 0; i < aVec.size(); i++) {
aVec(i) = v[numVars];
numVars++;
}
}
void RBM::printVariables() const
{
cout << "RBM\n";
cout << "wMat\n" << wMat << endl << endl;
cout << "bVec\n" << bVec << endl << endl;
cout << "aVec\n" << aVec << endl << endl;
}
<file_sep>import numpy as np
from pyscf import gto, scf, ao2mo, tools, fci
from pyscf.lo import pipek
from scipy.linalg import fractional_matrix_power
n = 4
norb = 4
sqrt2 = 2**0.5
ghfCoeffs = np.full((2*norb, 2*norb), 0.)
row = 0
fileh = open("ghf.txt", 'r')
for line in fileh:
col = 0
for coeff in line.split():
ghfCoeffs[row, col] = float(coeff)
col = col + 1
row = row + 1
fileh.close()
theta = ghfCoeffs[::, :n]
amat = np.full((n, n), 0.)
for i in range(n/2):
amat[2 * i + 1, 2 * i] = -1.
amat[2 * i, 2 * i + 1] = 1.
#print amat
pairMat = theta.dot(amat).dot(theta.T)
pairMati = np.random.rand(2*norb, 2*norb)/5
pairMati = pairMati - pairMati.T
#randMat = np.random.rand(2*norb,2*norb)
#randMat = (randMat - randMat.T)/10
filePfaff = open("pairMat.txt", 'w')
for i in range(2*norb):
for j in range(2*norb):
filePfaff.write('%16.10e '%(pairMat[i,j]))
filePfaff.write('\n')
filePfaff.close()
filePfaff = open("pairMati.txt", 'w')
for i in range(2*norb):
for j in range(2*norb):
filePfaff.write('%16.10e '%(pairMati[i,j]))
filePfaff.write('\n')
filePfaff.close()
<file_sep>#include "pythonInterface.h"
#include <iostream>
#include <vector>
#include <omp.h>
#include <stdio.h>
#include <pvfmm.hpp>
#include <ctime>
using namespace std;
//the coords are nx3 matrix in "c" order but libcint requires it to be in
//"f" order
void getValuesAtGrid(const double* grid_cformat, int ngrid, double* out) {
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
if (aovals.size() < nao*ngrid) {
aovals.resize(nao*ngrid, 0.0);
intermediate.resize(nao*ngrid, 0.0);
}
if (grid_fformat.size() < 3*ngrid)
grid_fformat.resize(ngrid*3);
std::fill(aovals.begin(), aovals.end(), 0.);
std::fill(out, out+ngrid, 0.);
std::fill(&intermediate[0], &intermediate[0]+nao*ngrid, 0.);
std::fill(&grid_fformat[0], &grid_fformat[0]+3*ngrid, 0.);
long lena[2] = {ngrid, nao}, stridea[2] = {1, ngrid}; //aovals, intermediate
long lenc[2] = {3, ngrid} , stridec[2] = {1, 3}; //grid-cformat
long lenf[2] = {ngrid, 3} , stridef[2] = {1, ngrid}; //grid-fformat
long lendm[2] = {nao, nao} , stridedm[2] = {1, nao}; //density matrix
long lenout[1] = {ngrid} , strideout[1] = {1}; //density matrix
tblis_init_tensor_d(&AOVALS, 2, lena, &aovals[0], stridea);
tblis_init_tensor_d(&INTERMEDIATE, 2, lena, &intermediate[0], stridea);
tblis_init_tensor_d(&GRID_C, 2, lenc, const_cast<double*>(&grid_cformat[0]), stridec);
tblis_init_tensor_d(&GRID_F, 2, lenf, &grid_fformat[0], stridef);
tblis_init_tensor_d(&DM, 2, lendm, dm, stridedm);
tblis_init_tensor_d(&OUT, 1, lenout, out, strideout);
//make the f-format from c-format
tblis_tensor_add(NULL, NULL, &GRID_C, "ij", &GRID_F, "ji");
//now you have to scale the basis such that centroid is 0.5
for (int i=0; i<ngrid; i++)
grid_fformat[i] = (grid_fformat[i]-0.5)*coordScale + centroid[0];
for (int i=0; i<ngrid; i++)
grid_fformat[ngrid+i] = (grid_fformat[ngrid+i]-0.5)*coordScale + centroid[1];
for (int i=0; i<ngrid; i++)
grid_fformat[2*ngrid+i] = (grid_fformat[2*ngrid+i]-0.5)*coordScale + centroid[2];
int tabSize = (((ngrid + BLKSIZE-1)/BLKSIZE) * nbas)*10;
if (non0tab.size() < tabSize)
non0tab.resize(tabSize, 1);
GTOval_cart(ngrid, shls, ao_loc, &aovals[0], &grid_fformat[0],
&non0tab[0], atm, natm, bas, nbas, env);
tblis_tensor_mult(NULL, NULL, &AOVALS, "gp", &DM, "pq", &INTERMEDIATE, "gq");
tblis_tensor_mult(NULL, NULL, &INTERMEDIATE, "gp", &AOVALS, "gp", &OUT, "g");
ncalls += ngrid;
}
void getPotential(int nTarget, double* coordsTarget, double* potential, double* pdm,
double* pcentroid, double pscale, double tol) {
cout.precision(12);
ncalls = 0;
dm = pdm;
centroid = pcentroid;
coordScale = pscale;
int rank;MPI_Comm_rank(MPI_COMM_WORLD, &rank);
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
MPI_Comm comm = MPI_COMM_WORLD;
int cheb_deg = 10, max_pts = 100, mult_order = 10;
vector<double> trg_coord(3*nTarget), input_coord(3*nTarget);
for (int i=0; i<nTarget; i++) {
trg_coord[3*i+0] = (coordsTarget[3*i+0] - centroid[0])/coordScale + 0.5;
trg_coord[3*i+1] = (coordsTarget[3*i+1] - centroid[1])/coordScale + 0.5;
trg_coord[3*i+2] = (coordsTarget[3*i+2] - centroid[2])/coordScale + 0.5;
}
const pvfmm::Kernel<double>& kernel_fn=pvfmm::LaplaceKernel<double>::potential();
auto* tree=ChebFMM_CreateTree(cheb_deg, kernel_fn.ker_dim[0],
getValuesAtGrid,
trg_coord, comm, tol, max_pts, pvfmm::FreeSpace);
current_time = time(NULL);
if (rank == 0) cout << "make tree "<<(current_time - Initcurrent_time)<<endl;
// Load matrices.
pvfmm::ChebFMM<double> matrices;
matrices.Initialize(mult_order, cheb_deg, comm, &kernel_fn);
// FMM Setup
tree->SetupFMM(&matrices);
current_time = time(NULL);
if (rank == 0) cout << "fmm setup "<<(current_time - Initcurrent_time)<<endl;
// Run FMM
std::vector<double> trg_value;
size_t n_trg=trg_coord.size()/PVFMM_COORD_DIM;
pvfmm::ChebFMM_Evaluate(tree, trg_value, n_trg);
current_time = time(NULL);
if (rank == 0) cout << "evalstep setup "<<(current_time - Initcurrent_time)<<endl;
for (int i=0; i<nTarget; i++)
potential[i] = trg_value[i]*4*M_PI;
}
<file_sep>#include <iostream>
#include <cmath>
#include <string.h>
#include "primitives.h"
#include "workArray.h"
double calcOvlpMatrix(int LA, double Ax, double Ay, double Az, double expA,
int LB, double Bx, double By, double Bz, double expB,
tensor& S_2d) {
calc1DOvlp(LA, Ax, expA, LB, Bx, expB, Sx_2d);
calc1DOvlp(LA, Ay, expA, LB, By, expB, Sy_2d);
calc1DOvlp(LA, Az, expA, LB, Bz, expB, Sz_2d);
int IA0 = (LA)*(LA+1)*(LA+2)/6;
int IB0 = (LB)*(LB+1)*(LB+2)/6;
double normA = 1.0/sqrt( doubleFact(2*LA-1)/pow(4*expA, LA)) / pow(M_PI/2./expA, 0.75);
if (LA >=2) normA = normA * sqrt(4* M_PI/ (2*LA+1));
double normB = 1.0/sqrt( doubleFact(2*LB-1)/pow(4*expB, LB)) / pow(M_PI/2./expB, 0.75);
if (LB >=2) normB = normB * sqrt(4 * M_PI / (2*LB+1));
for (int i=0; i<(LA+1)*(LA+2)/2; i++)
for (int j=0; j<(LB+1)*(LB+2)/2; j++) {
auto ipow = CartOrder[IA0 + i];
auto jpow = CartOrder[IB0 + j];
S_2d(i, j) = Sx_2d(ipow[0], jpow[0]) *
Sy_2d(ipow[1], jpow[1]) *
Sz_2d(ipow[2], jpow[2]) * normA * normB;
}
}
void calcCoulombIntegralPeriodic(int LA, double Ax, double Ay, double Az,
double expA, double normA,
int LB, double Bx, double By, double Bz,
double expB, double normB,
double Lx, double Ly, double Lz,
tensor& Int, bool includeNorm) {
if (includeNorm ) {
normA *= 1.0/sqrt( doubleFact(2*LA-1)/pow(4*expA, LA))
/ pow(M_PI/2./expA, 0.75);// * sqrt(4* M_PI/ (2*LA+1));
if (LA >=2) normA = normA * sqrt(4* M_PI/ (2*LA+1));
normB *= 1.0/sqrt( doubleFact(2*LB-1)/pow(4*expB, LB))
/ pow(M_PI/2./expB, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LB >=2) normB = normB * sqrt(4 * M_PI / (2*LB+1));
}
powExpA.dimensions = {LA+1}; powExpB.dimensions = {LB+1};
powPIOverLx.dimensions = {LA+LB+1}; powPIOverLy.dimensions = {LA+LB+1}; powPIOverLz.dimensions = {LA+LB+1};
for (int i=0; i<=LA; i++)
powExpA(i) = pow(1./expA, i);
for (int j=0; j<=LB; j++)
powExpB(j) = pow(1./expB, j);
for (int k=0; k<=LA+LB; k++) {
powPIOverLx(k) = pow(M_PI/Lx, k);
powPIOverLy(k) = pow(M_PI/Ly, k);
powPIOverLz(k) = pow(M_PI/Lz, k);
}
Sx_2d.dimensions ={LA+1, LB+1}; Sy_2d.dimensions ={LA+1, LB+1}; Sz_2d.dimensions ={LA+1, LB+1};
Sx2_2d.dimensions={LA+1, LB+1}; Sy2_2d.dimensions={LA+1, LB+1}; Sz2_2d.dimensions={LA+1, LB+1};
//Sx_2d.dimensions ={LA+1, LA+1}; Sy_2d.dimensions ={LA+1, LA+1}; Sz_2d.dimensions ={LA+1, LA+1};
//Sx2_2d.dimensions={LA+1, LA+1}; Sy2_2d.dimensions={LA+1, LA+1}; Sz2_2d.dimensions={LA+1, LA+1};
double prevt = -1.0;
Coulomb_14_14_8& coulomb = coulomb_14_14_8;
for (int i=0; i<coulomb.exponents.size(); i++) {
double expG = coulomb.exponents[i], wtG = coulomb.weights[i];
//assume that LA and LB = 0
double t = expG * expA * expB / (expG*expA + expG*expB + expA*expB);
double prefactor = pow(M_PI*M_PI*M_PI/(expG*expA*expB), 1.5) * normA * normB / (Lx * Ly * Lz);
//if (abs(t) < 1.e-6) continue;
if (abs(prevt - t) > 1.e-6) {
calc1DOvlpPeriodic(LA, Ax, expA, LB, Bx, expB, t, 0, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Ay, expA, LB, By, expB, t, 0, Ly, Sy_2d, &workArray[0], powPIOverLy, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Az, expA, LB, Bz, expB, t, 0, Lz, Sz_2d, &workArray[0], powPIOverLz, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Ax, expA, LB, Bx, expB, 0, 0, Lx, Sx2_2d, &workArray[0], powPIOverLx, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Ay, expA, LB, By, expB, 0, 0, Ly, Sy2_2d, &workArray[0], powPIOverLy, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Az, expA, LB, Bz, expB, 0, 0, Lz, Sz2_2d, &workArray[0], powPIOverLz, powExpA, powExpB);
}
prevt = t;
int IA0 = (LA)*(LA+1)*(LA+2)/6;
int IB0 = (LB)*(LB+1)*(LB+2)/6;
//now calculate the 3d integrals.
for (int i=0; i<(LA+1)*(LA+2)/2; i++)
for (int j=0; j<(LB+1)*(LB+2)/2; j++) {
vector<int>& ipow = CartOrder[IA0 + i];
vector<int>& jpow = CartOrder[IB0 + j];
/*
double k0Termx = DerivativeToPolynomial(ipow[0], 0)
* DerivativeToPolynomial(jpow[0], 0)
* powExpA(ipow[0]/2) * powExpB(jpow[0]/2);
double k0Termy = DerivativeToPolynomial(ipow[1], 0)
* DerivativeToPolynomial(jpow[1], 0)
* powExpA(ipow[1]/2) * powExpB(jpow[1]/2);
//* pow(1./expA, ipow[1]/2) * pow(1./expB, jpow[1]/2);
double k0Termz = DerivativeToPolynomial(ipow[2], 0)
* DerivativeToPolynomial(jpow[2], 0)
* powExpA(ipow[2]/2) * powExpB(jpow[2]/2);
//* pow(1./expA, ipow[2]/2) * pow(1./expB, jpow[2]/2);
*/
Int(i, j) += prefactor * ( (Sx_2d(ipow[0], jpow[0])) *
(Sy_2d(ipow[1], jpow[1])) *
(Sz_2d(ipow[2], jpow[2])) -
(Sx2_2d(ipow[0], jpow[0])) *
(Sy2_2d(ipow[1], jpow[1])) *
(Sz2_2d(ipow[2], jpow[2]))) * wtG;
//- k0Termx*k0Termy*k0Termz) * wtG ;
}
}
}
void calcKineticIntegralPeriodic(int LA, double Ax, double Ay, double Az,
double expA, double normA,
int LB, double Bx, double By, double Bz,
double expB, double normB,
double Lx, double Ly, double Lz,
tensor& Int, bool Includenorm) {
if (Includenorm) {
normA *= 1.0/sqrt( doubleFact(2*LA-1)/pow(4*expA, LA))
/ pow(M_PI/2./expA, 0.75);// * sqrt(4* M_PI/ (2*LA+1));
if (LA >=2) normA = normA * sqrt(4* M_PI/ (2*LA+1));
normB *= 1.0/sqrt( doubleFact(2*LB-1)/pow(4*expB, LB))
/ pow(M_PI/2./expB, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LB >=2) normB = normB * sqrt(4 * M_PI / (2*LB+1));
}
//assume that LA and LB = 0
double prefactor = pow(M_PI*M_PI/(expA*expB), 1.5) * normA * normB / (Lx * Ly * Lz);
double t = expA*expB/(expA + expB);
powExpA.dimensions = {LA+3}; powExpB.dimensions = {LB+3};
powPIOverLx.dimensions = {LA+LB+3}; powPIOverLy.dimensions = {LA+LB+3}; powPIOverLz.dimensions = {LA+LB+3};
for (int i=0; i<=LA+2; i++)
powExpA(i) = pow(1./expA, i);
for (int j=0; j<=LB+2; j++)
powExpB(j) = pow(1./expB, j);
for (int k=0; k<=LA+LB+3; k++) {
powPIOverLx(k) = pow(M_PI/Lx, k);
powPIOverLy(k) = pow(M_PI/Ly, k);
powPIOverLz(k) = pow(M_PI/Lz, k);
}
Sx_2d.dimensions ={LA+3, LB+3}; Sy_2d.dimensions ={LA+3, LB+3}; Sz_2d.dimensions ={LA+3, LB+3};
Sx2_2d.dimensions={LA+3, LB+3}; Sy2_2d.dimensions={LA+3, LB+3}; Sz2_2d.dimensions={LA+3, LB+3};
calc1DOvlpPeriodic(LA, Ax, expA, LB, Bx, expB, t, 2, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Ay, expA, LB, By, expB, t, 2, Ly, Sy_2d, &workArray[0], powPIOverLy, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Az, expA, LB, Bz, expB, t, 2, Lz, Sz_2d, &workArray[0], powPIOverLz, powExpA, powExpB);
int IA0 = (LA)*(LA+1)*(LA+2)/6;
int IB0 = (LB)*(LB+1)*(LB+2)/6;
//now calculate the 3d integrals.
for (int i=0; i<(LA+1)*(LA+2)/2; i++)
for (int j=0; j<(LB+1)*(LB+2)/2; j++) {
vector<int>& ipow = CartOrder[IA0 + i];
vector<int>& jpow = CartOrder[IB0 + j];
double derivX = 4*expB*expB * Sx_2d(ipow[0], jpow[0]+2)
- 2. * expB * (2 * jpow[0] + 1) * Sx_2d(ipow[0], jpow[0])
+ (jpow[0] >= 2 ? jpow[0]*(jpow[0]-1) * Sx_2d(ipow[0], jpow[0]-2) : 0.0);
double derivY = 4*expB*expB * Sy_2d(ipow[1], jpow[1]+2)
- 2. * expB * (2 * jpow[1] + 1) * Sy_2d(ipow[1], jpow[1])
+ (jpow[1] >= 2 ? jpow[1]*(jpow[1]-1) * Sy_2d(ipow[1], jpow[1]-2) : 0.0);
double derivZ = 4*expB*expB * Sz_2d(ipow[2], jpow[2]+2)
- 2. * expB * (2 * jpow[2] + 1) * Sz_2d(ipow[2], jpow[2])
+ (jpow[2] >= 2 ? jpow[2]*(jpow[2]-1) * Sz_2d(ipow[2], jpow[2]-2) : 0.0);
Int(i, j) += -0.5 * prefactor * ( derivX * Sy_2d(ipow[1], jpow[1]) * Sz_2d(ipow[2], jpow[2]) +
derivY * Sx_2d(ipow[0], jpow[0]) * Sz_2d(ipow[2], jpow[2]) +
derivZ * Sy_2d(ipow[1], jpow[1]) * Sx_2d(ipow[0], jpow[0]) );
}
}
void calcOverlapIntegralPeriodic(int LA, double Ax, double Ay, double Az,
double expA, double normA,
int LB, double Bx, double By, double Bz,
double expB, double normB,
double Lx, double Ly, double Lz,
tensor& Int, bool Includenorm) {
if (Includenorm) {
normA *= 1.0/sqrt( doubleFact(2*LA-1)/pow(4*expA, LA))
/ pow(M_PI/2./expA, 0.75);// * sqrt(4* M_PI/ (2*LA+1));
if (LA >=2) normA = normA * sqrt(4* M_PI/ (2*LA+1));
normB *= 1.0/sqrt( doubleFact(2*LB-1)/pow(4*expB, LB))
/ pow(M_PI/2./expB, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LB >=2) normB = normB * sqrt(4 * M_PI / (2*LB+1));
}
//assume that LA and LB = 0
double prefactor = pow(M_PI*M_PI/(expA*expB), 1.5) * normA * normB / (Lx * Ly * Lz);
double t = expA*expB/(expA + expB);
powExpA.dimensions = {LA+1}; powExpB.dimensions = {LB+1};
powPIOverLx.dimensions = {LA+LB+1}; powPIOverLy.dimensions = {LA+LB+1}; powPIOverLz.dimensions = {LA+LB+1};
for (int i=0; i<=LA; i++)
powExpA(i) = pow(1./expA, i);
for (int j=0; j<=LB; j++)
powExpB(j) = pow(1./expB, j);
for (int k=0; k<=LA+LB; k++) {
powPIOverLx(k) = pow(M_PI/Lx, k);
powPIOverLy(k) = pow(M_PI/Ly, k);
powPIOverLz(k) = pow(M_PI/Lz, k);
}
Sx_2d.dimensions ={LA+1, LB+1}; Sy_2d.dimensions ={LA+1, LB+1}; Sz_2d.dimensions ={LA+1, LB+1};
Sx2_2d.dimensions={LA+1, LB+1}; Sy2_2d.dimensions={LA+1, LB+1}; Sz2_2d.dimensions={LA+1, LB+1};
calc1DOvlpPeriodic(LA, Ax, expA, LB, Bx, expB, t, 0, Lx, Sx_2d, &workArray[0], powPIOverLx, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Ay, expA, LB, By, expB, t, 0, Ly, Sy_2d, &workArray[0], powPIOverLy, powExpA, powExpB);
calc1DOvlpPeriodic(LA, Az, expA, LB, Bz, expB, t, 0, Lz, Sz_2d, &workArray[0], powPIOverLz, powExpA, powExpB);
int IA0 = (LA)*(LA+1)*(LA+2)/6;
int IB0 = (LB)*(LB+1)*(LB+2)/6;
//now calculate the 3d integrals.
for (int i=0; i<(LA+1)*(LA+2)/2; i++)
for (int j=0; j<(LB+1)*(LB+2)/2; j++) {
vector<int>& ipow = CartOrder[IA0 + i];
vector<int>& jpow = CartOrder[IB0 + j];
Int(i, j) += prefactor * ( (Sx_2d(ipow[0], jpow[0])) *
(Sy_2d(ipow[1], jpow[1])) *
(Sz_2d(ipow[2], jpow[2])) );
}
}
void calcShellIntegral_2c(char* Name, double* integrals, int sh1, int sh2, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
double Lx = Lattice[0], Ly = Lattice[4], Lz = Lattice[8];
int nbas1 = bas[8* sh1 + 3], nbas2 = bas[8*sh2 +3];
int LA = bas[8 * sh1 +1], LB = bas[8 * sh2 +1];
int nLA = (LA+1)*(LA+2)/2, nLB = (LB+1)*(LB+2)/2;
int Dim1 = nbas1 * nLA,
Dim2 = nbas2 * nLB;
int stride1 = Dim2;
int stride2 = 1;
teri.dimensions = {nLA, nLB};
std::fill(integrals, integrals+Dim1*Dim2, 0.0);
double scaleLA = LA < 2 ? sqrt( (2*LA+1)/(4*M_PI)) : 1.0;
double scaleLB = LB < 2 ? sqrt( (2*LB+1)/(4*M_PI)) : 1.0;
double scaleLz = scaleLA * scaleLB ;
int start1 = bas[8 * sh1 + 5], end1 = bas[8 * sh1 + 6];
int sz1 = end1 - start1;
for (int ia = start1; ia<end1; ia++) {
int atmIndex = bas[8*sh1];
int LA = bas[8 * sh1 +1], pos = atm[6*atmIndex + 1];//20 + 4*bas[8*sh1];
double Ax = env[pos], Ay = env[pos + 1], Az = env[pos + 2];
double expA = env[ ia ];
int start2 = bas[8 * sh2 + 5], end2 = bas[8 * sh2 + 6];
int sz2 = end2 - start2;
for (int ja = start2; ja<end2; ja++) {
int atmIndex = bas[8*sh2];
int LB = bas[8 * sh2 +1], pos = atm[6*atmIndex + 1];//20 + 4*bas[8*sh2];
double Bx = env[pos], By = env[pos + 1], Bz = env[pos + 2];
double expB = env[ ja ];
teri.setZero();
if (strncmp(Name, "ovl", 3)==0) {
calcOverlapIntegralPeriodic(
LA, Ax, Ay, Az, expA, 1.0,
LB, Bx, By, Bz, expB, 1.0,
Lx, Ly, Lz, teri, false);
}
else if (strncmp(Name, "kin", 3)==0) {
calcKineticIntegralPeriodic(
LA, Ax, Ay, Az, expA, 1.0,
LB, Bx, By, Bz, expB, 1.0,
Lx, Ly, Lz, teri, false);
}
else if (strncmp(Name, "pot", 3)==0) {
calcCoulombIntegralPeriodic(
LA, Ax, Ay, Az, expA, 1.0,
LB, Bx, By, Bz, expB, 1.0,
Lx, Ly, Lz, teri, false);
}
else
cout << "Integral "<<Name<<" not supported"<<endl;
//now put teri in the correct location in the integrals
for (int ii = 0; ii<nbas1; ii++)
for (int jj = 0; jj<nbas2; jj++)
{
double scale = env[bas[8* sh1 +5] + (ii+1)*sz1 + (ia-start1)] *
env[bas[8* sh2 +5] + (jj+1)*sz2 + (ja-start2)] ;
for (int i=0; i<nLA; i++)
for (int j=0; j<nLB; j++) {
integrals[ (ii * nLA + i)*stride1 +
(jj * nLB + j)*stride2 ] += teri(i, j)*scale * scaleLz;
}
}
} //ja
}//ia
}
void calcIntegral_2c(char* Name, double* integrals, int* shls, int* ao_loc,
int* atm, int natm, int* bas, int nbas,
double* env, double* Lattice) {
int dim = 0;
for (int i=0; i<nbas; i++)
if (ao_loc[i+1] - ao_loc[i] > dim)
dim = ao_loc[i+1] - ao_loc[i];
tensor teri( {dim, dim});
int n1 = ao_loc[shls[1]] - ao_loc[shls[0]],
n2 = ao_loc[shls[3]] - ao_loc[shls[2]];
for(int sh1 = shls[0]; sh1 < shls[1]; sh1++)
for(int sh2 = shls[2]; sh2 < shls[3]; sh2++) {
calcShellIntegral_2c(Name, teri.vals, sh1, sh2, ao_loc, atm, natm, bas, nbas, env, Lattice);
teri.dimensions = {ao_loc[sh1+1] - ao_loc[sh1], ao_loc[sh2+1]-ao_loc[sh2]};
for (int i = ao_loc[sh1] - ao_loc[shls[0]]; i < ao_loc[sh1+1] - ao_loc[shls[0]]; i++)
for (int j = ao_loc[sh2] - ao_loc[shls[2]]; j < ao_loc[sh2+1] - ao_loc[shls[2]]; j++) {
int I = i - (ao_loc[sh1] - ao_loc[shls[0]]), J = j - (ao_loc[sh2] - ao_loc[shls[2]]);
integrals[i*n2 + j] = teri(I, J);
}
}//sh2
}
//actually this calculates phi_i(r, a, A) phi_0(r,tau, r') phi_j(r', b, B)
//where phi_0 is one of the gaussians approximating 1/r
/*
double calcCoulombIntegral(int LA, double Ax, double Ay, double Az,
double expA, double normA,
double expG, double wtG,
int LB, double Bx, double By, double Bz,
double expB, double normB,
tensor& Int) {
double mu = expG * expB / (expG + expB);
double prefactor = sqrt(M_PI/(expG + expB)) * normA * normB;
calc1DOvlp(LA, Ax, expA, LB, Bx, mu, Sx);
calc1DOvlp(LA, Ay, expA, LB, By, mu, Sy_2d);
calc1DOvlp(LA, Az, expA, LB, Bz, mu, Sz);
Sx2.block(0,0,LA+1, LB+1).setZero();
Sy_2d2.block(0,0,LA+1, LB+1).setZero();
Sz2.block(0,0,LA+1, LB+1).setZero();
double commonFactor = sqrt(M_PI/(expB+expG));
double f = sqrt(2. * (expB+expG));
for (int j=0; j <= LB; j++) {
for (int n = 0; n <= j; n++) {
if ( (j-n)%2 != 0) continue;
double factor = nChoosek(j, n) * pow(expG/(expG+expB), n)
* doubleFact(j - n - 1)/pow(f, 1.*j-1.*n) * commonFactor;
for (int i=0; i <= LA; i++) {
Sx2(i, j) += factor * Sx(i, n);
Sy_2d2(i, j) += factor * Sy_2d(i, n);
Sz2(i, j) += factor * Sz(i, n);
}
}
}
int IA0 = (LA)*(LA+1)*(LA+2)/6;
int IB0 = (LB)*(LB+1)*(LB+2)/6;
normA *= 1.0/sqrt( doubleFact(2*LA-1)/pow(4*expA, LA))
/ pow(M_PI/2./expA, 0.75);// * sqrt(4* M_PI/ (2*LA+1));
if (LA >=2) normA = normA * sqrt(4* M_PI/ (2*LA+1));
normB *= 1.0/sqrt( doubleFact(2*LB-1)/pow(4*expB, LB))
/ pow(M_PI/2./expB, 0.75);// * sqrt(4 * M_PI / (2*LB+1));
if (LB >=2) normB = normB * sqrt(4 * M_PI / (2*LB+1));
for (int i=0; i<(LA+1)*(LA+2)/2; i++)
for (int j=0; j<(LB+1)*(LB+2)/2; j++) {
auto ipow = CartOrder[IA0 + i];
auto jpow = CartOrder[IB0 + j];
Int(i, j) += Sx2(ipow[0], jpow[0]) *
Sy_2d2(ipow[1], jpow[1]) *
Sz2(ipow[2], jpow[2]) * normA * normB * wtG;
}
}
*/
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include "igl/slice.h"
#include "igl/slice_into.h"
#include "Determinants.h"
#include "MultiSlater.h"
#include "global.h"
#include "input.h"
using namespace Eigen;
MultiSlater::MultiSlater()
{
initHforbs();
initCiExpansion();
}
void MultiSlater::initHforbs()
{
ifstream dump("hf.txt");
if (dump) {
int norbs = Determinant::norbs;
Hforbs = MatrixXcd::Zero(2*norbs, 2*norbs);
readMat(Hforbs, "hf.txt");
if (schd.ifComplex && Hforbs.imag().isZero(0)) Hforbs.imag() = 0.1 * MatrixXd::Random(2*norbs, 2*norbs) / norbs;
}
}
void MultiSlater::initCiExpansion()
{
string fname = "dets";
if (schd.ghfDets) readDeterminantsGHF(fname, ref, open, ciExcitations, ciParity, ciCoeffs);
else readDeterminants(fname, ref, open, ciExcitations, ciParity, ciCoeffs);
numDets = ciCoeffs.size();
}
void MultiSlater::getVariables(Eigen::VectorBlock<VectorXd> &v) const
{
int norbs = Determinant::norbs;
for (size_t i = 0; i < numDets; i++) v[i] = ciCoeffs[i];
for (int i = 0; i < 2*norbs; i++) {
for (int j = 0; j < 2*norbs; j++) {
v[numDets + 4 * i * norbs + 2 * j] = Hforbs(i, j).real();
v[numDets + 4 * i * norbs + 2 * j + 1] = Hforbs(i, j).imag();
}
}
}
size_t MultiSlater::getNumVariables() const
{
return numDets + 2 * Hforbs.rows() * Hforbs.rows();
}
void MultiSlater::updateVariables(const Eigen::VectorBlock<VectorXd> &v)
{
int norbs = Determinant::norbs;
for (size_t i = 0; i < numDets; i++) ciCoeffs[i] = v[i];
for (int i = 0; i < 2*norbs; i++) {
for (int j = 0; j < 2*norbs; j++) {
Hforbs(i, j) = std::complex<double>(v[numDets + 4 * i * norbs + 2 * j], v[numDets + 4 * i * norbs + 2 * j + 1]);
}
}
}
void MultiSlater::printVariables() const
{
cout << "\nciCoeffs\n";
for (size_t i = 0; i < numDets; i++) cout << ciCoeffs[i] << endl;
cout << "\nHforbs\n";
for (int i = 0; i < Hforbs.rows(); i++) {
for (int j = 0; j < Hforbs.rows(); j++) cout << " " << Hforbs(i, j);
cout << endl;
}
cout << endl;
}
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
void ReorderData1A( FScalar *RESTRICT pOut, FScalar *RESTRICT pIn,
FArraySizes const &StridesOut, FArraySizes const &Sizes, FScalar DataFactor,
bool AddToDest, bool InToOut, FArraySizes const *pStridesIn );
<file_sep>#include <iostream>
#include <cmath>
#include "primitives.h"
#include "workArray.h"
using namespace std;
extern "C" {
double exp_cephes(double x);
}
double nChoosek( size_t n, size_t k )
{
if (k > n) return 0.;
if (k * 2 > n) k = 1.*(n-k);
if (k == 0) return 1.;
double result = 1.*n;
for( int i = 2; i <= k; ++i ) {
result *= (n-i+1);
result /= i;
}
return result;
}
double doubleFact(size_t n) {
if (n == -1) return 1.;
double val = 1.0;
int limit = n/2;
for (int i=0; i<limit; i++)
val *= (n-2*i);
return val;
}
//calculates the entire matrix \Omega_{ij} i,j<=max(n1,n2)
double calc1DOvlp(int n1, double A, double expA,
int n2, double B, double expB,
tensor& S) {
double p = expA + expB,
P = (expA * A + expB * B)/(expA + expB),
mu = expA * expB / (expA + expB);
if (mu*(A-B)*(A-B) > 40.) {
return 0.0;
}
S(0,0) = sqrt(M_PI/p) * exp(-mu * (A-B) * (A-B));
if (n1 == 0 && n2 == 0) return S(0,0);
double f = 1./2./p;
for (int L = 0; L< max(n1, n2); L++) {
for (int i=0; i<= L; i++) {
S(i, L+1) = (P-B) * S(i,L) ;
S(i, L+1) += L != 0 ? L * S(i, L-1)*f : 0.;
S(i, L+1) += i != 0 ? i * S(i-1, L)*f : 0.;
}
for (int j=0; j<= L+1; j++) {
S(L+1, j) = (P-A) * S(L, j) ;
S(L+1, j) += L != 0 ? L * S(L-1, j)*f : 0.;
S(L+1, j) += j != 0 ? j * S(L, j-1)*f : 0.;
}
}
return S(n1, n2);
}
//actually it is \sqrt(pi/t) Theta3[0, exp(-pi*pi/t)]
double JacobiTheta(double z, double t, bool includeZero ) {
double result = 0.0;
if (t > 3.5) {//then do summation in direct space
double prefactor = sqrt(t/M_PI);
double Z = z/M_PI;
Z = fmod(Z, 1.0) ; Z = Z < 0.0 ? 1.0 + Z : Z; //make sure that Z is between 0 and 1;
for (int n = 0; n<=100; n++) {
double term = exp(-t*(Z-n)*(Z-n));
if (n != 0) term += exp(-t*(Z+n)*(Z+n));
result += term ;
if (abs(term) < 1.e-12) break;
}
if (!includeZero) result -= 1.0/prefactor;
return result*prefactor;
}
else {
double expt = exp(-M_PI*M_PI/t);
int k0 = includeZero ? 0 : 1;
for (int k = k0; k<=100; k++) {
double term = pow(expt, k*k) * cos(2*k*z);
result += k==0 ? term : 2*term;
if (abs(term) < 1.e-12) break;
}
return result;
}
}
void JacobiThetaDerivative(double z, double t, double* workArray, int nderiv, bool includeZero ) {
//zero out all the derivatives
std::fill(workArray, workArray+ 2*(nderiv+1), 0.0);
if (t > 3.5) {//then do summation in direct space
double prefactor = sqrt(t/M_PI);
double Z = z/M_PI;
Z = fmod(Z, 1.0) ; Z = Z < 0.0 ? 1.0 + Z : Z; //make sure that Z is between 0 and 1;
double* intermediate = workArray + nderiv+1;
double expt1 = exp(-t * Z * Z); double expt2 = expt1;//exp(-t * (Z+n) * (Z+n));
for (int n = 0; n<=10; n++) {
//do for positive n
double nAB = Z - n;
intermediate[0] = expt1;
if (nderiv >= 1)
intermediate[1] = -expt1 * nAB * 2 * t;
for (int k = 2; k <= nderiv; k++)
intermediate[k] = -2 * t * (intermediate[k-2] + nAB * intermediate[k-1])/k;
double factorial = 1.0;
workArray[0] += intermediate[0];
for (int k = 1; k <= nderiv; k++) {
factorial *= k/M_PI;
workArray[k] += factorial * intermediate[k];
}
//if n is not zero then do the summation for negative n
if (n != 0) {
nAB = Z + n;
expt2 = exp(-t * nAB * nAB);
intermediate[0] = expt2;
if (nderiv >= 1)
intermediate[1] = -expt2 * nAB * 2 * t;
for (int k = 2; k <= nderiv; k++)
intermediate[k] = -2 * t * (intermediate[k-2] + nAB * intermediate[k-1])/k;
double factorial = 1.0;
workArray[0] += intermediate[0];
for (int k = 1; k <= nderiv; k++) {
factorial *= k/M_PI;
workArray[k] += factorial * intermediate[k];
}
}
expt1 = exp(-t * (Z - n -1)*(Z-n-1)); expt2 = exp(-t * (Z -n +1) * (Z-n+1));
if (expt1 < 1.e-12 && expt2 < 1.e-12) break;
}
workArray[0] = includeZero ? workArray[0] * prefactor : (workArray[0] - 1.0/prefactor) * prefactor;
for (int i=1; i<=nderiv; i++)
workArray[i] *= prefactor;
}
else {
double expt = exp(-M_PI*M_PI/t);
int n0 = includeZero ? 0 : 1;
for (int n = n0; n<=100; n++) {
double exptPown = pow(expt, n*n);
workArray[0] += exptPown * cos(2*z*n) * (n==0 ? 1. : 2.);
if (n > 0) {
for (int k = 1; k<=nderiv; k++)
workArray[k] += 2 * pow(2*n, k) * exptPown * cos(k*M_PI/2 + 2*z*n);
}
//multiply current term with an additional expt to estimate the next term
if (abs(exptPown*pow(2*M_PI,nderiv)*pow(expt,2*n+1)) < 1.e-12) break;
}
}
}
//calculates the entire matrix \Omega_{ij} i,j<=max(n1,n2)
double calc1DOvlpPeriodic(int n1, double A, double a,
int n2, double B, double b, double t,
int AdditionalDeriv, double L,
tensor& S, double* workArray,
tensor& powPiOverL, tensor& pow1OverExpA,
tensor& pow1OverExpB) {
double z = (A-B) * M_PI/L ;
JacobiThetaDerivative(z, t*L*L, &workArray[0], (n1+n2+AdditionalDeriv), true);
//convert derivatives of gaussian to polynomial times gaussians
for (int i = 0; i <= n1; i++) {
for (int j = 0; j <= n2+AdditionalDeriv; j++) {
S(i, j) = 0.0;
for (int ii = i%2; ii <= i; ii+=2)
for (int jj = j%2; jj <= j; jj+=2) {
S(i, j) += (jj%2 == 0 ? 1 : -1) * DerivativeToPolynomial(i, ii) *
DerivativeToPolynomial(j, jj) *
workArray[ii+jj] * pow1OverExpA( (i+ii)/2) *
pow1OverExpB( (j+jj)/2) * powPiOverL( jj+ii);
/*S(i, j) += DerivativeToPolynomial(i, ii) *
DerivativeToPolynomial(j, jj) *
workArray[ii+jj] *
pow(-1, jj) * pow(1./a, (i + ii)/2) * pow(1./b, (j+jj)/2)
* pow(M_PI/L, ii+jj);
*/
}
}
}
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef runFCIQMC_HEADER_H
#define runFCIQMC_HEADER_H
#include "dataFCIQMC.h"
#include "excitGen.h"
#include "semiStoch.h"
#include "spawnFCIQMC.h"
#include "utilsFCIQMC.h"
#include "walkersFCIQMC.h"
template<typename Wave, typename TrialWalk>
void initFCIQMC(Wave& wave, TrialWalk& walk,
const int norbs, const int nel, const int nalpha, const int nbeta,
Determinant& HFDet, double& HFEnergy, heatBathFCIQMC& hb,
walkersFCIQMC<TrialWalk>& walkers, spawnFCIQMC& spawn,
semiStoch& core, workingArray& work);
template<typename Wave, typename TrialWalk>
void initWalkerListHF(Wave& wave, TrialWalk& walk, walkersFCIQMC<TrialWalk>& walkers,
spawnFCIQMC& spawn, semiStoch& core, workingArray& work,
Determinant& HFDet, const int DetLenMin);
template<typename Wave, typename TrialWalk>
void initWalkerListTrialWF(Wave& wave, TrialWalk& walk, walkersFCIQMC<TrialWalk>& walkers,
spawnFCIQMC& spawn, workingArray& work);
template<typename Wave, typename TrialWalk>
void runFCIQMC(Wave& wave, TrialWalk& walk, const int norbs, const int nel,
const int nalpha, const int nbeta);
template<typename Wave, typename TrialWalk>
void attemptSpawning(Wave& wave, TrialWalk& walk, Determinant& parentDet, Determinant& childDet,
spawnFCIQMC& spawn, oneInt &I1, twoInt &I2, double& coreE, const int nAttemptsEach,
const double parentAmp, const int parentFlags, const int iReplica,
const double tau, const double minSpawn, const double pgen,
const int ex1, const int ex2);
template<typename Wave, typename TrialWalk>
void performDeath(const int iDet, walkersFCIQMC<TrialWalk>& walkers, oneInt &I1, twoInt &I2,
double& coreE, const vector<double>& Eshift, const double tau);
template<typename Wave, typename TrialWalk>
void performDeathAllWalkers(walkersFCIQMC<TrialWalk>& walkers, oneInt &I1, twoInt &I2,
double& coreE, const vector<double>& Eshift, const double tau);
template<typename Wave, typename TrialWalk>
void calcVarEnergy(walkersFCIQMC<TrialWalk>& walkers, const spawnFCIQMC& spawn, const oneInt& I1,
const twoInt& I2, double& coreE, const double tau,
double& varEnergyNum, double& varEnergyDenom);
template<typename Wave, typename TrialWalk>
void calcEN2Correction(walkersFCIQMC<TrialWalk>& walkers, const spawnFCIQMC& spawn, const oneInt& I1,
const twoInt& I2, double& coreE, const double tau, const double varEnergyNum,
const double varEnergyDenom, double& EN2All);
void communicateEstimates(dataFCIQMC& dat, const int nDets, const int nSpawnedDets, int& nDetsTot,
int& nSpawnedDetsTot);
void updateShift(vector<double>& Eshift, vector<bool>& varyShift, const vector<double>& walkerPop,
const vector<double>& walkerPopOld, const double targetPop,
const double shiftDamping, const double tau);
void printDataTableHeader();
void printDataTable(const dataFCIQMC& dat, const int iter, const int nDets, const int nSpawned,
const double iter_time);
void printFinalStats(const vector<double>& walkerPop, const int nDets,
const int nSpawnDets, const double total_time);
#endif
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef CX_PODARRAY_H
#define CX_PODARRAY_H
#include <string.h> // for memcpy
#include <stdlib.h> // for malloc/free
#include "iostream"
#include "CxDefs.h"
namespace ct {
// swap two primitive values. Here such that we need not include <algorithm> here.
template<class FType>
void swap1(FType &A, FType &B){
FType t = A; A = B; B = t;
}
// A dynamic array of POD (``plain old data'') types that can be
// copied via a memcpy. Main point for this is that std::vector does not
// allow containing C-style arrays (e.g., double [3]), because C-style
// arrays are not assignable. Additionally, std::vector can be *very* slow
// when allocating large amounts of data, because that data is set to
// zero on resize. This class explicitly does not do that: It has RAII
// semantics, but non-explicitly touched data is just random.
//
// It is effectively a 'buffer-ptr + size' pair.
template<class FType>
struct TArray
{
typedef FType *iterator;
typedef FType const *const_iterator;
typedef ::size_t size_type;
iterator begin() { return m_pData; }
iterator end() { return m_pDataEnd; }
const_iterator begin() const { return m_pData; }
const_iterator end() const { return m_pDataEnd; }
FType &front() { return *m_pData; }
FType &back() { return *(m_pDataEnd-1); }
FType const &front() const { return *m_pData; }
FType const &back() const { return *(m_pDataEnd-1); }
FType &operator[] (size_type i) { return m_pData[i]; }
FType const &operator[] (size_type i) const { return m_pData[i]; }
size_type size() const { return m_pDataEnd - m_pData; }
bool empty() const { return m_pData == m_pDataEnd; }
// WARNING: contrary to std::vector, this function *DOES NOT*
// initialize (or touch, for that matter) the newly created data.
// If you want that behavior, use the other resize function.
void resize(size_type n) {
reserve(n);
m_pDataEnd = m_pData + n;
};
void resize(size_type n, FType t) {
size_type old_size = size();
resize(n);
if ( old_size < n ) {
for ( size_type i = old_size; i < n; ++ i )
m_pData[i] = t;
}
};
void clear() {
::free(m_pData);
m_pData = 0;
m_pDataEnd = 0;
m_pReservedEnd = 0;
};
// memset the entire array to 0.
void clear_data() {
memset(m_pData, 0, sizeof(FType)*size());
};
void resize_and_clear(size_type n) {
resize(n);
clear_data();
}
void push_back( FType const &t ) {
if ( size() + 1 > static_cast<size_type>(m_pReservedEnd - m_pData) ) {
reserve(2 * size() + 1);
}
m_pDataEnd[0] = t;
++m_pDataEnd;
};
void pop_back() {
assert(!empty());
m_pDataEnd -= 1;
}
void reserve(size_type n) {
if ( static_cast<size_type>(m_pReservedEnd - m_pData) < n ) {
FType *pNewData = static_cast<FType*>(::malloc(sizeof(FType) * n));
size_type
nSize = size();
if ( nSize != 0 )
::memcpy(pNewData, m_pData, sizeof(FType) * nSize);
::free(m_pData);
m_pData = pNewData;
m_pDataEnd = m_pData + nSize;
m_pReservedEnd = m_pData + n;
}
};
TArray()
: m_pData(0), m_pDataEnd(0), m_pReservedEnd(0)
{}
TArray(TArray const &other)
: m_pData(0), m_pDataEnd(0), m_pReservedEnd(0)
{
*this = other;
};
// WARNING: array's content not initialized with this function!
// (with intention!)
explicit TArray(size_type n)
: m_pData(0), m_pDataEnd(0), m_pReservedEnd(0)
{
resize(n);
}
TArray(size_type n, FType t)
: m_pData(0), m_pDataEnd(0), m_pReservedEnd(0)
{
resize(n);
for ( size_type i = 0; i < n; ++ i )
m_pData[i] = t;
}
~TArray() {
::free(m_pData);
m_pData = 0;
}
void operator = (TArray const &other) {
resize(other.size());
memcpy(m_pData, other.m_pData, sizeof(FType) * size());
};
void swap(TArray &other) {
swap1(m_pData, other.m_pData);
swap1(m_pDataEnd, other.m_pDataEnd);
swap1(m_pReservedEnd, other.m_pReservedEnd);
};
template<class FRandomIt>
void assign(FRandomIt begin, FRandomIt end){
resize(end - begin);
for ( size_type i = 0; i < size(); ++ i )
m_pData[i] = begin[i];
}
private:
FType
// start of controlled array. may be 0 if no data is contained.
*m_pData,
// end of actual data
*m_pDataEnd,
// end of reserved space (i.e., of the space *this owns)
*m_pReservedEnd;
};
} // namespace ct
namespace std {
template<class FType>
void swap( ct::TArray<FType> &A, ct::TArray<FType> &B ) {
A.swap(B);
}
}
#endif // CX_PODARRAY_H
<file_sep>#ifndef semiStoch_HEADER_H
#define semiStoch_HEADER_H
#include <fstream>
#include <string>
#include <vector>
#include "Determinants.h"
#include "walkersFCIQMC.h"
#include "utilsFCIQMC.h"
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
class semiStoch {
public:
// True if this instance is being used in a semi-stochastic
// FCIQMC simulation (if init has been called)
bool doingSemiStoch;
// The number of determinants in the core space
int nDets;
// The number of determinants in the core space on this process
int nDetsThisProc;
// The number of determinants and displacements for each process -
// these is used in MPI communications.
int* determSizes;
int* determDispls;
// The list of determinants in the core space
vector<simpleDet> dets;
// The list of determinants in the core space on this process
vector<simpleDet> detsThisProc;
// Holds the CI coefficients read in from the selected CI calculation
vector<double> sciAmps;
// The number of replica simulations, which determines the width of
// amps and ampsFull
int nreplicas;
// Used to hold the walker amplitudes of the core determinants, and
// also to store the ouput of the projection each iteration
double** amps;
// Used to hold all walker amplitudes from all core determinants,
// which is obtained by gathering the values in amps before projection
double** ampsFull;
// The positions of the core determinants in the main walker list
vector<int> indices;
// Deterministic flags of the walkers in the main walker list
vector<int> flags;
// Hash table to find the position of a determinant in dets
unordered_map<simpleDet, int, boost::hash<simpleDet>> ht;
// The positions of non-zero elements in the core Hamiltonian.
// pos[i,j] is the j'th non-zero column index in row i.
vector<vector<int>> pos;
// The values of the non-zero elements in the core Hamiltonian.
// ham[i,j] is the j'th non-zero element in row i.
vector<vector<double>> ham;
semiStoch() {
doingSemiStoch = false;
}
template<typename Wave, typename TrialWalk>
void init(std::string SHCIFile, Wave& wave, TrialWalk& walk,
walkersFCIQMC<TrialWalk>& walkers, int DetLenMin,
int nreplicasLocal, bool importanceSampling,
bool semiStochInit, double targetPop, workingArray& work) {
doingSemiStoch = true;
nDets = 0;
nDetsThisProc = 0;
nreplicas = nreplicasLocal;
ifstream dump(SHCIFile.c_str());
int index = 0;
double bestCoeff = 0.0;
int orbsToLoopOver;
int offset;
orbsToLoopOver = Determinant::norbs;
// Loop through all lines in the SHCI file
while (dump.good()) {
std::string Line;
std::getline(dump, Line);
boost::trim_if(Line, boost::is_any_of(", \t\n"));
vector<string> tok;
boost::split(tok, Line, boost::is_any_of(", \t\n"), boost::token_compress_on);
if (tok.size() > 2 ) {
double ci = atof(tok[0].c_str());
Determinant det ;
for (int i=0; i<orbsToLoopOver; i++)
{
if (boost::iequals(tok[1+i], "2")) {
det.setoccA(i, true);
det.setoccB(i, true);
}
else if (boost::iequals(tok[1+i], "a")) {
det.setoccA(i, true);
det.setoccB(i, false);
}
if (boost::iequals(tok[1+i], "b")) {
det.setoccA(i, false);
det.setoccB(i, true);
}
if (boost::iequals(tok[1+i], "0")) {
det.setoccA(i, false);
det.setoccB(i, false);
}
}
nDets += 1;
int proc = getProc(det, DetLenMin);
// If the determinant belongs to this process, store it
if (proc == commrank) {
nDetsThisProc += 1;
detsThisProc.push_back(det.getSimpleDet());
sciAmps.push_back(ci);
}
}
}
// Finished looping over the SHCI file
// Next we need to accumualte the core determinants from each
// process, in the correct order (proc 0 dets, proc 1 dets, etc.)
determSizes = new int[commsize];
determDispls = new int[commsize];
#ifdef SERIAL
determSizes[0] = nDetsThisProc;
#else
MPI_Allgather(&nDetsThisProc, 1, MPI_INTEGER, determSizes, 1,
MPI_INTEGER, MPI_COMM_WORLD);
#endif
determDispls[0] = 0;
for (int i = 1; i<commsize; i++) {
determDispls[i] = determDispls[i-1] + determSizes[i-1];
}
int determSizesDets[commsize];
int determDisplsDets[commsize];
for (int i=0; i<commsize; i++) {
determSizesDets[i] = determSizes[i] * 2*DetLen;
determDisplsDets[i] = determDispls[i] * 2*DetLen;
}
// Gather the determinants into the dets array
dets.resize(nDets);
#ifdef SERIAL
for (int i=0; i<nDetsThisProc; i++) {
dets[i] = detsThisProc[i];
}
#else
MPI_Allgatherv(&detsThisProc.front(), nDetsThisProc*2*DetLen, MPI_LONG,
&dets.front(), determSizesDets, determDisplsDets,
MPI_LONG, MPI_COMM_WORLD);
#endif
// Create the hash table, mapping determinants to their position
// in the full list of core determinants
for (int i=0; i<nDets; i++) {
ht[ dets[i] ] = i;
}
if (importanceSampling) {
createCoreHamil_IS(wave, walk);
} else {
createCoreHamil();
}
// Create arrays that will store the walker amplitudes in the
// core space
amps = allocateAmpsArray(nDetsThisProc, nreplicas, 0.0);
ampsFull = allocateAmpsArray(nDets, nreplicas, 0.0);
// If true, then initialise from the SCI wave function
if (semiStochInit) {
if (importanceSampling) {
setAmpsToSCIWF_IS(wave, walk, targetPop);
} else {
setAmpsToSCIWF(targetPop);
}
}
indices.resize(nDetsThisProc, 0);
// Add the core determinants to the main list with zero amplitude
addCoreDetsToMainList(wave, walk, walkers, work);
}
void setAmpsToSCIWF(double targetPop) {
// Set the amplitudes to those from the read-in SCI wave function
// Find the total population
double totPop = 0.0, totPopAll = 0.0;
for (int i=0; i<nDetsThisProc; i++) {
totPop += abs(sciAmps[i]);
}
#ifdef SERIAL
totPopAll = totPop;
#else
MPI_Allreduce(&totPop, &totPopAll, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
// Factor to scale up the amplitudes to the correct initial
// walker population
double fac = targetPop/totPopAll;
for (int i=0; i<nDetsThisProc; i++) {
for (int j=0; j<nreplicas; j++) {
amps[i][j] = sciAmps[i] * fac;
}
}
}
template<typename Wave, typename TrialWalk>
void setAmpsToSCIWF_IS(Wave& wave, TrialWalk& walk, double targetPop) {
// Set the amplitudes to those from the read-in SCI wave function.
// This uses the importance sampled Hamiltonian, where the amplitudes
// should be C_i * psi_i^T, i.e. they include a factor from the trial
// wave function, psi_i^T, also.
// Find the total population
double totPop = 0.0, totPopAll = 0.0;
for (int i=0; i<nDetsThisProc; i++) {
Determinant det_i(detsThisProc[i]);
TrialWalk walk_i(wave, det_i);
double ovlp = wave.Overlap(walk_i);
totPop += abs(sciAmps[i]*ovlp);
}
#ifdef SERIAL
totPopAll = totPop;
#else
MPI_Allreduce(&totPop, &totPopAll, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
// Factor to scale up the amplitudes to the correct initial
// walker population
double fac = targetPop/totPopAll;
for (int i=0; i<nDetsThisProc; i++) {
Determinant det_i(detsThisProc[i]);
TrialWalk walk_i(wave, det_i);
double ovlp = wave.Overlap(walk_i);
for (int j=0; j<nreplicas; j++) {
amps[i][j] = sciAmps[i] * ovlp * fac;
}
}
}
template<typename Wave, typename TrialWalk>
void addCoreDetsToMainList(Wave& wave, TrialWalk& walk,
walkersFCIQMC<TrialWalk>& walkers,
workingArray& work) {
for (int i = 0; i<nDetsThisProc; i++) {
Determinant det_i = Determinant(detsThisProc[i]);
// Is this spawned determinant already in the main list?
if (walkers.ht.find(det_i) != walkers.ht.end()) {
int iDet = walkers.ht[det_i];
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
double oldAmp = walkers.amps[iDet][iReplica];
double newAmp = amps[i][iReplica] + oldAmp;
walkers.amps[iDet][iReplica] = newAmp;
}
}
else
{
// New determinant
int pos = walkers.nDets;
walkers.dets[pos] = det_i;
walkers.diagH[pos] = det_i.Energy(I1, I2, coreE);
TrialWalk newWalk(wave, det_i);
double ovlp, localE, SVTotal;
wave.HamAndOvlpAndSVTotal(newWalk, ovlp, localE, SVTotal, work,
schd.epsilon);
walkers.ovlp[pos] = ovlp;
walkers.localE[pos] = localE;
walkers.SVTotal[pos] = SVTotal;
walkers.trialWalk[pos] = newWalk;
// Add in the new walker population
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
walkers.amps[pos][iReplica] = amps[i][iReplica];
}
walkers.ht[det_i] = pos;
walkers.nDets += 1;
}
}
}
template<typename TrialWalk>
void copyWalkerAmps(walkersFCIQMC<TrialWalk>& walkers) {
// Run through the main list and copy the core amplitudes to the
// core.amps array. This is needed for printing the correct stats
// in the first iteration, for some cases.
int nCoreFound = 0;
for (int iDet=0; iDet<walkers.nDets; iDet++) {
simpleDet det_i = walkers.dets[iDet].getSimpleDet();
if (ht.find(det_i) != ht.end()) {
for (int iReplica=0; iReplica<schd.nreplicas; iReplica++) {
amps[nCoreFound][iReplica] = walkers.amps[iDet][iReplica];
}
// Store the position of this core determinant in the main list
indices[nCoreFound] = iDet;
nCoreFound += 1;
}
}
}
~semiStoch() {
if (doingSemiStoch) {
delete[] determSizes;
delete[] determDispls;
dets.clear();
detsThisProc.clear();
sciAmps.clear();
deleteAmpsArray(amps);
deleteAmpsArray(ampsFull);
indices.clear();
flags.clear();
ht.clear();
for (auto pos_i: pos) {
pos_i.clear();
}
pos.clear();
for (auto ham_i: ham) {
ham_i.clear();
}
ham.clear();
}
}
void createCoreHamil() {
// These will be used to hold the positions and elements
// for each row of the core Hamiltonian
vector<int> tempPos;
vector<double> tempHam;
for (int i=0; i<nDetsThisProc; i++) {
Determinant det_i(detsThisProc[i]);
for (int j=0; j<nDets; j++) {
Determinant det_j(dets[j]);
double HElem = 0.0;
if (det_i == det_j) {
// Don't include the diagonal contributions - these are
// taken care of in the death step
HElem = 0.0;
} else {
HElem = Hij(det_i, det_j, I1, I2, coreE);
}
if (abs(HElem) > 1.e-12) {
tempPos.push_back(j);
tempHam.push_back(HElem);
}
}
// Add the elements for this row to the arrays
pos.push_back(tempPos);
ham.push_back(tempHam);
tempPos.clear();
tempHam.clear();
}
}
template<typename Wave, typename TrialWalk>
void createCoreHamil_IS(Wave& wave, TrialWalk& walk) {
// These will be used to hold the positions and elements
// for each row of the core Hamiltonian
vector<int> tempPos;
vector<double> tempHam;
for (int i=0; i<nDetsThisProc; i++) {
Determinant det_i(detsThisProc[i]);
TrialWalk walk_i(wave, det_i);
for (int j=0; j<nDets; j++) {
Determinant det_j(dets[j]);
double HElem = 0.0;
if (det_i == det_j) {
// Don't include the diagonal contributions - these are
// taken care of in the death step
HElem = 0.0;
} else {
HElem = Hij(det_i, det_j, I1, I2, coreE);
}
if (abs(HElem) > 1.e-12) {
// Apply importane sampling factor
HElem /= wave.getOverlapFactor(walk_i, det_j, true);
tempPos.push_back(j);
tempHam.push_back(HElem);
}
}
// Add the elements for this row to the arrays
pos.push_back(tempPos);
ham.push_back(tempHam);
tempPos.clear();
tempHam.clear();
}
}
void determProjection(double tau) {
int determSizesAmps[commsize];
int determDisplsAmps[commsize];
for (int i=0; i<commsize; i++) {
determSizesAmps[i] = determSizes[i] * nreplicas;
determDisplsAmps[i] = determDispls[i] * nreplicas;
}
#ifdef SERIAL
for (int i=0; i<nDetsThisProc; i++) {
for (int j=0; j<nreplicas; j++) {
ampsFull[i][j] = amps[i][j];
}
}
#else
MPI_Allgatherv(&s[0][0], nDetsThisProc*nreplicas, MPI_DOUBLE,
&sFull[0][0], determSizesAmps, determDisplsAmps,
MPI_DOUBLE, MPI_COMM_WORLD);
#endif
// Zero the amps array, which will be used for accumulating the
// results of the projection
for (int iDet=0; iDet<nDetsThisProc; iDet++) {
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
amps[iDet][iReplica] = 0.0;
}
}
// Perform the multiplication by the core Hamiltonian
for (int iDet=0; iDet<nDetsThisProc; iDet++) {
for (int jDet=0; jDet < pos[iDet].size(); jDet++) {
int colInd = pos[iDet][jDet];
double HElem = ham[iDet][jDet];
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
amps[iDet][iReplica] -= HElem * ampsFull[colInd][iReplica];
}
}
}
// Now multiply by the time step to get the final projected vector
for (int iDet=0; iDet<nDetsThisProc; iDet++) {
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
amps[iDet][iReplica] *= tau;
}
}
}
void determAnnihilation(double** walkerAmps, vector<double> nAnnihil) {
for (int iDet=0; iDet<nDetsThisProc; iDet++) {
// The position of this core determinant in the main list
int ind = indices[iDet];
for (int iReplica=0; iReplica<nreplicas; iReplica++) {
// Add the deterministic projection amplitudes into the main
// walker list amplitudes
if (walkerAmps[ind][iReplica]*amps[iDet][iReplica] < 0.0) {
nAnnihil[iReplica] += 2.0*min(abs(walkerAmps[ind][iReplica]), abs(amps[iDet][iReplica]));
}
walkerAmps[ind][iReplica] += amps[iDet][iReplica];
}
}
}
};
#endif
<file_sep>import numpy as np
import math
from pyscf import gto, scf, ao2mo, mcscf, tools, fci, mp
#from pyscf.shciscf import shci, settings
from pyscf.lo import pipek, boys
import sys
from scipy.linalg import fractional_matrix_power
UHF = False
r = float(sys.argv[1])*0.529177
n = 20
norb = 20
order = 2
sqrt2 = 2**0.5
atomstring = ""
for i in range(n):
atomstring += "H 0 0 %g\n"%(i*r)
mol = gto.M(
atom = atomstring,
basis = 'sto-6g',
verbose=4,
symmetry=0,
spin = 0)
mf = scf.RHF(mol)
if (UHF) :
mf = scf.UHF(mol)
print mf.kernel()
if UHF :
mocoeff = mf.mo_coeff[0]
else:
mocoeff = mf.mo_coeff
lowdin = fractional_matrix_power(mf.get_ovlp(mol), -0.5).T
lmo = pipek.PM(mol).kernel(lowdin)
h1 = lmo.T.dot(mf.get_hcore()).dot(lmo)
eri = ao2mo.kernel(mol, lmo)
tools.fcidump.from_integrals('FCIDUMP', h1, eri, norb, n, mf.energy_nuc())
#print the atom with which the lmo is associated
orbitalOrder = []
for i in range(lmo.shape[1]):
orbitalOrder.append(np.argmax(np.absolute(lmo[:,i])) )
print orbitalOrder
ovlp = mf.get_ovlp(mol)
uc = (mf.mo_coeff.T.dot(ovlp).dot(lmo)).T
if UHF:
uc2 = (mf.mo_coeff[1].T.dot(ovlp).dot(lmo)).T
else:
uc2 = uc
fileh = open("rhf.txt", 'w')
for i in range(norb):
for j in range(norb):
fileh.write('%16.10e '%(uc[i,j]))
fileh.write('\n')
fileh.close()
fileHF = open("uhf.txt", 'w')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(uc[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(uc2[i,j]))
fileHF.write('\n')
fileHF.close()
diag = np.zeros(shape=(norb,norb))
for i in range(norb/2):
diag[i,i] = 1.
pairMat = uc.dot(diag).dot(uc.T)
filePair = open("pairMatAGP.txt", 'w')
for i in range(norb):
for j in range(norb):
filePair.write('%16.10e '%(pairMat[i,j]))
filePair.write('\n')
filePair.close()
gmf = scf.GHF(mol)
gmf.max_cycle = 200
dm = gmf.get_init_guess()
dm = dm + np.random.rand(2*norb, 2*norb) / 3
print gmf.kernel(dm0 = dm)
uc1 = (gmf.mo_coeff[:norb, :norb].T.dot(ovlp).dot(lmo)).T
uc2 = (gmf.mo_coeff[:norb, norb:].T.dot(ovlp).dot(lmo)).T
uc3 = (gmf.mo_coeff[norb:, :norb].T.dot(ovlp).dot(lmo)).T
uc4 = (gmf.mo_coeff[norb:, norb:].T.dot(ovlp).dot(lmo)).T
fileHF = open("ghf.txt", 'w')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(uc1[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(uc2[i,j]))
fileHF.write('\n')
for i in range(norb):
for j in range(norb):
fileHF.write('%16.10e '%(uc3[i,j]))
for j in range(norb):
fileHF.write('%16.10e '%(uc4[i,j]))
fileHF.write('\n')
fileHF.close()
ghfCoeffs = np.block([[uc1, uc2], [uc3, uc4]])
theta = ghfCoeffs[::, :n]
amat = np.full((n, n), 0.)
for i in range(n/2):
amat[2 * i + 1, 2 * i] = -1.
amat[2 * i, 2 * i + 1] = 1.
pairMat = theta.dot(amat).dot(theta.T)
filePfaff = open("pairMatPfaff.txt", 'w')
for i in range(2*norb):
for j in range(2*norb):
filePfaff.write('%16.10e '%(pairMat[i,j]))
filePfaff.write('\n')
filePfaff.close()
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace MRLCC_CCVV {
FTensorDecl TensorDecls[31] = {
/* 0*/{"t", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "eecc", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"k", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"k", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"k", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"W", "caca", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 6*/{"W", "caac", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 7*/{"W", "cece", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 8*/{"W", "ceec", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 9*/{"W", "aeae", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 10*/{"W", "aeea", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 11*/{"W", "cccc", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 12*/{"W", "aaaa", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 13*/{"W", "e", "",USAGE_Intermediate, STORAGE_Memory},
/* 14*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"E3", "a", "",USAGE_Intermediate, STORAGE_Memory},
/* 17*/{"S1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 18*/{"S2", "aa", "",USAGE_Density, STORAGE_Memory},
/* 19*/{"T", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"b", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"p", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"Ap", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"P", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"AP", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 25*/{"B", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 26*/{"W", "eecc", "",USAGE_Hamiltonian, STORAGE_Disk},
/* 27*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 29*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 30*/{"t1", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
};
//Number of terms : 32
FEqInfo EqsRes[30] = {
{"abcd,ce,abde", 8.0 , 3, {22,2,21}}, //8.0 Ap[abcd] k[ce] p[abde]
{"abcd,ce,abed", -16.0 , 3, {22,2,21}}, //-16.0 Ap[abcd] k[ce] p[abed]
{"abcd,ae,becd", -8.0 , 3, {22,4,21}}, //-8.0 Ap[abcd] k[ae] p[becd]
{"abcd,ae,bedc", 16.0 , 3, {22,4,21}}, //16.0 Ap[abcd] k[ae] p[bedc]
{"abcd,cdef,abef", 8.0 , 3, {22,11,21}}, //8.0 Ap[abcd] W[cdef] p[abef]
{"abcd,cdef,abfe", -4.0 , 3, {22,11,21}}, //-4.0 Ap[abcd] W[cdef] p[abfe]
{"abcd,cegf,abdf,ge", -8.0 , 4, {22,11,21,27}}, //-8.0 Ap[abcd] W[cegf] p[abdf] delta[ge]
{"abcd,cegf,abfd,ge", 16.0 , 4, {22,11,21,27}}, //16.0 Ap[abcd] W[cegf] p[abfd] delta[ge]
{"abcd,cefg,abdf,ge", 16.0 , 4, {22,11,21,27}}, //16.0 Ap[abcd] W[cefg] p[abdf] delta[ge]
{"abcd,cefg,abfd,ge", -32.0 , 4, {22,11,21,27}}, //-32.0 Ap[abcd] W[cefg] p[abfd] delta[ge]
{"abcd,caef,bfde", -16.0 , 3, {22,7,21}}, //-16.0 Ap[abcd] W[caef] p[bfde]
{"abcd,caef,bfed", 8.0 , 3, {22,7,21}}, //8.0 Ap[abcd] W[caef] p[bfed]
{"abcd,cbef,afde", 8.0 , 3, {22,7,21}}, //8.0 Ap[abcd] W[cbef] p[afde]
{"abcd,cbef,afed", -16.0 , 3, {22,7,21}}, //-16.0 Ap[abcd] W[cbef] p[afed]
{"abcd,eagf,bfcd,ge", -16.0 , 4, {22,7,21,27}}, //-16.0 Ap[abcd] W[eagf] p[bfcd] delta[ge]
{"abcd,eagf,bfdc,ge", 32.0 , 4, {22,7,21,27}}, //32.0 Ap[abcd] W[eagf] p[bfdc] delta[ge]
{"abcd,eafc,bfde", 32.0 , 3, {22,8,21}}, //32.0 Ap[abcd] W[eafc] p[bfde]
{"abcd,eafc,bfed", -16.0 , 3, {22,8,21}}, //-16.0 Ap[abcd] W[eafc] p[bfed]
{"abcd,eafd,bfce", -16.0 , 3, {22,8,21}}, //-16.0 Ap[abcd] W[eafd] p[bfce]
{"abcd,eafd,bfec", 8.0 , 3, {22,8,21}}, //8.0 Ap[abcd] W[eafd] p[bfec]
{"abcd,eafg,bfcd,ge", 8.0 , 4, {22,8,21,27}}, //8.0 Ap[abcd] W[eafg] p[bfcd] delta[ge]
{"abcd,eafg,bfdc,ge", -16.0 , 4, {22,8,21,27}}, //-16.0 Ap[abcd] W[eafg] p[bfdc] delta[ge]
//{"abcd,abef,efcd", 8.0 , 3, {22,13,21}}, //8.0 Ap[abcd] W[abef] p[efcd]
//{"abcd,abef,efdc", -4.0 , 3, {22,13,21}}, //-4.0 Ap[abcd] W[abef] p[efdc]
{"abcd,eafg,bgcd,ef", -8.0 , 4, {22,9,21,14}}, //-8.0 Ap[abcd] W[eafg] p[bgcd] E1[ef]
{"abcd,eafg,bgdc,ef", 16.0 , 4, {22,9,21,14}}, //16.0 Ap[abcd] W[eafg] p[bgdc] E1[ef]
{"abcd,eafg,bfcd,eg", 4.0 , 4, {22,10,21,14}}, //4.0 Ap[abcd] W[eafg] p[bfcd] E1[eg]
{"abcd,eafg,bfdc,eg", -8.0 , 4, {22,10,21,14}}, //-8.0 Ap[abcd] W[eafg] p[bfdc] E1[eg]
{"abcd,cefg,abdf,eg", 8.0 , 4, {22,5,21,14}}, //8.0 Ap[abcd] W[cefg] p[abdf] E1[eg]
{"abcd,cefg,abfd,eg", -16.0 , 4, {22,5,21,14}}, //-16.0 Ap[abcd] W[cefg] p[abfd] E1[eg]
{"abcd,efgc,abde,fg", -4.0 , 4, {22,6,21,14}}, //-4.0 Ap[abcd] W[efgc] p[abde] E1[fg]
{"abcd,efgc,abed,fg", 8.0 , 4, {22,6,21,14}}, //8.0 Ap[abcd] W[efgc] p[abed] E1[fg]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[4] = {
{"CDKL,LM,CDKM", 2.0, 3, {20, 27, 26}},
{"CDKL,LM,DCKM",-1.0, 3, {20, 27, 26}},
{"CDKL,LM,CDMK",-1.0, 3, {20, 27, 26}},
{"CDKL,LM,DCMK", 2.0, 3, {20, 27, 26}},
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "MRLCC_CCVV";
Out.perturberClass = "CCVV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 31;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 0;
Out.EqsRes = FEqSet(&EqsRes[0], 30, "MRLCC_CCVV/Res");
Out.Overlap = FEqSet(&Overlap[0], 4, "MRLCC_CCVV/Overlap");
};
};
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DAVIDSON_HEADER_H
#define DAVIDSON_HEADER_H
#include <Eigen/Dense>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <vector>
#include <iostream>
#include "global.h"
using namespace Eigen;
using namespace std;
void GeneralizedEigen(MatrixXd& Hamiltonian, MatrixXd& Overlap, VectorXcd& eigenvalues, MatrixXcd& eigenvectors, VectorXd& betas);
void SelfAdjointEigen(MatrixXd& Overlap, VectorXd& eigenvalues, MatrixXd& eigenvectors);
void SolveEigen(MatrixXd& A, VectorXd& b, VectorXd& x);
#endif
<file_sep>import numpy as np
import math
from pyscf import gto, scf, ao2mo, mcscf, tools, fci, mp
#from pyscf.shciscf import shci, settings
from pyscf.lo import pipek, boys
import sys
from scipy.linalg import fractional_matrix_power
UHF = False
r = float(sys.argv[1])*0.529177
n = 10
order = 2
sqrt2 = 2**0.5
atomstring = ""
for i in range(n):
atomstring += "H 0 0 %g\n"%(i*r)
mol = gto.M(
atom = atomstring,
basis = 'sto-6g',
verbose=4,
symmetry=0,
spin = 0)
mf = scf.RHF(mol)
if (UHF) :
mf = scf.UHF(mol)
print mf.kernel()
if UHF :
mocoeff = mf.mo_coeff[0]
else:
mocoeff = mf.mo_coeff
lmo = fractional_matrix_power(mf.get_ovlp(mol), -0.5).T
#lmo = pipek.PM(mol).kernel(mocoeff)
h1 = lmo.T.dot(mf.get_hcore()).dot(lmo)
eri = ao2mo.kernel(mol, lmo)
tools.fcidump.from_integrals('FCIDUMP', h1, eri, 10, 10, mf.energy_nuc())
print mf.mo_coeff
print "local"
print lmo
#print the atom with which the lmo is associated
orbitalOrder = []
for i in range(lmo.shape[1]):
orbitalOrder.append(np.argmax(np.absolute(lmo[:,i])) )
print orbitalOrder
ovlp = mf.get_ovlp(mol)
uc = (mocoeff.T.dot(ovlp).dot(lmo)).T
#fileh = open("hf.txt", 'w')
#for i in range(10):
# for j in range(10):
# fileh.write('%16.10e '%(uc[i,j]))
# fileh.write('\n')
#fileh.close()
#fileHF = open("hf.txt", 'w')
#for i in range(10):
# for j in range(5):
# fileHF.write('%16.10e '%(uc[i,j]/sqrt2))
# for j in range(5):
# fileHF.write('%16.10e '%(uc[i,j]/sqrt2))
# for j in range(5):
# fileHF.write('%16.10e '%(uc[i,j+5]/sqrt2))
# for j in range(5):
# fileHF.write('%16.10e '%(uc[i,j+5]/sqrt2))
# fileHF.write('\n')
#for i in range(10):
# for j in range(5):
# fileHF.write('%16.10e '%(uc[i,j]/sqrt2))
# for j in range(5):
# fileHF.write('%16.10e '%(-uc[i,j]/sqrt2))
# for j in range(5):
# fileHF.write('%16.10e '%(uc[i,j+5]/sqrt2))
# for j in range(5):
# fileHF.write('%16.10e '%(-uc[i,j+5]/sqrt2))
# fileHF.write('\n')
#fileHF.close()
#
diag = np.zeros(shape=(10,10))
for i in range(5):
diag[i,i] = 1.
pairMat = uc.dot(diag).dot(uc.T)
randMat = np.random.rand(20,20)
randMat = (randMat - randMat.T)/10
filePfaff = open("pairMat.txt", 'w')
for i in range(n):
for j in range(n):
filePfaff.write('%16.10e '%(randMat[i,j]))
for j in range(n):
filePfaff.write('%16.10e '%(pairMat[i,j]+randMat[i,j+n]))
filePfaff.write('\n')
for i in range(n):
for j in range(n):
filePfaff.write('%16.10e '%(-pairMat[i,j]+randMat[i+n,j]))
for j in range(n):
filePfaff.write('%16.10e '%(randMat[i+n,j+n]))
filePfaff.write('\n')
filePfaff.close()
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
#include "CxNumpyArray.h"
#include "CxAlgebra.h"
#include "CxMemoryStack.h"
#include "CxPodArray.h"
#include "BlockContract.h"
#include "icpt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
using ct::TArray;
using ct::FMemoryStack2;
using boost::format;
using namespace std;
FNdArrayView ViewFromNpy(ct::FArrayNpy &A);
void FJobContext::ExecHandCoded(FMemoryStack2 *Mem)
{
if (0 == strcmp(MethodName.c_str(), "MRLCC_AAVV") ) {
FArrayOffset nact = TensorById(23)->Sizes[0];
FArrayOffset nvirt = TensorById(6)->Sizes[0];
void
*pBaseOfMemory = Mem[omprank].Alloc(0);
//{"abcd,abef,efgh,cdgh", 2.0 , 4, {6,20,4,22}}, //2.0 Ap[abcd] W[abef] p[efgh] E2[cdgh]
FScalar scaleA = 2.0, scaleB = 1.0, scaleC=0.0;
FScalar *intermediateD = Mem[0].AllocN(nvirt*nvirt*nact*nact, scaleA);
char T='t', N='n';
FArrayOffset nvirtsq = nvirt*nvirt, nactsq = nact*nact;
#ifdef _SINGLE_PRECISION
sgemm_(N, T, nvirtsq, nactsq, nactsq,
scaleA, TensorById(4)->pData, nvirtsq, TensorById(22)->pData, nactsq, scaleC, intermediateD, nvirtsq);
sgemm_(T, N, nvirtsq, nactsq, nvirtsq,
scaleB, TensorById(20)->pData, nvirtsq, intermediateD, nvirtsq, scaleB, TensorById(6)->pData, nvirtsq);
#else
dgemm_(N, T, nactsq, nvirtsq, nactsq,
scaleA, TensorById(22)->pData, nactsq, TensorById(4)->pData, nvirtsq, scaleC, intermediateD, nactsq);
SplitStackmem(Mem);
#pragma omp parallel
{
void
*pBaseOfMemorylocal = Mem[omprank].Alloc(0);
double *Wslice = Mem[omprank].AllocN(nvirt*nvirt*nvirt, scaleA);
for (int b=0; b<nvirt; b++) {
if (b%omp_get_num_threads() != omprank) continue;
char filename[700];
sprintf(filename, "int/W:eeee%04d", b);
FILE* f = fopen(filename, "rb");
fread(Wslice, sizeof(scaleA), nvirtsq*nvirt, f);
dgemm_(N, T, nvirt, nactsq, nvirtsq,
scaleB, Wslice, nvirt, intermediateD, nactsq, scaleB, &TensorById(6)->operator()(0,b,0,0), nvirtsq);
fclose(f);
}
Mem[omprank].Free(pBaseOfMemorylocal);
}
MergeStackmem(Mem);
#endif
Mem[omprank].Free(pBaseOfMemory);
FillData(16, Mem[0]);
FillData(17, Mem[0]);
//Allocate("W:aeae", Mem[0]);
//Allocate("W:aeea", Mem[0]);
SplitStackmem(Mem);
#pragma omp parallel
{
char Header0[10], Header[256];
FILE *f = fopen("int/E3.npy", "rb");
fread(&Header0[0], 1, 10, f);
uint16_t HeaderSize = (uint16_t)Header0[8] + (((uint16_t)Header0[9]) << 8);
//char Header0[10], Header[256];
//FILE *f = fopen("int/node0/spatial_threepdm.0.0.bin.unpack", "rb");
FNdArrayView E3slice, Apslice;
E3slice.pData=0;
E3slice.Sizes.clear(); E3slice.Strides.clear();
FArrayOffset Stride = 1;
for (int i=0; i<4; i++) {
E3slice.Sizes.push_back(nact);
E3slice.Strides.push_back(Stride);
Stride *= E3slice.Sizes.back();
}
Stride = 1;
Apslice.Sizes.clear(); Apslice.Strides.clear();
for (int i=0; i<2; i++) {
Apslice.Sizes.push_back(nvirt);
Apslice.Strides.push_back(Stride);
Stride *= Apslice.Sizes.back();
}
void
*pBaseOfMemory = Mem[omprank].Alloc(0);
FNdArrayView **pTs1; Mem[omprank].Alloc(pTs1, 4);
pTs1[0] = &Apslice;
pTs1[1] = TensorById(16);
pTs1[2] = TensorById(4);
pTs1[3] = &E3slice;
FNdArrayView **pTs2; Mem[omprank].Alloc(pTs2, 4);
pTs2[0] = &Apslice;
pTs2[1] = TensorById(17);
pTs2[2] = TensorById(4);
pTs2[3] = &E3slice;
FNdArrayView **pTs3; Mem[omprank].Alloc(pTs3, 4);
pTs3[0] = &Apslice;
pTs3[1] = TensorById(19);
pTs3[2] = TensorById(4);
pTs3[3] = &E3slice;
double temp=1.;
size_t nact4 = nact*nact*nact*nact, nact2=nact*nact;
double * E3slicedata = Mem[omprank].AllocN(nact4, temp);
for (size_t cd=0; cd<nact*nact; cd++) {
if (cd%omp_get_num_threads() != omprank) continue;
size_t c=cd/nact, d=cd%nact;
fseek(f, HeaderSize+10+(d+c*nact)*nact4*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact4, f);
//E3slice.pData = &TensorById(23)->operator()(0,0,0,0,d,c) ;
E3slice.pData = E3slicedata;
Apslice.pData = &TensorById(6)->operator()(0,0,c,d) ;
FScalar scale = 4.0;
ContractN(pTs3, "ab,efgh,abei,higf", -scale, true, Mem[omprank]);
ContractN(pTs2, "ab,eafg,bfhi,ihge", scale, true, Mem[omprank]);
ContractN(pTs1, "ab,eafg,bghi,fhie", scale, true, Mem[omprank]);
}
fclose(f);
Mem[omprank].Free(pBaseOfMemory);
}
MergeStackmem(Mem);
DeAllocate("W:aeea", Mem[0]);
DeAllocate("W:aeae", Mem[0]);
}
else if (0 == strcmp(MethodName.c_str(), "NEVPT2_AAVV") ) {
FArrayOffset nact = TensorById(23)->Sizes[0];
FArrayOffset nvirt = TensorById(6)->Sizes[0];
SplitStackmem(Mem);
#pragma omp parallel
{
char Header0[10], Header[256];
FILE *f = fopen("int/E3.npy", "rb");
fread(&Header0[0], 1, 10, f);
uint16_t HeaderSize = (uint16_t)Header0[8] + (((uint16_t)Header0[9]) << 8);
//char Header0[10], Header[256];
//FILE *f = fopen("int/node0/spatial_threepdm.0.0.bin.unpack", "rb");
FNdArrayView E3slice, Apslice;
E3slice.pData=0;
E3slice.Sizes.clear(); E3slice.Strides.clear();
FArrayOffset Stride = 1;
for (int i=0; i<4; i++) {
E3slice.Sizes.push_back(nact);
E3slice.Strides.push_back(Stride);
Stride *= E3slice.Sizes.back();
}
Stride = 1;
Apslice.Sizes.clear(); Apslice.Strides.clear();
for (int i=0; i<2; i++) {
Apslice.Sizes.push_back(nvirt);
Apslice.Strides.push_back(Stride);
Stride *= Apslice.Sizes.back();
}
void
*pBaseOfMemory = Mem[omprank].Alloc(0);
FNdArrayView **pTs3; Mem[omprank].Alloc(pTs3, 4);
pTs3[0] = &Apslice;
pTs3[1] = TensorById(19);
pTs3[2] = TensorById(4);
pTs3[3] = &E3slice;
double temp=1.;
size_t nact4 = nact*nact*nact*nact, nact2=nact*nact;
double * E3slicedata = Mem[omprank].AllocN(nact4, temp);
for (size_t cd=0; cd<nact*nact; cd++) {
if (cd%omp_get_num_threads() != omprank) continue;
size_t c=cd/nact, d=cd%nact;
fseek(f, HeaderSize+10+(d+c*nact)*nact4*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact4, f);
E3slice.pData = E3slicedata;
Apslice.pData = &TensorById(6)->operator()(0,0,c,d) ;
FScalar scale = 4.0;
ContractN(pTs3, "ab,efgh,abei,higf", -scale, true, Mem[omprank]);
}
fclose(f);
Mem[omprank].Free(pBaseOfMemory);
}
MergeStackmem(Mem);
}
else if (0 == strcmp(MethodName.c_str(), "MRLCC_CAAV") ) {
FArrayOffset nact = TensorById(22)->Sizes[2];
FArrayOffset ncore = TensorById(22)->Sizes[0];
FArrayOffset nvirt = TensorById(22)->Sizes[3];
SplitStackmem(Mem);
#pragma omp parallel
{
void
*pBaseOfMemorylocal = Mem[omprank].Alloc(0);
char AHeader0[10], AHeader[256];
FILE *fA = fopen("int/E3B.npy", "rb");
fread(&AHeader0[0], 1, 10, fA);
size_t AHeaderSize = (uint16_t)AHeader0[8] + (((uint16_t)AHeader0[9]) << 8);
char BHeader0[10], BHeader[256];
FILE *fB = fopen("int/E3C.npy", "rb");
fread(&BHeader0[0], 1, 10, fB);
size_t BHeaderSize = (uint16_t)BHeader0[8] + (((uint16_t)BHeader0[9]) << 8);
std::vector<FSrciTensor> localTensors;
localTensors.resize(47);
for (int i=0; i<47; i++) {
localTensors[i].Sizes = m_Tensors[i].Sizes;
localTensors[i].Strides = m_Tensors[i].Strides;
if (i < 39)
localTensors[i].pData = m_Tensors[i].pData;
}
double scale = 1.0;
double* E3slicedata = Mem[omprank].AllocN(nact*nact*nact*nact, scale);
double* Ap1data = Mem[omprank].AllocN(ncore*nvirt*nact*nact, scale);
double* Ap2data = Mem[omprank].AllocN(ncore*nvirt*nact*nact, scale);
for (size_t i=0; i<nact*nact*ncore*nvirt; i++)
Ap1data[i] = 0.0;
for (size_t i=0; i<nact*nact*ncore*nvirt; i++)
Ap2data[i] = 0.0;
localTensors[42].pData = Ap1data;
localTensors[43].pData = Ap2data;
for (size_t RS=0; RS<nact*nact; RS++)
{
if (RS%omp_get_num_threads() != omprank) continue;
size_t R = (RS)/nact;
size_t S = (RS)%nact;
fseek(fA, AHeaderSize+10+(R+S*nact)*nact*nact*nact*nact*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact*nact*nact*nact, fA);
localTensors[39].pData = &localTensors[42].operator()(0,0,R,S);
localTensors[44].pData = &localTensors[43].operator()(0,0,R,S);
localTensors[40].pData = E3slicedata;
ExecEquationSet(Method.EqsHandCode, localTensors, Mem[omprank]); //Ap = A*p
fseek(fB, BHeaderSize+10+(R+S*nact)*nact*nact*nact*nact*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact*nact*nact*nact, fB);
localTensors[41].pData = E3slicedata;
ExecEquationSet(Method.EqsHandCode2, localTensors, Mem[omprank]); //Ap = A*p
}
#pragma omp critical
{
for (size_t i=0; i<ncore; i++)
for (size_t j=0; j<nact; j++)
for (size_t k=0; k<nact; k++)
for (size_t l=0; l<nvirt; l++) {
localTensors[21].operator()(i,j,k,l) += localTensors[42].operator()(i,l,j,k);
localTensors[22].operator()(i,j,k,l) += localTensors[43].operator()(i,l,j,k);
}
}
localTensors.clear();
fclose(fA);
fclose(fB);
Mem[omprank].Free(pBaseOfMemorylocal);
}
MergeStackmem(Mem);
}
else if (0 == strcmp(MethodName.c_str(), "NEVPT2_CAAV") ) {
FArrayOffset nact = TensorById(22)->Sizes[2];
FArrayOffset ncore = TensorById(22)->Sizes[0];
FArrayOffset nvirt = TensorById(22)->Sizes[3];
SplitStackmem(Mem);
#pragma omp parallel
{
void
*pBaseOfMemorylocal = Mem[omprank].Alloc(0);
char AHeader0[10], AHeader[256];
FILE *fA = fopen("int/E3B.npy", "rb");
fread(&AHeader0[0], 1, 10, fA);
size_t AHeaderSize = (uint16_t)AHeader0[8] + (((uint16_t)AHeader0[9]) << 8);
char BHeader0[10], BHeader[256];
FILE *fB = fopen("int/E3C.npy", "rb");
fread(&BHeader0[0], 1, 10, fB);
size_t BHeaderSize = (uint16_t)BHeader0[8] + (((uint16_t)BHeader0[9]) << 8);
std::vector<FSrciTensor> localTensors;
localTensors.resize(47);
for (int i=0; i<47; i++) {
localTensors[i].Sizes = m_Tensors[i].Sizes;
localTensors[i].Strides = m_Tensors[i].Strides;
if (i < 39)
localTensors[i].pData = m_Tensors[i].pData;
}
double scale = 1.0;
double* E3slicedata = Mem[omprank].AllocN(nact*nact*nact*nact, scale);
double* Ap1data = Mem[omprank].AllocN(ncore*nvirt*nact*nact, scale);
double* Ap2data = Mem[omprank].AllocN(ncore*nvirt*nact*nact, scale);
for (size_t i=0; i<nact*nact*ncore*nvirt; i++)
Ap1data[i] = 0.0;
for (size_t i=0; i<nact*nact*ncore*nvirt; i++)
Ap2data[i] = 0.0;
localTensors[42].pData = Ap1data;
localTensors[43].pData = Ap2data;
for (size_t RS=0; RS<nact*nact; RS++)
{
if (RS%omp_get_num_threads() != omprank) continue;
size_t R = (RS)/nact;
size_t S = (RS)%nact;
fseek(fA, AHeaderSize+10+(R+S*nact)*nact*nact*nact*nact*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact*nact*nact*nact, fA);
localTensors[39].pData = &localTensors[42].operator()(0,0,R,S);
localTensors[44].pData = &localTensors[43].operator()(0,0,R,S);
localTensors[40].pData = E3slicedata;
ExecEquationSet(Method.EqsHandCode, localTensors, Mem[omprank]); //Ap = A*p
fseek(fB, BHeaderSize+10+(R+S*nact)*nact*nact*nact*nact*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact*nact*nact*nact, fB);
localTensors[41].pData = E3slicedata;
ExecEquationSet(Method.EqsHandCode2, localTensors, Mem[omprank]); //Ap = A*p
}
#pragma omp critical
{
for (size_t i=0; i<ncore; i++)
for (size_t j=0; j<nact; j++)
for (size_t k=0; k<nact; k++)
for (size_t l=0; l<nvirt; l++) {
localTensors[20].operator()(i,j,k,l) += localTensors[42].operator()(i,l,j,k);
localTensors[21].operator()(i,j,k,l) += localTensors[43].operator()(i,l,j,k);
}
}
localTensors.clear();
fclose(fA);
fclose(fB);
Mem[omprank].Free(pBaseOfMemorylocal);
}
MergeStackmem(Mem);
}
else if (0 == strcmp(MethodName.c_str(), "MRLCC_CCAA") ) {
//{"KLRS,IaKb,PQaRSb,ILPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[IaKb] E3[PQaRSb] p[ILPQ]
//{"KLSR,IaLb,PQaRSb,IKPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[IaLb] E3[PQaSRb] p[IKPQ]
//{"KLSR,JaKb,PQaRSb,LJPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[JaKb] E3[PQaSRb] p[LJPQ]
//{"KLRS,JaLb,PQaRSb,KJPQ", -1.0 , 4, {22,5,16,21}}, //Ap[KLRS] += -1.0 W[JaLb] E3[PQaRSb] p[KJPQ]
//{"KLbS,KIaR,PQaRSb,ILPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[IabK] E3[PQabSR] p[ILPQ]
//{"KLSb,LIaR,PQaRSb,IKPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[IabL] E3[PQabRS] p[IKPQ]
//{"KLbR,KJaS,PQaRSb,LJPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[JabK] E3[PQaSbR] p[LJPQ]
//{"KLRb,LJaS,PQaRSb,KJPQ", -1.0 , 4, {22,26,16,21}}, //Ap[KLRS] += -1.0 W[JabL] E3[PQaRbS] p[KJPQ]
//{"KLcR,PabS,QabRSc,KLPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabScR] p[KLPQ]
//{"KLRc,PabS,QabRSc,LKPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Pabc] E3[QabRcS] p[LKPQ]
//{"KLRc,QabS,PabRSc,KLPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabRcS] p[KLPQ]
//{"KLcR,QabS,PabRSc,LKPQ", 1.0 , 4, {22,12,16,21}}, //Ap[KLRS] += 1.0 W[Qabc] E3[PabScR] p[LKPQ]
FArrayOffset nact = TensorById(22)->Sizes[2];
FArrayOffset ncore = TensorById(22)->Sizes[0];
SplitStackmem(Mem);
#pragma omp parallel
{
void
*pBaseOfMemorylocal = Mem[omprank].Alloc(0);
char Header0[10], Header[256];
FILE *f = fopen("int/E3.npy", "rb");
fread(&Header0[0], 1, 10, f);
uint16_t HeaderSize = (uint16_t)Header0[8] + (((uint16_t)Header0[9]) << 8);
//FILE *f = fopen("scratch/node0/spatial_threepdm.0.0.bin.unpack", "rb");
std::vector<FSrciTensor> localTensors;
localTensors.resize(14);
for (int i=0; i<12; i++) {
localTensors[i].Sizes = m_Tensors[i+30].Sizes;
localTensors[i].Strides = m_Tensors[i+30].Strides;
}
localTensors[12].Sizes = m_Tensors[21].Sizes;
localTensors[12].Strides = m_Tensors[21].Strides;
localTensors[12].pData = m_Tensors[21].pData;
localTensors[13].Sizes = m_Tensors[42].Sizes;
localTensors[13].Strides = m_Tensors[42].Strides;
double scale = 1.0;
double * E3slicedata = Mem[omprank].AllocN(nact*nact*nact, scale);
double* Ap2data = Mem[omprank].AllocN(nact*nact*ncore*ncore, scale);
for (size_t i=0; i<nact*nact*ncore*ncore; i++)
Ap2data[i] = 0.0;
localTensors[13].pData = Ap2data;
for (size_t RSB=0; RSB<nact*nact*nact; RSB++)
{
if (RSB%omp_get_num_threads() != omprank) continue;
size_t R = RSB/nact/nact;
size_t S = (RSB%(nact*nact))/nact;
size_t b = (RSB%(nact*nact))%nact;
fseek(f, HeaderSize+10+(R+S*nact+b*nact*nact)*nact*nact*nact*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact*nact*nact, f);
localTensors[0].pData = &localTensors[13].operator()(0,0,R,S);
localTensors[1].pData = &TensorById(5)->operator()(0,0,0,b);
localTensors[2].pData = E3slicedata;//&TensorById(16)->operator()(0,0,0,R,S,b);
localTensors[4].pData = &TensorById(26)->operator()(0,0,0,R);
localTensors[5].pData = &TensorById(12)->operator()(0,0,0,S);
localTensors[6].pData = &localTensors[13].operator()(0,0,S,R);
localTensors[7].pData = &localTensors[13].operator()(0,0,b,S);
localTensors[8].pData = &localTensors[13].operator()(0,0,S,b);
localTensors[9].pData = &localTensors[13].operator()(0,0,b,R);
localTensors[10].pData = &localTensors[13].operator()(0,0,R,b);
localTensors[11].pData = &TensorById(26)->operator()(0,0,0,S);
ExecEquationSet(Method.EqsHandCode, localTensors, Mem[omprank]); //Ap = A*p
}
#pragma omp critical
{
for (size_t i=0; i<nact*nact*ncore*ncore; i++)
TensorById(22)->pData[i] += localTensors[13].pData[i];
}
localTensors.clear();
Mem[omprank].Free(pBaseOfMemorylocal);
}
MergeStackmem(Mem);
}
else if (0 == strcmp(MethodName.c_str(), "NEVPT2_CCAA") ) {
FArrayOffset nact = TensorById(21)->Sizes[2];
FArrayOffset ncore = TensorById(21)->Sizes[0];
SplitStackmem(Mem);
#pragma omp parallel
{
void
*pBaseOfMemorylocal = Mem[omprank].Alloc(0);
char AHeader0[10], AHeader[256];
FILE *fA = fopen("int/E3.npy", "rb");
fread(&AHeader0[0], 1, 10, fA);
size_t AHeaderSize = (uint16_t)AHeader0[8] + (((uint16_t)AHeader0[9]) << 8);
std::vector<FSrciTensor> localTensors;
localTensors.resize(32);
for (int i=0; i<32; i++) {
localTensors[i].Sizes = m_Tensors[i].Sizes;
localTensors[i].Strides = m_Tensors[i].Strides;
if (i < 29)
localTensors[i].pData = m_Tensors[i].pData;
}
double scale = 1.0;
double* E3slicedata = Mem[omprank].AllocN(nact*nact*nact*nact, scale);
for (size_t RS=0; RS<nact*nact; RS++)
{
if (RS%omp_get_num_threads() != omprank) continue;
size_t R = (RS)/nact;
size_t S = (RS)%nact;
fseek(fA, AHeaderSize+10+(S+R*nact)*nact*nact*nact*nact*sizeof(double), SEEK_SET);
fread(E3slicedata, sizeof(double), nact*nact*nact*nact, fA);
localTensors[29].pData = &localTensors[21].operator()(0,0,R,S);
localTensors[30].pData = &localTensors[21].operator()(0,0,S,R);
localTensors[31].pData = E3slicedata;
ExecEquationSet(Method.EqsHandCode, localTensors, Mem[omprank]); //Ap = A*p
}
localTensors.clear();
fclose(fA);
Mem[omprank].Free(pBaseOfMemorylocal);
}
MergeStackmem(Mem);
}
else if (0 == strcmp(MethodName.c_str(), "MRLCC_CCVV") ) {
//{"abcd,abef,efcd", 8.0 , 3, {22,13,21}}, //8.0 Ap[abcd] W[abef] p[efcd]
//{"abcd,abef,efdc", -4.0 , 3, {22,13,21}}, //-4.0 Ap[abcd] W[abef] p[efdc]
void
*pBaseOfMemory = Mem[omprank].Alloc(0);
int ncore = TensorById(22)->Sizes[2];
int nvirt = TensorById(22)->Sizes[0];
FScalar scaleA = -4.0, scaleB = 1.0, scaleC=8.0;
char T='t', N='n';
FArrayOffset nvirtsq = nvirt*nvirt, ncoresq = ncore*ncore;
FScalar *intermediateD = Mem[0].AllocN(nvirt*nvirt*ncore*ncore, scaleA);
for (int i=0; i<ncore; i++)
for (int j=0; j<ncore; j++)
for (int b=0; b<nvirt; b++)
for (int a=0; a<nvirt; a++)
intermediateD[a+b*nvirt+j*nvirt*nvirt+i*nvirt*nvirt*ncore] = TensorById(21)->operator()(a,b,i,j);
SplitStackmem(Mem);
#pragma omp parallel
{
void
*pBaseOfMemorylocal = Mem[omprank].Alloc(0);
double *Wslice = Mem[omprank].AllocN(nvirt*nvirt*nvirt, scaleA);
for (int b=0; b<nvirt; b++) {
if (b%omp_get_num_threads() != omprank) continue;
char filename[700];
sprintf(filename, "int/W:eeee%04d", b);
FILE* f = fopen(filename, "rb");
fread(Wslice, sizeof(scaleA), nvirtsq*nvirt, f);
dgemm_(N, N, nvirt, ncoresq, nvirtsq,
scaleC, Wslice, nvirt, TensorById(21)->pData, nvirtsq, scaleB, &TensorById(22)->operator()(0,b,0,0), nvirtsq);
dgemm_(N, N, nvirt, ncoresq, nvirtsq,
scaleA, Wslice, nvirt, intermediateD, nvirtsq, scaleB, &TensorById(22)->operator()(0,b,0,0), nvirtsq);
fclose(f);
}
Mem[omprank].Free(pBaseOfMemorylocal);
}
MergeStackmem(Mem);
//dgemm_(N, N, nvirtsq, ncoresq, nvirtsq,
//scaleC, TensorById(13)->pData, nvirtsq, TensorById(21)->pData, nvirtsq, scaleB, TensorById(22)->pData, nvirtsq);
//dgemm_(N, N, nvirtsq, ncoresq, nvirtsq,
//scaleA, TensorById(13)->pData, nvirtsq, intermediateD, nvirtsq, scaleB, TensorById(22)->pData, nvirtsq);
Mem[omprank].Free(pBaseOfMemory);
}
else if (0 == strcmp(MethodName.c_str(), "MRLCC_ACVV") ) {
//{"CDJR,ABCD,RQ,ABJQ", 2.0 , 4, {22,13,14,21}}, //Ap[CDJR] += 2.0 W[ABCD] E1[RQ] p[ABJQ]
//{"CDJR,ABDC,RQ,ABJQ", -1.0 , 4, {22,13,14,21}}, //Ap[CDJR] += -1.0 W[ABDC] E1[RQ] p[ABJQ]
void
*pBaseOfMemory = Mem[omprank].Alloc(0);
FArrayOffset ncore = TensorById(22)->Sizes[2];
FArrayOffset nact = TensorById(22)->Sizes[3];
FArrayOffset nvirt = TensorById(22)->Sizes[0];
FScalar scaleA = -1.0, scaleB = 1.0, scaleC=2.0, scaleD=0.0;
char T='t', N='n';
FArrayOffset nvirtsq = nvirt*nvirt,
ncoreact = ncore*nact,
nvvc = nvirt*nvirt*ncore;
FScalar *intermediateD = Mem[0].AllocN(nvirt*nvirt*ncore*nact, scaleA);
dgemm_(N, N, nvvc, nact, nact,
scaleB, TensorById(21)->pData, nvvc, TensorById(14)->pData, nact, scaleD, TensorById(30)->pData, nvvc);
for (int r=0; r<nact; r++)
for (int j=0; j<ncore; j++)
for (int b=0; b<nvirt; b++)
for (int a=0; a<nvirt; a++)
intermediateD[b+a*nvirt+j*nvirt*nvirt+r*nvirt*nvirt*ncore] = TensorById(30)->operator()(a,b,j,r);
SplitStackmem(Mem);
#pragma omp parallel
{
void
*pBaseOfMemorylocal = Mem[omprank].Alloc(0);
double *Wslice = Mem[omprank].AllocN(nvirt*nvirt*nvirt, scaleA);
for (int b=0; b<nvirt; b++) {
if (b%omp_get_num_threads() != omprank) continue;
char filename[700];
sprintf(filename, "int/W:eeee%04d", b);
FILE* f = fopen(filename, "rb");
fread(Wslice, sizeof(scaleA), nvirtsq*nvirt, f);
dgemm_(N, N, nvirt, ncoreact, nvirtsq,
scaleC, Wslice, nvirt, TensorById(30)->pData, nvirtsq, scaleB, &TensorById(22)->operator()(0,b,0,0), nvirtsq);
dgemm_(N, N, nvirt, ncoreact, nvirtsq,
scaleA, Wslice, nvirt, intermediateD, nvirtsq, scaleB, &TensorById(22)->operator()(0,b,0,0), nvirtsq);
fclose(f);
}
Mem[omprank].Free(pBaseOfMemorylocal);
}
MergeStackmem(Mem);
Mem[omprank].Free(pBaseOfMemory);
}
//zero out all intermediates
for (uint i = 0; i != Method.nTensorDecls; ++i) {
FTensorDecl const
&Decl = Method.pTensorDecls[i];
if (Decl.Usage == USAGE_Intermediate)
memset(m_Tensors[i].pData, 0, m_Tensors[i].nValues() *sizeof(m_Tensors[i].pData[0]));
}
}
void FJobContext::InitAmplitudes(FMemoryStack2 &Mem)
{
// set all amplitudes to zero.
ClearTensors(USAGE_Amplitude);
if (0 == strcmp(Method.perturberClass, "AAVV")) {
ExecEquationSet(Method.Overlap, m_Tensors, Mem);
}
else if (0 == strcmp(Method.perturberClass, "CCAA")) {
ExecEquationSet(Method.Overlap, m_Tensors, Mem);
}
else if (0 == strcmp(Method.perturberClass, "ACVV")) {
ExecEquationSet(Method.Overlap, m_Tensors, Mem);
}
else if (0 == strcmp(Method.perturberClass, "CCAV")) {
ExecEquationSet(Method.Overlap, m_Tensors, Mem);
FNdArrayView *b = TN("b");
}
else if (0 == strcmp(Method.perturberClass, "CCVV")) {
ExecEquationSet(Method.Overlap, m_Tensors, Mem);
}
else if (0 == strcmp(Method.perturberClass, "CAAV")) {
FNdArrayView *p = TN("p");
FNdArrayView *Ap = TN("Ap");
FNdArrayView *bt = TN("b");
FNdArrayView *Bt = TN("B");
bt->pData = TN("b1")->pData; //just make the pointer
p->pData = TN("p1")->pData; //just make the pointer
Ap->pData = TN("Ap1")->pData; //just make the pointer
Bt->pData = TN("B1")->pData; //just make the pointer
p->Sizes.push_back(TN("p1")->nValues()*2);
p->Strides.push_back(1);
Ap->Sizes.push_back(TN("Ap1")->nValues()*2);
Ap->Strides.push_back(1);
bt->Sizes.push_back(TN("b1")->nValues()*2);
bt->Strides.push_back(1);
Bt->Sizes.push_back(TN("B1")->nValues()*2);
Bt->Strides.push_back(1);
//FillData(31, Mem);
//FillData(32, Mem);
FNdArrayView *t = TN("t");
FNdArrayView *w1 = TND("W:eaca");
FNdArrayView *w2 = TND("W:aeca");
FNdArrayView *f1 = TND("f:ec");
int ncore=t->Sizes[0], nvirt=t->Sizes[3];
int nact = t->Sizes[2];
for (int i=0; i<ncore; i++)
for (int p=0; p<nact; p++)
for (int a=0; a<nvirt; a++)
w1->operator()(a,p,i,p) += f1->operator()(a,i)/(WfDecl.nActElec);
ExecEquationSet(Method.Overlap, m_Tensors, Mem);
//DeAllocate("W:aeca", Mem);
//DeAllocate("W:eaca", Mem);
}
ct::FArrayNpy guess;
if (guessInput.compare("") != 0) {
FScalar zero = 0.0;
PrintResult("Reading guess from "+guessInput, zero, 0);
ct::ReadNpy( guess ,guessInput);
Copy(*TN("T"), ViewFromNpy(guess));
}
else
Copy(*TN("t"), *TN("b"));
}
void FJobContext::MakeOverlapAndOrthogonalBasis(ct::FMemoryStack2 *Mem) {
//make S and Shalf
if (0 == strcmp(Method.perturberClass, "AAVV")) {
FNdArrayView *S1 = TN("S1");
Copy(*TND("S2:aaaa"), *TND("E2:aaaa"));
FNdArrayView *a = TND("S2:aaaa"), *b=TND("E2:aaaa");
int nact = a->Sizes[0];
for (int k=0; k<a->Sizes[0]; k++)
for (int l=0; l<a->Sizes[0]; l++)
for (int j=0; j<a->Sizes[0]; j++)
for (int i=0; i<a->Sizes[0]; i++) {
a->operator()(i,j,k,l) += b->operator()(i,j,l,k);
S1->operator()(i,j,k,l) += b->operator()(i,j,k,l);
S1->operator()(i,j+nact,k,l+nact) += b->operator()(i,j,k,l);
S1->operator()(i,j+nact,k,l) += b->operator()(i,j,l,k);
S1->operator()(i,j,k,l+nact) += b->operator()(i,j,l,k);
}
//make X(rs,mu) and Xhalf(rs,mu) which are stored in place of overlap
FScalar *eigen1 = (FScalar*)::malloc(sizeof(FScalar)*S1->Strides[2]);
FScalar *eigen2 = (FScalar*)::malloc(sizeof(FScalar)*a->Strides[2]);
ct::Diagonalize(eigen1, TN("S1")->pData, S1->Strides[2], S1->Strides[2]);
ct::Diagonalize(eigen2, TND("S2:aaaa")->pData, a->Strides[2], a->Strides[2]);
//FNdArrayView *b = TND("W:eecc");
size_t aa = S1->Strides[2];
for (int i=0; i<aa; i++) {
if (fabs(eigen1[i]) < ThrTrun) {
for (int j=0; j<aa; j++)
S1->pData[j+aa*i] = 0.0;
}
else {
for (int j=0; j<aa; j++)
S1->pData[j+i*aa] = S1->pData[j+i*aa]/(pow(eigen1[i],0.5));
}
}
aa = a->Strides[2];
for (int i=0; i<aa; i++) {
if (fabs(eigen2[i]) < ThrTrun) {
for (int j=0; j<aa; j++)
TND("S2:aaaa")->pData[j+aa*i] = 0.0;
}
else {
for (int j=0; j<aa; j++) {
TND("S2:aaaa")->pData[j+i*aa] = TND("S2:aaaa")->pData[j+i*aa]/(pow(eigen2[i],0.5));
}
}
}
::free(eigen2);
::free(eigen1);
}
else if (0 == strcmp(Method.perturberClass, "CCAA")) {
FNdArrayView *a = TND("S2:aaaa"), *b=TND("E2:aaaa");
FNdArrayView *S1 = TND("S1:aaaa"); S1->ClearData(); a->ClearData();
ExecEquationSet(Method.MakeS1, m_Tensors, Mem[0]);
ExecEquationSet(Method.MakeS2, m_Tensors, Mem[0]);
//make X(rs,mu) and Xhalf(rs,mu) which are stored in place of overlap
FScalar *eigen1 = (FScalar*)::malloc(sizeof(FScalar)*a->Strides[2]);
FScalar *eigen2 = (FScalar*)::malloc(sizeof(FScalar)*a->Strides[2]);
ct::Diagonalize(eigen1, TND("S1:aaaa")->pData, a->Strides[2], a->Strides[2]);
ct::Diagonalize(eigen2, TND("S2:aaaa")->pData, a->Strides[2], a->Strides[2]);
size_t aa = a->Strides[2];
for (int i=0; i<aa; i++) {
if (fabs(eigen1[i]) < ThrTrun) {
for (int j=0; j<aa; j++)
TND("S1:aaaa")->pData[j+aa*i] = 0.0;
}
else {
for (int j=0; j<aa; j++)
TND("S1:aaaa")->pData[j+i*aa] = TND("S1:aaaa")->pData[j+i*aa]/(pow(eigen1[i],0.5));
}
if (fabs(eigen2[i]) < ThrTrun) {
for (int j=0; j<aa; j++)
TND("S2:aaaa")->pData[j+aa*i] = 0.0;
}
else {
for (int j=0; j<aa; j++)
TND("S2:aaaa")->pData[j+i*aa] = TND("S2:aaaa")->pData[j+i*aa]/(pow(eigen2[i],0.5));
}
}
::free(eigen2);
::free(eigen1);
}
else if (0 == strcmp(Method.perturberClass, "ACVV")) {
FNdArrayView *S1 = TND("S1:AA"), *E=TND("E1:aa");
FNdArrayView *S2 = TND("S2:aa");
int nact = E->Sizes[0];
for (int k=0; k<nact; k++)
for (int l=0; l<nact; l++) {
S1->operator()(k,l) = 2.*E->operator()(k,l);
S1->operator()(k+nact,l+nact) = 2.*E->operator()(k,l);
S1->operator()(k+nact,l) = -1.*E->operator()(k,l);
S1->operator()(k,l+nact) = -1.*E->operator()(k,l);
S2->operator()(k,l) = 1.*E->operator()(k,l);
}
//make X(rs,mu) and Xhalf(rs,mu) which are stored in place of overlap
FScalar *eigen1 = (FScalar*)::malloc(sizeof(FScalar)*S1->Strides[1]);
FScalar *eigen2 = (FScalar*)::malloc(sizeof(FScalar)*S2->Strides[1]);
ct::Diagonalize(eigen1, S1->pData, S1->Strides[1], S1->Strides[1]);
ct::Diagonalize(eigen2, S2->pData, S2->Strides[1], S2->Strides[1]);
for (int i=0; i<2*nact; i++) {
if (fabs(eigen1[i]) < ThrTrun) {
for (int j=0; j<2*nact; j++)
S1->pData[j+2*nact*i] = 0.0;
}
else {
for (int j=0; j<2*nact; j++)
S1->pData[j+i*2*nact] = S1->pData[j+i*2*nact]/(pow(eigen1[i],0.5));
}
}
for (int i=0; i<nact; i++) {
if (fabs(eigen2[i]) < ThrTrun) {
for (int j=0; j<nact; j++)
S2->pData[j+nact*i] = 0.0;
}
else {
for (int j=0; j<nact; j++)
S2->pData[j+i*nact] = S2->pData[j+i*nact]/(pow(eigen2[i],0.5));
}
}
::free(eigen2);
::free(eigen1);
}
else if (0 == strcmp(Method.perturberClass, "CCAV")) {
FNdArrayView *S1 = TND("S1:AA"), *E=TND("E1:aa");
FNdArrayView *S2 = TND("S2:aa");
int nact = E->Sizes[0];
for (int k=0; k<nact; k++)
for (int l=0; l<nact; l++) {
S2->operator()(k,l) = -1.*E->operator()(k,l);
S1->operator()(k,l) = -2.*E->operator()(k,l);
S1->operator()(k+nact,l+nact) = -2.*E->operator()(k,l);
S1->operator()(k+nact,l) = 1.*E->operator()(k,l);
S1->operator()(k,l+nact) = 1.*E->operator()(k,l);
if (k == l) {
S1->operator()(k,k) += 4.;
S1->operator()(k+nact,k) += -2.;
S1->operator()(k,k+nact) += -2.;
S1->operator()(k+nact,k+nact) += 4.;
S2->operator()(k,k) += 2.;
}
}
//std::cout << "Norm "<<S1->nValues()<<" "<< ct::Dot(S1->pData, S1->pData, S1->nValues())<<std::endl;
//std::cout << "Norm "<<S2->nValues()<<" "<< ct::Dot(S2->pData, S2->pData, S2->nValues())<<std::endl;
//make X(rs,mu) and Xhalf(rs,mu) which are stored in place of overlap
FScalar *eigen1 = (FScalar*)::malloc(sizeof(FScalar)*S1->Strides[1]);
FScalar *eigen2 = (FScalar*)::malloc(sizeof(FScalar)*S2->Strides[1]);
ct::Diagonalize(eigen1, S1->pData, S1->Strides[1], S1->Strides[1]);
ct::Diagonalize(eigen2, S2->pData, S2->Strides[1], S2->Strides[1]);
for (int i=0; i<2*nact; i++) {
if (fabs(eigen1[i]) < ThrTrun) {
for (int j=0; j<2*nact; j++)
S1->pData[j+2*nact*i] = 0.0;
}
else {
for (int j=0; j<2*nact; j++)
S1->pData[j+i*2*nact] = S1->pData[j+i*2*nact]/(pow(eigen1[i],0.5));
}
}
for (int i=0; i<nact; i++) {
if (fabs(eigen2[i]) < ThrTrun) {
for (int j=0; j<nact; j++)
S2->pData[j+nact*i] = 0.0;
}
else {
for (int j=0; j<nact; j++)
S2->pData[j+i*nact] = S2->pData[j+i*nact]/(pow(eigen2[i],0.5));
}
}
::free(eigen2);
::free(eigen1);
}
else if (0 == strcmp(Method.perturberClass, "CAAV")) {
FNdArrayView *S1 = TN("S1"), *E1=TN("E1"), *E2=TN("E2");
S1->ClearData();
int nact = E1->Sizes[0];
S1->Sizes.resize(0);S1->Strides.resize(0);
S1->Sizes.push_back(2*nact*nact); S1->Sizes.push_back(2*nact*nact);
S1->Strides.push_back(1); S1->Strides.push_back(2*nact*nact);
int fullrange = nact*nact;
for (int r=0; r<nact; r++)
for (int s=0; s<nact; s++)
for (int q=0; q<nact; q++)
for (int p=0; p<nact; p++){
if (p==r)
S1->operator()(p+q*nact,r+s*nact) += 2.*E1->operator()(s,q);
S1->operator()(p+q*nact,r+s*nact) += 2.*E2->operator()(p,s,q,r);
if (p==r)
S1->operator()(p+q*nact+fullrange, r+s*nact) += -1.*E1->operator()(s,q);
S1->operator()(p+q*nact+fullrange, r+s*nact) += -1.*E2->operator()(p,s,q,r);
if (p==r)
S1->operator()(r+s*nact, p+q*nact+fullrange) += -1.*E1->operator()(s,q);
S1->operator()(r+s*nact, p+q*nact+fullrange) += -1.*E2->operator()(p,s,q,r);
if (p==r)
S1->operator()(p+q*nact+fullrange, r+s*nact+fullrange) += 2.*E1->operator()(s,q);
S1->operator()(p+q*nact+fullrange, r+s*nact+fullrange) += -1.*E2->operator()(p,s,r,q);
}
//make X(rs,mu) and Xhalf(rs,mu) which are stored in place of overlap
FScalar *eigen1 = (FScalar*)::malloc(sizeof(FScalar)*2*fullrange);
ct::Diagonalize(eigen1, S1->pData, 2*fullrange, 2*fullrange);
for (int i=0; i<2*nact*nact; i++) {
if (fabs(eigen1[i]) < ThrTrun) {
for (int j=0; j<2*nact*nact; j++)
S1->pData[j+2*nact*nact*i] = 0.0;
}
else {
for (int j=0; j<2*nact*nact; j++)
S1->pData[j+i*2*nact*nact] = S1->pData[j+i*2*nact*nact]/(pow(eigen1[i],0.5));
}
}
::free(eigen1);
}
}
void FJobContext::MakeOrthogonal(std::string StringA, std::string StringB) {
if (0 == strcmp(Method.perturberClass, "AAVV")) {
FNdArrayView *t = TN(StringA);
FNdArrayView *Ta = TN(StringB); Ta->ClearData();
FNdArrayView *S1 = TN("S1");
FNdArrayView *S2 = TN("S2");
int nact = t->Sizes[2];
#pragma omp parallel for schedule(dynamic)
for (int rs=0; rs<t->Sizes[2]*t->Sizes[2]; rs++)
for (int p=0; p<t->Sizes[2]; p++)
for (int q=0; q<t->Sizes[2]; q++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c; b<t->Sizes[0]; b++)
{
int r = rs/t->Sizes[2], s=rs%t->Sizes[2];
if (b == c)
Ta->operator()(b,c,r,s) += S2->operator()(p,q,r,s)*t->operator()(b,c,p,q);
else {
Ta->operator()(b,c,r,s) += S1->operator()(p,q,r,s) *t->operator()(b,c,p,q) + S1->operator()(p,q+nact,r,s) *t->operator()(c,b,p,q);
Ta->operator()(c,b,r,s) += S1->operator()(p,q,r,s+nact)*t->operator()(b,c,p,q) + S1->operator()(p,q+nact,r,s+nact)*t->operator()(c,b,p,q);
}
}
/*
for (int p=0; p<t->Sizes[2]; p++)
for (int q=0; q<t->Sizes[2]; q++)
for (int r=0; r<t->Sizes[2]; r++)
for (int s=0; s<t->Sizes[2]; s++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c; b<t->Sizes[0]; b++)
{
if (b == c)
Ta->operator()(b,c,r,s) += S2->operator()(p,q,r,s)*t->operator()(b,c,p,q);
else {
Ta->operator()(b,c,r,s) += S1->operator()(p,q,r,s) *t->operator()(b,c,p,q) + S1->operator()(p,q+nact,r,s) *t->operator()(c,b,p,q);
Ta->operator()(c,b,r,s) += S1->operator()(p,q,r,s+nact)*t->operator()(b,c,p,q) + S1->operator()(p,q+nact,r,s+nact)*t->operator()(c,b,p,q);
}
}
*/
}
else if (0 == strcmp(Method.perturberClass, "CCVV")) {
FNdArrayView *t = TN(StringA);
FNdArrayView *Ta = TN(StringB); Ta->ClearData();
for (int i=0; i<t->Sizes[2]; i++)
for (int j=i; j<t->Sizes[2]; j++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c; b<t->Sizes[0]; b++)
{
if (b == c) {
Ta->operator()(b,c,i,j) += (0.*t->operator()(b,c,i,j) + 0.*t->operator()(b,c,j,i))/pow(8,0.5);
Ta->operator()(b,c,j,i) += ( t->operator()(b,c,i,j) + t->operator()(b,c,j,i))/pow(8,0.5);
}
else {
Ta->operator()(b,c,i,j) += ( t->operator()(b,c,i,j)*0. + t->operator()(b,c,j,i)*0. + t->operator()(c,b,i,j)*0. + t->operator()(c,b,j,i)*0. ) /pow( 4.0,0.5);
Ta->operator()(b,c,j,i) += ( t->operator()(b,c,i,j)*0. + t->operator()(b,c,j,i)*0. + t->operator()(c,b,i,j)*0. + t->operator()(c,b,j,i)*0. ) /pow( 4.0,0.5);
Ta->operator()(c,b,i,j) += ( t->operator()(b,c,i,j)*0.5 + t->operator()(b,c,j,i)*0.5 + t->operator()(c,b,i,j)*0.5 + t->operator()(c,b,j,i)*0.5) /pow( 4.0,0.5);
Ta->operator()(c,b,j,i) += (-t->operator()(b,c,i,j)*0.5 + t->operator()(b,c,j,i)*0.5 + t->operator()(c,b,i,j)*0.5 - t->operator()(c,b,j,i)*0.5) /pow(12.0,0.5);
}
}
}
else if (0 == strcmp(Method.perturberClass, "CCAA")) {
FNdArrayView *t = TN(StringA);
FNdArrayView *Ta = TN(StringB); Ta->ClearData();
FNdArrayView *S1 = TND("S1:aaaa");
FNdArrayView *S2 = TND("S2:aaaa");
for (int p=0; p<t->Sizes[2]; p++)
for (int q=0; q<t->Sizes[2]; q++)
for (int r=0; r<t->Sizes[2]; r++)
for (int s=0; s<t->Sizes[2]; s++)
for (int j=0; j<t->Sizes[0]; j++)
for (int i=j; i<t->Sizes[0]; i++)
{
if (i == j)
Ta->operator()(i,j,r,s) += S2->operator()(p,q,r,s)*t->operator()(i,j,p,q);
else {
Ta->operator()(i,j,r,s) += S1->operator()(p,q,r,s)*t->operator()(i,j,p,q);
Ta->operator()(j,i,r,s) = 0.0;
}
}
//std::cout << "Norm "<<S2->nValues()<<" "<< ct::Dot(S2->pData, S2->pData, S2->nValues())<<std::endl;
//std::cout << "Norm "<<t->nValues()<<" "<< ct::Dot(t->pData, t->pData, t->nValues())<<std::endl;
//std::cout << "Norm "<<Ta->nValues()<<" "<< ct::Dot(Ta->pData, Ta->pData, Ta->nValues())<<std::endl;
}
else if (0 == strcmp(Method.perturberClass, "CAAV")) {
FNdArrayView *t = TN(StringA);
FNdArrayView *Ta = TN(StringB); Ta->ClearData();
FNdArrayView *S1 = TN("S1");
int ncore = m_Domains['c'].nSize, nact = m_Domains['a'].nSize, nvirt = m_Domains['e'].nSize;
int fullrange = ncore*nact*nact*nvirt;
for (int p=0; p<nact; p++)
for (int q=0; q<nact; q++)
for (int r=0; r<nact; r++)
for (int s=0; s<nact; s++)
for (int a=0; a<nvirt; a++)
for (int i=0; i<ncore; i++)
{
Ta->pData[i+p*ncore+q*ncore*nact+a*ncore*nact*nact] += t->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact]*S1->operator()(r+s*nact,p+q*nact)
+t->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact + fullrange]* S1->operator()(r+s*nact+nact*nact,p+q*nact);
Ta->pData[i+p*ncore+q*ncore*nact+a*ncore*nact*nact+fullrange] += t->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact]*S1->operator()(r+s*nact,p+q*nact+nact*nact)
+t->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact + fullrange]* S1->operator()(r+s*nact+nact*nact,p+q*nact+nact*nact);
//std::cout<<t->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact]<<" "<<S1->operator()(r,s,p,q)<<" "<<Ta->pData[i+p*ncore+q*ncore*nact+a*ncore*nact*nact]<<" "<<i+p*ncore+q*ncore*nact+a*ncore*nact*nact<<" "<<Ta->nValues()<<std::endl;
}
}
else if (0 == strcmp(Method.perturberClass, "ACVV")) {
FNdArrayView *t = TN(StringA);
FNdArrayView *Ta = TN(StringB); Ta->ClearData();
FNdArrayView *S1 = TN("S1");
FNdArrayView *S2 = TN("S2");
int nact = t->Sizes[3];
for (int p=0; p<t->Sizes[3]; p++)
for (int q=0; q<t->Sizes[3]; q++)
for (int i=0; i<t->Sizes[2]; i++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c; b<t->Sizes[0]; b++)
{
if (b == c)
Ta->operator()(b,c,i,q) += S2->operator()(p,q)*t->operator()(b,c,i,p);
else {
Ta->operator()(b,c,i,q) += S1->operator()(p,q) *t->operator()(b,c,i,p);
Ta->operator()(b,c,i,q) += S1->operator()(p+nact,q) *t->operator()(c,b,i,p);
Ta->operator()(c,b,i,q) += S1->operator()(p,q+nact) *t->operator()(b,c,i,p);
Ta->operator()(c,b,i,q) += S1->operator()(p+nact,q+nact)*t->operator()(c,b,i,p);
}
}
}
else if (0 == strcmp(Method.perturberClass, "CCAV")) {
FNdArrayView *t = TN(StringA);
FNdArrayView *Ta = TN(StringB); Ta->ClearData();
FNdArrayView *S1 = TN("S1");
FNdArrayView *S2 = TN("S2");
int nact = t->Sizes[2];
for (int i=0; i<t->Sizes[0]; i++)
for (int j=0; j<i+1; j++)
for (int a=0; a<t->Sizes[3]; a++)
for (int p=0; p<t->Sizes[2]; p++)
for (int q=0; q<t->Sizes[2]; q++)
{
if (i == j)
Ta->operator()(i,j,p,a) += S2->operator()(q,p)*t->operator()(i,j,q,a);
else {
Ta->operator()(i,j,p,a) += S1->operator()(q,p)*t->operator()(i,j,q,a);
Ta->operator()(i,j,p,a) += S1->operator()(q+nact,p)*t->operator()(j,i,q,a);
Ta->operator()(j,i,p,a) += S1->operator()(q,p+nact)*t->operator()(i,j,q,a);
Ta->operator()(j,i,p,a) += S1->operator()(q+nact,p+nact)*t->operator()(j,i,q,a);
}
}
}
//nothing to do
}
void FJobContext::BackToNonOrthogonal(std::string StringA, std::string StringB) {
if (0 == strcmp(Method.perturberClass, "AAVV")) {
FNdArrayView *t = TN(StringA); t->ClearData();
FNdArrayView *Ta = TN(StringB);
FNdArrayView *S1 = TN("S1");
FNdArrayView *S2 = TN("S2");
int nact = t->Sizes[2];
#pragma omp parallel for schedule(dynamic)
for (int pq=0; pq<t->Sizes[2]*t->Sizes[2]; pq++)
//for (int q=0; q<t->Sizes[2]; q++)
for (int r=0; r<t->Sizes[2]; r++)
for (int s=0; s<t->Sizes[2]; s++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c; b<t->Sizes[0]; b++)
{
int p=pq/t->Sizes[2], q=pq%t->Sizes[2];
if (b == c)
t->operator()(b,c,p,q) += S2->operator()(p,q,r,s)*Ta->operator()(b,c,r,s);
else {
t->operator()(b,c,p,q) += S1->operator()(p,q,r,s) *Ta->operator()(b,c,r,s) + S1->operator()(p,q,r,s+nact) *Ta->operator()(c,b,r,s);
t->operator()(c,b,p,q) += S1->operator()(p,q+nact,r,s)*Ta->operator()(b,c,r,s) + S1->operator()(p,q+nact,r,s+nact)*Ta->operator()(c,b,r,s);
}
}
//in the equations we assume that t[a,b,p,q,] = t[b,a,q,p]
//this equality might be lost in single precision
//so for numerical reasons it is important to explicitly symmetrize
#pragma omp parallel for schedule(dynamic)
for (int p=0; p<t->Sizes[2]; p++)
for (int q=p; q<t->Sizes[2]; q++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c+1; b<t->Sizes[0]; b++)
{
float x = t->operator()(b,c,p,q), y = t->operator()(c,b,q,p);
t->operator()(b,c,p,q) = 0.5*(x+y);
t->operator()(c,b,q,p) = 0.5*(x+y);
x = t->operator()(b,c,q,p); y = t->operator()(c,b,p,q);
t->operator()(b,c,q,p) = 0.5*(x+y);
t->operator()(c,b,p,q) = 0.5*(x+y);
}
}
if (0 == strcmp(Method.perturberClass, "CCAA")) {
FNdArrayView *t = TN(StringA); t->ClearData();
FNdArrayView *Ta = TN(StringB);
FNdArrayView *S1 = TND("S1:aaaa");
FNdArrayView *S2 = TND("S2:aaaa");
for (int p=0; p<t->Sizes[2]; p++)
for (int q=0; q<t->Sizes[2]; q++)
for (int r=0; r<t->Sizes[2]; r++)
for (int s=0; s<t->Sizes[2]; s++)
for (int j=0; j<t->Sizes[0]; j++)
for (int i=j; i<t->Sizes[0]; i++)
{
if (i == j)
t->operator()(i,j,p,q) += S2->operator()(p,q,r,s)*Ta->operator()(i,j,r,s);
else {
t->operator()(i,j,p,q) += S1->operator()(p,q,r,s)*Ta->operator()(i,j,r,s);
t->operator()(j,i,p,q) = 0.0;
}
}
//std::cout << "Norm "<<TND("T:eeaa")->nValues()<<" "<< ct::Dot(TND("T:eeaa")->pData, TND("T:eeaa")->pData, TND("t:eeaa")->nValues())<<std::endl;
}
else if (0 == strcmp(Method.perturberClass, "ACVV")) {
FNdArrayView *t = TN(StringA); t->ClearData();
FNdArrayView *Ta = TN(StringB);
FNdArrayView *S1 = TN("S1");
FNdArrayView *S2 = TN("S2");
int nact = t->Sizes[3];
for (int p=0; p<t->Sizes[3]; p++)
for (int q=0; q<t->Sizes[3]; q++)
for (int i=0; i<t->Sizes[2]; i++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c; b<t->Sizes[0]; b++)
{
if (b == c)
t->operator()(b,c,i,p) += S2->operator()(p,q)*Ta->operator()(b,c,i,q);
else {
t->operator()(b,c,i,p) += S1->operator()(p,q) *Ta->operator()(b,c,i,q);
t->operator()(b,c,i,p) += S1->operator()(p,q+nact) *Ta->operator()(c,b,i,q);
t->operator()(c,b,i,p) += S1->operator()(p+nact,q) *Ta->operator()(b,c,i,q);
t->operator()(c,b,i,p) += S1->operator()(p+nact,q+nact)*Ta->operator()(c,b,i,q);
}
}
}
else if (0 == strcmp(Method.perturberClass, "CCAV")) {
FNdArrayView *t = TN(StringA); t->ClearData();
FNdArrayView *Ta = TN(StringB);
FNdArrayView *S1 = TN("S1");
FNdArrayView *S2 = TN("S2");
int nact = t->Sizes[2];
for (int i=0; i<t->Sizes[0]; i++)
for (int j=0; j<i+1; j++)
for (int a=0; a<t->Sizes[3]; a++)
for (int p=0; p<t->Sizes[2]; p++)
for (int q=0; q<t->Sizes[2]; q++)
{
if (i == j)
t->operator()(i,j,q,a) += S2->operator()(q,p)*Ta->operator()(i,j,p,a);
else {
t->operator()(i,j,q,a) += S1->operator()(q,p)*Ta->operator()(i,j,p,a);
t->operator()(i,j,q,a) += S1->operator()(q,p+nact)*Ta->operator()(j,i,p,a);
t->operator()(j,i,q,a) += S1->operator()(q+nact,p)*Ta->operator()(i,j,p,a);
t->operator()(j,i,q,a) += S1->operator()(q+nact,p+nact)*Ta->operator()(j,i,p,a);
}
}
}
else if (0 == strcmp(Method.perturberClass, "CCVV")) {
FNdArrayView *t = TN(StringA); t->ClearData();
FNdArrayView *Ta = TN(StringB);
for (int i=0; i<t->Sizes[2]; i++)
for (int j=i; j<t->Sizes[2]; j++)
for (int c=0; c<t->Sizes[0]; c++)
for (int b=c; b<t->Sizes[0]; b++)
{
if (b == c) {
t->operator()(b,c,i,j) += (0.*Ta->operator()(b,c,i,j) + Ta->operator()(b,c,j,i))/pow(8,0.5);
t->operator()(b,c,j,i) += (0.*Ta->operator()(b,c,i,j) + Ta->operator()(b,c,j,i))/pow(8,0.5);
}
else {
t->operator()(b,c,i,j) += Ta->operator()(b,c,i,j)*0.0 + Ta->operator()(b,c,j,i)*0.0 + Ta->operator()(c,b,i,j)*0.5/2. - Ta->operator()(c,b,j,i)*0.5/pow(12.0,0.5);
t->operator()(b,c,j,i) += -Ta->operator()(b,c,i,j)*0.0 + Ta->operator()(b,c,j,i)*0.0 + Ta->operator()(c,b,i,j)*0.5/2. + Ta->operator()(c,b,j,i)*0.5/pow(12.0,0.5);
t->operator()(c,b,i,j) += Ta->operator()(b,c,i,j)*0.0 + Ta->operator()(b,c,j,i)*0.0 + Ta->operator()(c,b,i,j)*0.5/2. + Ta->operator()(c,b,j,i)*0.5/pow(12.0,0.5);
t->operator()(c,b,j,i) += Ta->operator()(b,c,i,j)*0.0 + Ta->operator()(b,c,j,i)*0.0 + Ta->operator()(c,b,i,j)*0.5/2. - Ta->operator()(c,b,j,i)*0.5/pow(12.0,0.5);
}
}
}
else if (0 == strcmp(Method.perturberClass, "CAAV")) {
FNdArrayView *t = TN(StringA); t->ClearData();
FNdArrayView *Ta = TN(StringB);
FNdArrayView *S1 = TN("S1");
int ncore = m_Domains['c'].nSize, nact = m_Domains['a'].nSize, nvirt = m_Domains['e'].nSize;
int fullrange = ncore*nact*nact*nvirt;
for (int p=0; p<nact; p++)
for (int q=0; q<nact; q++)
for (int r=0; r<nact; r++)
for (int s=0; s<nact; s++)
for (int a=0; a<nvirt; a++)
for (int i=0; i<ncore; i++)
{
t->pData[i+p*ncore+q*ncore*nact+a*ncore*nact*nact] += Ta->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact]*S1->operator()(p+q*nact,r+s*nact)
+Ta->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact + fullrange]* S1->operator()(p+q*nact,r+s*nact+nact*nact);
t->pData[i+p*ncore+q*ncore*nact+a*ncore*nact*nact+fullrange] += Ta->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact]*S1->operator()(p+q*nact+nact*nact,r+s*nact)
+Ta->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact + fullrange]* S1->operator()(p+q*nact+nact*nact,r+s*nact+nact*nact);
//std::cout<<t->pData[i+r*ncore+s*ncore*nact+a*ncore*nact*nact]<<" "<<S1->operator()(r,s,p,q)<<" "<<Ta->pData[i+p*ncore+q*ncore*nact+a*ncore*nact*nact]<<" "<<i+p*ncore+q*ncore*nact+a*ncore*nact*nact<<" "<<Ta->nValues()<<std::endl;
}
//std::cout << "Norm "<<S1->Strides[0]<<" "<< ct::Dot(S1->pData, S1->pData, S1->nValues())<<std::endl;
//exit(0);
}
}
<file_sep>USE_MPI = yes
USE_INTEL = no
COMPILE_NUMERIC = yes
BOOST=${BOOST_ROOT}
HDF5=${CURC_HDF5_ROOT}
EIGEN=/projects/ilsa8974/apps/eigen/
LIBIGL=/projects/ilsa8974/apps/libigl/include/
SPARSEHASH=/projects/anma2640/sparsehash/src/
FLAGS = -std=c++14 -O3 -I./FCIQMC -I./VMC -I./utils -I./Wavefunctions -I./ICPT -I./ICPT/StackArray/ -I${EIGEN} -I${BOOST} -I${BOOST}/include -I${LIBIGL} -I${HDF5}/include -I${SPARSEHASH} -I/opt/local/include/openmpi-mp/ -fpermissive -w #-DComplex
#FLAGS = -std=c++14 -g -I./utils -I./Wavefunctions -I${EIGEN} -I${BOOST} -I${BOOST}/include -I${LIBIGL} -I/opt/local/include/openmpi-mp/ #-DComplex
GIT_HASH=`git rev-parse HEAD`
COMPILE_TIME=`date`
GIT_BRANCH=`git branch | grep "^\*" | sed s/^..//`
VERSION_FLAGS=-DGIT_HASH="\"$(GIT_HASH)\"" -DCOMPILE_TIME="\"$(COMPILE_TIME)\"" -DGIT_BRANCH="\"$(GIT_BRANCH)\""
INCLUDE_MKL=-I/curc/sw/intel/16.0.3/mkl/include
LIB_MKL = -L/curc/sw/intel/16.0.3/mkl/lib/intel64/ -lmkl_intel_ilp64 -lmkl_gnu_thread -lmkl_core
ifeq ($(USE_INTEL), yes)
FLAGS += -qopenmp
DFLAGS += -qopenmp
ifeq ($(USE_MPI), yes)
CXX = mpiicpc #-mkl
CC = mpiicpc
LFLAGS = -L${BOOST}/stage/lib -lboost_serialization -lboost_mpi -lboost_program_options -lboost_system -lboost_filesystem -L${HDF5}/lib -lhdf5
#CXX = mpicxx
#CC = mpicc
#LFLAGS = -L${BOOST}/lib -lboost_serialization -lboost_mpi -lboost_program_options -lboost_system -lboost_filesystem -lrt -L${HDF5}/lib -lhdf5
else
CXX = icpc
CC = icpc
LFLAGS = -L${BOOST}/stage/lib -lboost_serialization-mt
FLAGS += -DSERIAL
DFLAGS += -DSERIAL
endif
else
FLAGS += -openmp
DFLAGS += -openmp
ifeq ($(USE_MPI), yes)
CXX = mpicxx
CC = mpicxx
LFLAGS = -L${CURC_BOOST_LIB} -lboost_serialization -lboost_mpi -lboost_program_options -lboost_system -lboost_filesystem -L${HDF5}/lib -lhdf5
else
CXX = g++
CC = g++
LFLAGS = -L/opt/local/lib -lboost_serialization-mt
FLAGS += -DSERIAL
DFLAGS += -DSERIAL
endif
endif
# Host specific configurations.
HOSTNAME := $(shell hostname)
ifneq ($(filter dft node%, $(HOSTNAME)),)
include dft.mk
endif
OBJ_VMC = obj/staticVariables.o \
obj/input.o \
obj/integral.o\
obj/SHCIshm.o \
obj/Determinants.o \
obj/Slater.o \
obj/MultiSlater.o \
obj/AGP.o \
obj/Pfaffian.o \
obj/Jastrow.o \
obj/Gutzwiller.o \
obj/CPS.o \
obj/RBM.o \
obj/JRBM.o \
obj/Correlator.o \
obj/SelectedCI.o \
obj/SCPT.o \
obj/SimpleWalker.o \
obj/ShermanMorrisonWoodbury.o\
obj/excitationOperators.o\
obj/statistics.o \
obj/sr.o \
obj/evaluateE.o
OBJ_ICPT= obj/PerturberDependentCode.o \
obj/BlockContract.o \
obj/CxAlgebra.o \
obj/CxIndentStream.o \
obj/CxNumpyArray.o \
obj/icpt.o \
obj/CxMemoryStack.o \
obj/CxStorageDevice.o \
obj/TensorTranspose.o
OBJ_GFMC = obj/staticVariables.o \
obj/input.o \
obj/integral.o\
obj/SHCIshm.o \
obj/Determinants.o \
obj/Slater.o \
obj/AGP.o \
obj/Pfaffian.o \
obj/Jastrow.o \
obj/Gutzwiller.o \
obj/CPS.o \
obj/evaluateE.o \
obj/excitationOperators.o\
obj/ShermanMorrisonWoodbury.o\
obj/statistics.o \
obj/sr.o \
obj/Correlator.o
OBJ_FCIQMC = obj/staticVariables.o \
obj/input.o \
obj/integral.o\
obj/SHCIshm.o \
obj/Determinants.o \
obj/Correlator.o \
obj/runFCIQMC.o \
obj/spawnFCIQMC.o \
obj/walkersFCIQMC.o \
obj/excitGen.o \
obj/utilsFCIQMC.o \
obj/Slater.o \
obj/AGP.o \
obj/Jastrow.o \
obj/SelectedCI.o \
obj/SimpleWalker.o \
obj/ShermanMorrisonWoodbury.o \
obj/excitationOperators.o \
obj/statistics.o \
obj/sr.o \
obj/evaluateE.o
obj/%.o: %.cpp
$(CXX) $(FLAGS) $(OPT) -c $< -o $@
obj/%.o: Wavefunctions/%.cpp
$(CXX) $(FLAGS) $(OPT) -c $< -o $@
obj/%.o: utils/%.cpp
$(CXX) $(FLAGS) $(OPT) -c $< -o $@
obj/%.o: VMC/%.cpp
$(CXX) $(FLAGS) -I./VMC $(OPT) -c $< -o $@
obj/%.o: FCIQMC/%.cpp
$(CXX) $(FLAGS) -I./FCIQMC $(OPT) -c $< -o $@
obj/%.o: ICPT/%.cpp
$(CXX) $(FLAGS) $(INCLUDE_MKL) -I./ICPT/TensorExpressions/ $(OPT) -c $< -o $@
obj/%.o: ICPT/StackArray/%.cpp
$(CXX) $(FLAGS) $(INCLUDE_MKL) $(OPT) -c $< -o $@
ALL= bin/VMC bin/GFMC bin/ICPT bin/FCIQMC
ifeq ($(COMPILE_NUMERIC), yes)
ALL+= bin/periodic
endif
all: $(ALL) #bin/VMC bin/libPeriodic.so
FCIQMC: bin/FCIQMC
bin/periodic:
cd ./NumericPotential/PeriodicIntegrals/ && $(MAKE) -f Makefile && cp a.out ../../bin/periodic
bin/GFMC : $(OBJ_GFMC) executables/GFMC.cpp
$(CXX) $(FLAGS) -I./GFMC $(OPT) -c executables/GFMC.cpp -o obj/GFMC.o $(VERSION_FLAGS)
$(CXX) $(FLAGS) $(OPT) -o bin/GFMC $(OBJ_GFMC) obj/GFMC.o $(LFLAGS) $(VERSION_FLAGS)
bin/ICPT : $(OBJ_ICPT) executables/ICPT.cpp
$(CXX) $(FLAGS) $(INCLUDE_MKL) $(OPT) -c executables/ICPT.cpp -o obj/ICPT.o $(VERSION_FLAGS)
$(CXX) $(FLAGS) $(OPT) -o bin/ICPT $(OBJ_ICPT) obj/ICPT.o $(LFLAGS) $(LIB_MKL) $(VERSION_FLAGS)
bin/VMC : $(OBJ_VMC) executables/VMC.cpp
$(CXX) $(FLAGS) -I./VMC $(OPT) -c executables/VMC.cpp -o obj/VMC.o $(VERSION_FLAGS)
$(CXX) $(FLAGS) $(OPT) -o bin/VMC $(OBJ_VMC) obj/VMC.o $(LFLAGS) $(VERSION_FLAGS)
bin/FCIQMC : $(OBJ_FCIQMC) executables/FCIQMC.cpp
$(CXX) $(FLAGS) -I./FCIQMC $(OPT) -c executables/FCIQMC.cpp -o obj/FCIQMC.o $(VERSION_FLAGS)
$(CXX) $(FLAGS) $(OPT) -o bin/FCIQMC $(OBJ_FCIQMC) obj/FCIQMC.o $(LFLAGS) $(VERSION_FLAGS)
bin/sPT : $(OBJ_sPT)
$(CXX) $(FLAGS) $(OPT) -o bin/sPT $(OBJ_sPT) $(LFLAGS)
bin/CI : $(OBJ_CI)
$(CXX) $(FLAGS) $(OPT) -o bin/CI $(OBJ_CI) $(LFLAGS)
VMC2 : $(OBJ_VMC)
$(CXX) $(FLAGS) $(OPT) -o VMC2 $(OBJ_VMC) $(LFLAGS)
clean :
find . -name "*.o"|xargs rm 2>/dev/null;rm -f bin/* >/dev/null 2>&1
<file_sep>#!/bin/bash
printf "\n\nRunning Tests for FCIQMC\n"
printf "======================================================\n"
MPICOMMAND="mpirun -np 4"
FCIQMCPATH="../../../bin/FCIQMC fciqmc.json"
here=`pwd`
tol=1.0e-7
clean=1
cd $here/FCIQMC/He2
../../clean.sh
printf "...running FCIQMC/He2\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/He2_hb_uniform
../../clean.sh
printf "...running FCIQMC/He2_hb_uniform\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_plateau
../../clean.sh
printf "...running FCIQMC/Ne_plateau\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator
../../clean.sh
printf "...running FCIQMC/Ne_initiator\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator_replica
../../clean.sh
printf "...running FCIQMC/Ne_initiator_replica\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_replica' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator_en2
../../clean.sh
printf "...running FCIQMC/Ne_initiator_en2\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_replica' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/Ne_initiator_en2_ss
../../clean.sh
printf "...running FCIQMC/Ne_initiator_en2_ss\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_replica' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/water_vdz_hb
../../clean.sh
printf "...running FCIQMC/water_vdz_hb\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/N2_fixed_node
../../clean.sh
printf "...running FCIQMC/N2_fixed_node\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/N2_is_ss
../../clean.sh
printf "...running FCIQMC/N2_is_ss\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/H10_free_prop
../../clean.sh
printf "...running FCIQMC/H10_free_prop\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here/FCIQMC/H10_partial_node
../../clean.sh
printf "...running FCIQMC/H10_partial_node\n"
$MPICOMMAND $FCIQMCPATH > fciqmc.out
python2 ../../testEnergy.py 'fciqmc_trial' $tol
if [ $clean == 1 ]
then
../../clean.sh
fi
cd $here
<file_sep>#pragma once
#include <boost/math/special_functions/legendre.hpp>
#include <algorithm>
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace boost;
//gives (l-m)!/(l+m)!
double factorialRatio(int l, int m);
struct CalculateSphHarmonics {
int lmax;
Eigen::VectorXd values;
CalculateSphHarmonics() : lmax(0) {
values.resize( (lmax+1)*(lmax+1));
values.setZero();
}
CalculateSphHarmonics(int plmax) : lmax(plmax)
{
values.resize( (lmax+1)*(lmax+1));
values.setZero();
}
double& getval(int l, int m) {
size_t index = l*l + (l + m);
return values[index];
}
//calculate all the spherical harmonics at theta phi
void populate(double theta, double phi);
};
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <random>
#include <chrono>
#include <complex>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Core>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
//#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include "evaluatePT.h"
#include "MoDeterminants.h"
#include "Determinants.h"
#include "Correlator.h"
#include "Wfn.h"
#include "input.h"
#include "integral.h"
#include "SHCIshm.h"
#include "math.h"
#include "Walker.h"
#include "Davidson.h"
using namespace Eigen;
using namespace boost;
using namespace std;
void getNVariables(int excitationLevel, vector<int> &SingleIndices,
vector<int>& DoubleIndices, int norbs, twoIntHeatBathSHM &I2hb);
void getStochasticGradientContinuousTimeCI(CPSSlater &w, double &E0, vector<int> &SingleIndices,
vector<int>& DoubleIndices, double &stddev,
int &nalpha, int &nbeta, int &norbs,
oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb,
double &coreE, VectorXd &vars, double &rk,
int niter, double targetError);
void getDeterministicCI(CPSSlater &w, double &E0, vector<int> &SingleIndices,
vector<int>& DoubleIndices, double &stddev,
int &nalpha, int &nbeta, int &norbs,
oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb,
double &coreE, VectorXd &vars, double &rk,
int niter, double targetError);
void generateAllDeterminants(vector<Determinant> &allDets, int norbs, int nalpha, int nbeta);
double calcTcorr(vector<double> &v); //in evaluateE.cpp
int main(int argc, char *argv[])
{
#ifndef SERIAL
boost::mpi::environment env(argc, argv);
boost::mpi::communicator world;
#endif
startofCalc = getTime();
initSHM();
license();
string inputFile = "input.dat";
if (argc > 1)
inputFile = string(argv[1]);
if (commrank == 0)
readInput(inputFile, schd);
#ifndef SERIAL
mpi::broadcast(world, schd, 0);
#endif
generator = std::mt19937(schd.seed + commrank);
twoInt I2;
oneInt I1;
int norbs, nalpha, nbeta;
double coreE = 0.0;
std::vector<int> irrep;
readIntegrals("FCIDUMP", I2, I1, nalpha, nbeta, norbs, coreE, irrep);
//initialize the heatbath integrals
std::vector<int> allorbs;
for (int i = 0; i < norbs; i++)
allorbs.push_back(i);
twoIntHeatBath I2HB(1.e-10);
twoIntHeatBathSHM I2HBSHM(1.e-10);
if (commrank == 0)
I2HB.constructClass(allorbs, I2, I1, norbs);
I2HBSHM.constructClass(norbs, I2HB);
//Setup static variables
Determinant::EffDetLen = (norbs) / 64 + 1;
Determinant::norbs = norbs;
MoDeterminant::norbs = norbs;
MoDeterminant::nalpha = nalpha;
MoDeterminant::nbeta = nbeta;
//Setup Slater Determinants
HforbsA = MatrixXd::Zero(norbs, norbs);
HforbsB = MatrixXd::Zero(norbs, norbs);
readHF(HforbsA, HforbsB, schd.uhf);
//Setup CPS wavefunctions
std::vector<Correlator> nSiteCPS;
for (auto it = schd.correlatorFiles.begin(); it != schd.correlatorFiles.end();
it++)
{
readCorrelator(it->second, it->first, nSiteCPS);
}
vector<Determinant> detList;
vector<double> ciExpansion;
if (boost::iequals(schd.determinantFile, ""))
{
detList.resize(1);
ciExpansion.resize(1, 1.0);
for (int i = 0; i < nalpha; i++)
detList[0].setoccA(i, true);
for (int i = 0; i < nbeta; i++)
detList[0].setoccB(i, true);
}
else
{
readDeterminants(schd.determinantFile, detList, ciExpansion);
}
//setup up wavefunction
CPSSlater wave(nSiteCPS, detList, ciExpansion);
size_t size;
ifstream file("params.bin", ios::in | ios::binary | ios::ate);
if (commrank == 0)
{
size = file.tellg();
}
#ifndef SERIAL
MPI_Bcast(&size, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
Eigen::VectorXd vars = Eigen::VectorXd::Zero(size / sizeof(double));
if (commrank == 0)
{
file.seekg(0, ios::beg);
file.read((char *)(&vars[0]), size);
file.close();
}
#ifndef SERIAL
MPI_Bcast(&vars[0], vars.rows(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if ((schd.uhf && vars.size() != wave.getNumVariables() + 2 * norbs * norbs) ||
(!schd.uhf && vars.size() != wave.getNumVariables() + norbs * norbs))
{
cout << "number of variables on disk: " << vars.size() << " is not equal to wfn parameters: " << wave.getNumVariables() << endl;
exit(0);
}
wave.updateVariables(vars);
int numVars = wave.getNumVariables();
for (int i = 0; i < norbs; i++)
{
for (int j = 0; j < norbs; j++)
{
if (!schd.uhf)
{
HforbsA(i, j) = vars[numVars + i * norbs + j];
HforbsB(i, j) = vars[numVars + i * norbs + j];
}
else
{
HforbsA(i, j) = vars[numVars + i * norbs + j];
HforbsB(i, j) = vars[numVars + norbs * norbs + i * norbs + j];
}
}
}
MatrixXd alpha(norbs, nalpha), beta(norbs, nbeta);
alpha = HforbsA.block(0, 0, norbs, nalpha);
beta = HforbsB.block(0, 0, norbs, nbeta);
MoDeterminant det(alpha, beta);
vector<int> SingleSpinIndices, DoubleSpinIndices;
getNVariables(schd.excitationLevel, SingleSpinIndices, DoubleSpinIndices, norbs, I2HBSHM);
//we assume intermediate normalization
Eigen::VectorXd civars = Eigen::VectorXd::Zero(SingleSpinIndices.size() / 2 +
1 + DoubleSpinIndices.size() / 4);
double rt = 0., stddev, E0 = 0.;
if (!schd.deterministic)
getStochasticGradientContinuousTimeCI(wave, E0, SingleSpinIndices, DoubleSpinIndices,
stddev, nalpha, nbeta, norbs,
I1, I2, I2HBSHM, coreE, civars, rt,
schd.stochasticIter, 0.5e-3);
else
getDeterministicCI(wave, E0, SingleSpinIndices, DoubleSpinIndices,
stddev, nalpha, nbeta, norbs,
I1, I2, I2HBSHM, coreE, civars, rt,
schd.stochasticIter, 0.5e-3);
boost::interprocess::shared_memory_object::remove(shciint2.c_str());
boost::interprocess::shared_memory_object::remove(shciint2shm.c_str());
return 0;
}
void getNVariables(int excitationLevel, vector<int> &SingleIndices, vector<int>& DoubleIndices,
int norbs, twoIntHeatBathSHM &I2hb)
{
for (int i = 0; i < 2 * norbs; i++)
for (int j = 0; j < 2 * norbs; j++)
{
//if (I2hb.Singles(i, j) > schd.epsilon )
if (i%2 == j%2)
{
SingleIndices.push_back(i);
SingleIndices.push_back(j);
}
}
for (int i=0; i < 2*norbs; i++) {
for (int j=i+1; j < 2*norbs; j++) {
int pair = (j/2) * (j/2 + 1)/2 + i/2;
size_t start = i%2 == j%2 ? I2hb.startingIndicesSameSpin[pair] : I2hb.startingIndicesOppositeSpin[pair];
size_t end = i%2 == j%2 ? I2hb.startingIndicesSameSpin[pair+1] : I2hb.startingIndicesOppositeSpin[pair+1];
float *integrals = i%2 == j%2 ? I2hb.sameSpinIntegrals : I2hb.oppositeSpinIntegrals;
short *orbIndices = i%2 == j%2 ? I2hb.sameSpinPairs : I2hb.oppositeSpinPairs;
for (size_t index = start; index < end; index++) {
if (fabs(integrals[index]) < schd.epsilon)
break;
int a = 2 * orbIndices[2* index] + i%2, b = 2 * orbIndices[2 * index] + j%2;
DoubleIndices.push_back(i); DoubleIndices.push_back(j);
DoubleIndices.push_back(a); DoubleIndices.push_back(b);
}
}
}
//SingleIndices.resize(4); DoubleIndices.resize(8);
/*
for (int i=0; i<SingleIndices.size()/2; i++) {
for (int j=i+1; j<SingleIndices.size()/2; j++) {
int I = SingleIndices[2*i], A = SingleIndices[2*i+1],
J = SingleIndices[2*j], B = SingleIndices[2*j+1];
if (I == A || J == A || I == B || J == B ||
I == J || A == B) continue;
DoubleIndices.push_back(I);
DoubleIndices.push_back(J);
DoubleIndices.push_back(A);
DoubleIndices.push_back(B);
//cout << I<<" "<<J<<" "<<A<<" "<<B<<endl;
}
}
*/
//exit(0);
return;
}
void getStochasticGradientContinuousTimeCI(CPSSlater &w, double &E0, vector<int> &SingleIndices,
vector<int>& DoubleIndices, double &stddev,
int &nalpha, int &nbeta, int &norbs,
oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb,
double &coreE, VectorXd &civars, double &rk,
int niter, double targetError)
{
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
//initialize the walker
Determinant d;
bool readDeterminant = false;
char file[5000];
sprintf(file, "BestDeterminant.txt");
{
ifstream ofile(file);
if (ofile)
readDeterminant = true;
}
if (readDeterminant)
{
if (commrank == 0)
{
std::ifstream ifs(file, std::ios::binary);
boost::archive::binary_iarchive load(ifs);
load >> d;
}
#ifndef SERIAL
MPI_Bcast(&d.reprA, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&d.reprB, DetLen, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
Walker walk(d);
walk.initUsingWave(w);
int maxTerms = (nalpha) * (norbs - nalpha); //pick a small number that will be incremented later
vector<double> ovlpRatio(maxTerms);
vector<size_t> excitation1(maxTerms), excitation2(maxTerms);
vector<double> HijElements(maxTerms);
int nExcitations = 0;
vector<double> ovlpRatioForM(maxTerms);
vector<size_t> excitation1ForM(maxTerms), excitation2ForM(maxTerms);
vector<double> HijElementsForM(maxTerms);
int nExcitationsForM = 0;
stddev = 1.e4;
int iter = 0;
double M1 = 0., S1 = 0., Eavg = 0.;
double Eloc = 0.;
double ham = 0., ovlp = 0.;
double scale = 1.0;
VectorXd hamRatio = VectorXd::Zero(civars.rows());
VectorXd gradRatio = VectorXd::Zero(civars.rows());
MatrixXd Hamiltonian(civars.rows(), civars.rows());
MatrixXd Overlap(civars.rows(), civars.rows());
MatrixXd iterHamiltonian(civars.rows(), civars.rows());
MatrixXd iterOverlap(civars.rows(), civars.rows());
VectorXd localGrad;
double bestOvlp = 0.;
Determinant bestDet = d;
//schd.epsilon = -1;
nExcitations = 0;
E0 = walk.d.Energy(I1, I2, coreE);
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, false);
gradRatio.setZero();
double factor = 1.0;
w.OvlpRatioCI(walk, gradRatio, I1, I2, SingleIndices, DoubleIndices, I2hb, coreE, factor);
hamRatio = E0 * gradRatio;
for (int m = 0; m < nExcitations; m++)
{
Walker wtmp = walk;
//this is the new walker m, later I should try to get rid of this step
wtmp.updateWalker(w, excitation1[m], excitation2[m]);
double factor = HijElements[m] * ovlpRatio[m];
w.OvlpRatioCI(wtmp, hamRatio, I1, I2,
SingleIndices, DoubleIndices, I2hb, coreE, factor);
}
//updateHamOverlap(iterHamiltonian, iterOverlap, hamRatio, gradRatio, SingleIndices);
iterHamiltonian = gradRatio*hamRatio.transpose();
iterOverlap = gradRatio*gradRatio.transpose();
Hamiltonian = iterHamiltonian;
Overlap = iterOverlap;
int nstore = 1000000 / commsize;
int gradIter = min(nstore, niter);
std::vector<double> gradError(gradIter * commsize, 0);
bool reset = false;
double cumdeltaT = 0., cumdeltaT2 = 0.;
while (iter < niter && stddev > targetError)
{
double cumovlpRatio = 0;
//when using uniform probability 1./numConnection * max(1, pi/pj)
for (int i = 0; i < nExcitations; i++)
{
cumovlpRatio += abs(ovlpRatio[i]);
//cumovlpRatio += min(1.0, pow(ovlpRatio[i], 2));
ovlpRatio[i] = cumovlpRatio;
}
//double deltaT = -log(random())/(cumovlpRatio);
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(ovlpRatio.begin(), (ovlpRatio.begin() + nExcitations),
nextDetRandom) -
ovlpRatio.begin();
cumdeltaT += deltaT;
cumdeltaT2 += deltaT * deltaT;
double Elocold = Eloc;
double ratio = deltaT / cumdeltaT;
Hamiltonian += ratio * (iterHamiltonian - Hamiltonian);
Overlap += ratio * (iterOverlap - Overlap);
Eloc = Eloc + deltaT * (ham - Eloc) / (cumdeltaT); //running average of energy
//cout << Hamiltonian(0,0)<<" "<<Eloc<<" "<<iterHamiltonian(1,1)<<" "<<iterOverlap(1,1)<<endl;
S1 = S1 + (ham - Elocold) * (ham - Eloc);
if (iter < gradIter)
gradError[iter + commrank * gradIter] = ham;
iter++;
//update the walker
if (true)
{
walk.updateWalker(w, excitation1[nextDet], excitation2[nextDet]);
}
nExcitations = 0;
double E0 = walk.d.Energy(I1, I2, coreE);
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, false);
gradRatio.setZero();
double factor = 1.0;
//gradRatio[0] = 1.0;
w.OvlpRatioCI(walk, gradRatio, I1, I2, SingleIndices, DoubleIndices, I2hb, coreE, factor);
//<m|Psi_i>/<n|Psi0>
hamRatio = E0 * gradRatio;
for (int m = 0; m < nExcitations; m++)
{
Walker wtmp = walk;
wtmp.updateWalker(w, excitation1[m], excitation2[m]);
double factor = HijElements[m] * ovlpRatio[m];
//hamRatio[0] += factor;
w.OvlpRatioCI(wtmp, hamRatio, I1, I2,
SingleIndices, DoubleIndices, I2hb, coreE, factor);
}
iterHamiltonian = gradRatio*hamRatio.transpose();
iterOverlap = gradRatio*gradRatio.transpose();
//updateHamOverlap(iterHamiltonian, iterOverlap, hamRatio, gradRatio, SingleIndices);
if (abs(ovlp) > bestOvlp)
{
bestOvlp = abs(ovlp);
bestDet = walk.d;
}
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(gradError[0]), gradError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Hamiltonian(0, 0)), Hamiltonian.rows() * Hamiltonian.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Overlap(0, 0)), Overlap.rows() * Overlap.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &Eloc, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
//if (commrank == 0)
rk = calcTcorr(gradError);
Hamiltonian /= (commsize);
Overlap /= (commsize);
E0 = Eloc / commsize;
stddev = sqrt(S1 * rk / (niter - 1) / niter / commsize);
#ifndef SERIAL
MPI_Bcast(&stddev, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if (commrank == 0)
{
MatrixXcd eigenvectors; VectorXcd eigenvalues;
VectorXd betas;
GeneralizedEigen(Hamiltonian, Overlap, eigenvalues, eigenvectors, betas);
//GeneralizedEigenSolver<MatrixXd> ges(Hamiltonian, Overlap);
double lowest = Hamiltonian(0,0)/Overlap(0,0);
MatrixXcd eigenvecInv = eigenvectors.inverse();
int vecIndex = 0;
for (int i=0; i<Hamiltonian.rows(); i++) {
if (abs(betas.transpose()(i)) > 1.e-10) {
if (eigenvalues.transpose()(i).real() < lowest) {
lowest = eigenvalues.transpose()(i).real();
vecIndex = i;
}
}
}
double norm = std::abs((eigenvectors.col(vecIndex).adjoint()*(Overlap*eigenvectors.col(vecIndex)))(0,0));
double a0 = std::norm((Overlap*eigenvectors.col(vecIndex))(0,0)/pow(Overlap(0,0),0.5))/norm;
double e0 = (Hamiltonian(0,0)/Overlap(0,0));
std::cout << format("%18s : %14.8f (%8.2e)") % ("VMC energy") % e0 % stddev<<endl;
std::cout << format("%18s : %14.8f (%8.2e)") % ("CISD energy") % (lowest) % stddev<<endl;
double de = lowest - e0;
double plusQ = (1 - a0)*de/a0;
std::cout << format("%18s : %14.8f (%8.2e)") % ("CISD+Q energy") % (lowest+plusQ) % stddev<<endl;
}
if (commrank == 0) {
Hamiltonian /= Overlap(0,0);
Overlap /= Overlap(0,0);
double E0 = Hamiltonian(0,0)/Overlap(0,0);
MatrixXd Uo = MatrixXd::Zero(Hamiltonian.rows(), Hamiltonian.cols());
Uo(0,0) = 1.0;
for (int i=1; i<Uo.rows(); i++) {
Uo(0, i) = - Overlap(0,i);
Uo(i, i) = 1.0;
}
Overlap = Uo.transpose()* (Overlap * Uo);
Hamiltonian = Uo.transpose()* (Hamiltonian * Uo);
VectorXd Vpsi0 = Hamiltonian.block(1,0,Overlap.rows()-1, 1);
MatrixXd temp = Overlap;
Overlap = temp.block(1,1, Overlap.rows()-1, Overlap.rows()-1);
temp = Hamiltonian;
Hamiltonian = temp.block(1,1, temp.rows()-1, temp.rows()-1);
MatrixXd eigenvectors; VectorXd eigenvalues;
SelfAdjointEigen(Overlap, eigenvalues, eigenvectors);
int nCols = 0;
for (int i=0; i<Overlap.rows(); i++)
if ( eigenvalues(i) > 1.e-8)
nCols ++;
MatrixXd U = MatrixXd::Zero(Overlap.rows(), nCols);
int index = 0;
for (int i=0; i<Overlap.rows(); i++)
if ( eigenvalues(i) > 1.e-8) {
U.col(index) = eigenvectors.col(i)/pow(eigenvalues(i), 0.5);
index++;
}
MatrixXd Hprime = U.transpose()*(Hamiltonian * U);
MatrixXd Hprime_E0 = 1.*Hprime;
for (int i=0; i<Hprime.rows(); i++) {
Hprime_E0(i,i) -= E0;
}
VectorXd temp1 = Vpsi0;
Vpsi0 = U.transpose()*temp1;
VectorXd psi1;
SolveEigen(Hprime_E0, Vpsi0, psi1);
double E2 = -Vpsi0.transpose()*psi1;
std::cout << format("%18s : %14.8f (%8.2e)") % ("E0+E2 energy") % (E0+E2) % stddev<<endl;
}
}
void getDeterministicCI(CPSSlater &w, double &E0, vector<int> &SingleIndices,
vector<int>& DoubleIndices, double &stddev,
int &nalpha, int &nbeta, int &norbs,
oneInt &I1, twoInt &I2, twoIntHeatBathSHM &I2hb,
double &coreE, VectorXd &civars, double &rk,
int niter, double targetError)
{
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
int maxTerms = 1000000; //pick a small number that will be incremented later
vector<double> ovlpRatio(maxTerms);
vector<size_t> excitation1(maxTerms), excitation2(maxTerms);
vector<double> HijElements(maxTerms);
int nExcitations = 0;
double Energy = 0.0;
VectorXd hamRatio = VectorXd::Zero(civars.rows());
VectorXd gradRatio = VectorXd::Zero(civars.rows());
MatrixXd Hamiltonian = MatrixXd::Zero(civars.rows(), civars.rows());
MatrixXd Overlap = MatrixXd::Zero(civars.rows(), civars.rows());
VectorXd localGrad;
for (int i = commrank; i < allDets.size(); i += commsize)
{
Walker walk(allDets[i]);
walk.initUsingWave(w);
double ham, ovlp;
{
nExcitations = 0;
E0 = walk.d.Energy(I1, I2, coreE);
w.HamAndOvlpGradient(walk, ovlp, ham, localGrad, I1, I2, I2hb, coreE, ovlpRatio,
excitation1, excitation2, HijElements, nExcitations, false);
gradRatio.setZero();
double factor = 1.0;
w.OvlpRatioCI(walk, gradRatio, I1, I2, SingleIndices, DoubleIndices, I2hb, coreE, factor);
hamRatio = E0 * gradRatio;
for (int m = 0; m < nExcitations; m++)
{
Walker wtmp = walk;
//this is the new walker m, later I should try to get rid of this step
wtmp.updateWalker(w, excitation1[m], excitation2[m]);
double factor = HijElements[m] * ovlpRatio[m];
w.OvlpRatioCI(wtmp, hamRatio, I1, I2,
SingleIndices, DoubleIndices, I2hb, coreE, factor);
}
}
Hamiltonian += gradRatio*hamRatio.transpose() * ovlp * ovlp;
Overlap += gradRatio*gradRatio.transpose() * ovlp * ovlp;
Energy += ham * ovlp * ovlp;
}
//cout << Energy/Overlap(0,0) << endl;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(Hamiltonian(0, 0)), Hamiltonian.rows() * Hamiltonian.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(Overlap(0, 0)), Overlap.rows() * Overlap.cols(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
//MPI_Allreduce(MPI_IN_PLACE, &Eloc, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
//Hamiltonian /= (commsize);
//Overlap /= (commsize);
//E0 = Eloc / commsize;
if (commrank == 0)
{
MatrixXcd eigenvectors; VectorXcd eigenvalues;
VectorXd betas;
GeneralizedEigen(Hamiltonian, Overlap, eigenvalues, eigenvectors, betas);
//GeneralizedEigenSolver<MatrixXd> ges(Hamiltonian, Overlap);
double lowest = Hamiltonian(0,0)/Overlap(0,0);
MatrixXcd eigenvecInv = eigenvectors.inverse();
int vecIndex = 0;
for (int i=0; i<Hamiltonian.rows(); i++) {
if (abs(betas.transpose()(i)) > 1.e-10) {
if (eigenvalues.transpose()(i).real() < lowest) {
lowest = eigenvalues.transpose()(i).real();
vecIndex = i;
}
}
}
double norm = std::abs((eigenvectors.col(vecIndex).adjoint()*(Overlap*eigenvectors.col(vecIndex)))(0,0));
double a0 = std::norm((Overlap*eigenvectors.col(vecIndex))(0,0)/pow(Overlap(0,0),0.5))/norm;
double e0 = (Hamiltonian(0,0)/Overlap(0,0));
std::cout << format("%18s : %14.8f (%8.2e)") % ("VMC energy") % e0 % stddev<<endl;
std::cout << format("%18s : %14.8f (%8.2e)") % ("CISD energy") % (lowest) % stddev<<endl;
double de = lowest - e0;
double plusQ = (1 - a0)*de/a0;
std::cout << format("%18s : %14.8f (%8.2e)") % ("CISD+Q energy") % (lowest+plusQ) % stddev<<endl;
}
if (commrank == 0) {
Hamiltonian /= Overlap(0,0);
Overlap /= Overlap(0,0);
double E0 = Hamiltonian(0,0)/Overlap(0,0);
MatrixXd Uo = MatrixXd::Zero(Hamiltonian.rows(), Hamiltonian.cols());
Uo(0,0) = 1.0;
for (int i=1; i<Uo.rows(); i++) {
Uo(0, i) = - Overlap(0,i);
Uo(i, i) = 1.0;
}
Overlap = Uo.transpose()* (Overlap * Uo);
Hamiltonian = Uo.transpose()* (Hamiltonian * Uo);
VectorXd Vpsi0 = Hamiltonian.block(1,0,Overlap.rows()-1, 1);
MatrixXd temp = Overlap;
Overlap = temp.block(1,1, Overlap.rows()-1, Overlap.rows()-1);
temp = Hamiltonian;
Hamiltonian = temp.block(1,1, temp.rows()-1, temp.rows()-1);
MatrixXd eigenvectors; VectorXd eigenvalues;
SelfAdjointEigen(Overlap, eigenvalues, eigenvectors);
int nCols = 0;
for (int i=0; i<Overlap.rows(); i++)
if ( eigenvalues(i) > 1.e-8)
nCols ++;
MatrixXd U = MatrixXd::Zero(Overlap.rows(), nCols);
int index = 0;
for (int i=0; i<Overlap.rows(); i++)
if ( eigenvalues(i) > 1.e-8) {
U.col(index) = eigenvectors.col(i)/pow(eigenvalues(i), 0.5);
index++;
}
MatrixXd Hprime = U.transpose()*(Hamiltonian * U);
MatrixXd Hprime_E0 = 1.*Hprime;
for (int i=0; i<Hprime.rows(); i++) {
Hprime_E0(i,i) -= E0;
}
VectorXd temp1 = Vpsi0;
Vpsi0 = U.transpose()*temp1;
VectorXd psi1;
SolveEigen(Hprime_E0, Vpsi0, psi1);
double E2 = -Vpsi0.transpose()*psi1;
std::cout << format("%18s : %14.8f (%8.2e)") % ("E0+E2 energy") % (E0+E2) % stddev<<endl;
}
}
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef CX_DEFS_H
#define CX_DEFS_H
#define AIC_NO_THROW throw()
#define CX_NO_THROW AIC_NO_THROW
// define macros for restricted pointer extensions. By defining a
// pointer as ``restricted'', we promise the compiler that
// the pointer is not aliased in the current scope
#ifdef __GNUC__ // g++
#define AIC_RP __restrict__
#elif _MSC_VER // microsoft c++. intel c++ may also understand this syntax.
#define AIC_RP __restrict
#elif __INTEL_COMPILER
// compile with -restrict command line option (linux) or -Qrestrict (windows).
#define AIC_RP restrict
#else
#define AIC_RP
#endif
#define RESTRICT AIC_RP
#ifdef assert
#undef assert
#endif
#ifdef assert_rt
#undef assert_rt
#endif
void AicAssertFail( char const *pExpr, char const *pFile, int iLine );
#define assert_rt(x) if(x) {} else AicAssertFail(#x,__FILE__,__LINE__)
#ifdef _DEBUG
#define assert(x) assert_rt(x)
#else
#define assert(x) ((void) 0)
#endif
#ifdef _SINGLE_PRECISION
typedef float FScalar;
#else
typedef double FScalar;
#endif
#endif // CX_DEFS_H
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INTEGRAL_HEADER_H
#define INTEGRAL_HEADER_H
#include <vector>
#include <string>
#include <iostream>
#include <Eigen/Dense>
#include <map>
#include <utility>
#include "iowrapper.h"
#include <boost/interprocess/managed_shared_memory.hpp>
#include "global.h"
using namespace std;
using namespace Eigen;
bool myfn(double i, double j);
class compAbs {
public:
bool operator()(const float& a, const float& b) const { return fabs(a) < fabs(b); }
bool operator()(const complex<double>& a, const complex<double>& b) const { return std::abs(a) < std::abs(b); }
};
class oneInt {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version){ ar & store & norbs; }
public:
std::vector<double> store;
int norbs;
//I explicitly store all elements of the matrix
//so for normal operator if i and j dont have the same spin
//then it will just return zero. If we have SOC and
// i and j have different spin then it can be a complex number.
inline double& operator()(int i, int j) { return store.at(i*norbs+j); }
inline double operator()(int i, int j) const { return store.at(i*norbs+j); }
};
class twoInt {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version){
ar & maxEntry \
& Direct \
& Exchange \
& zero \
& norbs \
& npair \
& ksym;
}
public:
double* store;
double maxEntry;
MatrixXd Direct, Exchange;
double zero ;
size_t norbs;
size_t npair;
size_t inner;
size_t virt;
size_t nii;
size_t niv;
size_t nvv;
size_t niiii;
size_t niiiv;
size_t niviv;
size_t niivv;
bool ksym;
twoInt() :zero(0.0),maxEntry(100.) {}
inline double& operator()(int i, int j, int k, int l) {
zero = 0.0;
if (!((i%2 == j%2) && (k%2 == l%2))) return zero;
int I=i/2;int J=j/2;int K=k/2;int L=l/2;
if(!ksym) {
//unsigned int IJ = max(I,J)*(max(I,J)+1)/2 + min(I,J);
//unsigned int KL = max(K,L)*(max(K,L)+1)/2 + min(K,L);
//unsigned int A = max(IJ,KL), B = min(IJ,KL);
//return store[A*(A+1)/2+B];
//unsigned int IJ = min(I,J) * norbs -(min(I,J) * (min(I,J) - 1)) / 2 + max(I,J) - min(I,J);
//unsigned int KL = min(K,L) * norbs -(min(K,L)* (min(K,L) - 1)) / 2 + max(K,L) - min(K,L);
size_t IJ, KL;
bool iv1 = false, iv2 = false;
if (I < inner && J < inner) IJ = max(I,J)*(max(I,J)+1)/2 + min(I,J);
else if (I >= inner && J >= inner) IJ = inner*(inner+1)/2 + inner*virt + max(I-inner,J-inner)*(max(I-inner,J-inner)+1)/2 + min(I-inner,J-inner);
else {IJ = inner*(inner+1)/2 + inner*(max(I,J)-inner) + min(I,J); iv1 = true;}
if (K < inner && L < inner) KL = max(K,L)*(max(K,L)+1)/2 + min(K,L);
else if (K >= inner && L >= inner) KL = inner*(inner+1)/2 + inner*virt + max(K-inner,L-inner)*(max(K-inner,L-inner)+1)/2 + min(K-inner,L-inner);
else {KL = inner*(inner+1)/2 + inner*(max(K,L)-inner) + min(K,L); iv2 = true;}
size_t ind;
if (iv1 && iv2) ind = niiii + niiiv + niivv + max(IJ-nii,KL-nii)*(max(IJ-nii,KL-nii)+1)/2 + min(IJ-nii,KL-nii);
else ind = min(IJ,KL) * npair - (min(IJ,KL) * (min(IJ,KL) - 1)) / 2 + max(IJ,KL) - min(IJ,KL);
//cout << I << " " << J << " " << K << " " << L << " " << IJ << " " << KL << " " << ind << endl;
return store[ind];
} else {
unsigned int IJ = I*norbs+J, KL = K*norbs+L;
unsigned int A = max(IJ,KL), B = min(IJ,KL);
return store[A*(A+1)/2+B];
}
}
inline double operator()(int i, int j, int k, int l) const {
double zero = 0.0;
if (!((i%2 == j%2) && (k%2 == l%2))) return zero;
int I=i/2;int J=j/2;int K=k/2;int L=l/2;
if(!ksym) {
//unsigned int IJ = max(I,J)*(max(I,J)+1)/2 + min(I,J);
//unsigned int KL = max(K,L)*(max(K,L)+1)/2 + min(K,L);
//unsigned int A = max(IJ,KL), B = min(IJ,KL);
//return store[A*(A+1)/2+B];
//unsigned int IJ = min(I,J) * norbs -(min(I,J) * (min(I,J) - 1)) / 2 + max(I,J) - min(I,J);
//unsigned int KL = min(K,L) * norbs -(min(K,L)* (min(K,L) - 1)) / 2 + max(K,L) - min(K,L);
size_t IJ, KL;
bool iv1 = false, iv2 = false;
if (I < inner && J < inner) IJ = max(I,J)*(max(I,J)+1)/2 + min(I,J);
else if (I >= inner && J >= inner) IJ = inner*(inner+1)/2 + inner*virt + max(I-inner,J-inner)*(max(I-inner,J-inner)+1)/2 + min(I-inner,J-inner);
else {IJ = inner*(inner+1)/2 + inner*(max(I,J)-inner) + min(I,J); iv1 = true;}
if (K < inner && L < inner) KL = max(K,L)*(max(K,L)+1)/2 + min(K,L);
else if (K >= inner && L >= inner) KL = inner*(inner+1)/2 + inner*virt + max(K-inner,L-inner)*(max(K-inner,L-inner)+1)/2 + min(K-inner,L-inner);
else {KL = inner*(inner+1)/2 + inner*(max(K,L)-inner) + min(K,L); iv2 = true;}
size_t ind;
if (iv1 && iv2) ind = niiii + niiiv + niivv + max(IJ-nii,KL-nii)*(max(IJ-nii,KL-nii)+1)/2 + min(IJ-nii,KL-nii);
else ind = min(IJ,KL) * npair - (min(IJ,KL) * (min(IJ,KL) - 1)) / 2 + max(IJ,KL) - min(IJ,KL);
return store[ind];
} else {
unsigned int IJ = I*norbs+J, KL = K*norbs+L;
unsigned int A = max(IJ,KL), B = min(IJ,KL);
return store[A*(A+1)/2+B];
}
}
};
class twoIntHeatBath {
public:
//i,j,a,b are spatial orbitals
//first pair is i,j (i>j)
//the map contains a list of integral which are equal to (ia|jb) where a,b are the second pair
//if the integrals are for the same spin you have to separately store (ia|jb) and (ib|ja)
//for opposite spin you just have to store for a>b because the integral is (ia|jb) - (ib|ja)
//now this class is made by just considering integrals that are smaller than threshhold
std::map<std::pair<short,short>, std::multimap<float, std::pair<short,short>, compAbs > > sameSpin;
std::map<std::pair<short,short>, std::multimap<float, std::pair<short,short>, compAbs > > oppositeSpin;
std::map<std::pair<short,short>, std::multimap<float, short, compAbs > > singleIntegrals;
MatrixXd Singles;
double epsilon;
double zero ;
twoIntHeatBath(double epsilon_) :zero(0.0),epsilon(fabs(epsilon_)) {}
//the orbs contain all orbitals used to make the ij pair above
//typically these can be all orbitals of the problem or just the active space ones
//ab will typically contain all orbitals(norbs)
void constructClass(std::vector<int>& orbs, twoInt& I2, oneInt& I1, int ncore, int nact, bool cas=false) {
int first_virtual = ncore + nact;
int s = nact;
if (cas) s = orbs.size();
for (int i=0; i<s; i++) {
for (int j=0;j<=i;j++) {
std::pair<short,short> IJ=make_pair(i,j);
int start = 0;
int end = orbs.size();
if (cas) {start = ncore; end = first_virtual;}
for (int a=start; a<end; a++) {
if (fabs(I2(2*i, 2*j, 2*a, 2*a) - I2(2*i, 2*a, 2*a, 2*j)) > epsilon)
singleIntegrals[IJ].insert(pair<float, short>(I2(2*i, 2*j, 2*a, 2*a) - I2(2*i, 2*a, 2*a, 2*j), 2*a));
if (fabs(I2(2*i, 2*j, 2*a+1, 2*a+1) ) > epsilon)
singleIntegrals[IJ].insert(pair<float, short>(I2(2*i, 2*j, 2*a+1, 2*a+1), 2*a+1));
}
}
}
s = orbs.size();
for (int i=0; i<s; i++) {
for (int j=0;j<=i;j++) {
std::pair<short,short> IJ=make_pair(i,j);
//sameSpin[IJ]=std::map<double, std::pair<int,int> >();
//oppositeSpin[IJ]=std::map<double, std::pair<int,int> >();
for (int a=ncore; a<first_virtual; a++) {
for (int b=ncore; b<first_virtual; b++) {
//opposite spin
if (fabs(I2(2*i, 2*a, 2*j, 2*b)) > epsilon)
oppositeSpin[IJ].insert(pair<float, std::pair<short,short> >(I2(2*i, 2*a, 2*j, 2*b), make_pair(a,b)));
//samespin
if (a>=b && fabs(I2(2*i,2*a,2*j,2*b) - I2(2*i,2*b,2*j,2*a)) > epsilon) {
sameSpin[IJ].insert(pair<float, std::pair<short,short> >( I2(2*i,2*a,2*j,2*b) - I2(2*i,2*b,2*j,2*a), make_pair(a,b)));
//sameSpin[IJ][fabs(I2(2*i,2*a,2*j,2*b) - I2(2*i,2*b,2*j,2*a))] = make_pair<int,int>(a,b);
}
}
}
}
} // ij
Singles = MatrixXd::Zero(2*nact, 2*nact);
if (!cas) {
for (int i=0; i<2*nact; i++) {
for (int a=0; a<2*nact; a++) {
Singles(i,a) = std::abs(I1(i,a));
for (int j=0; j<2*orbs.size(); j++) {
//if (fabs(Singles(i,a)) < fabs(I2(i,a,j,j) - I2(i, j, j, a)))
Singles(i,a) += std::abs(I2(i,a,j,j) - I2(i, j, j, a));
}
}
}
}
} // end constructClass
};
class twoIntHeatBathSHM {
public:
float* sameSpinIntegrals;
float* oppositeSpinIntegrals;
float* singleIntegrals;
size_t* startingIndicesSameSpin;
size_t* startingIndicesOppositeSpin;
size_t* startingIndicesSingleIntegrals;
short* sameSpinPairs;
short* oppositeSpinPairs;
short* singleIntegralsPairs;
MatrixXd Singles;
//for each pair i,j it has sum_{a>b} abs((ai|bj)-(aj|bi)) if they are same spin
//and sum_{ab} abs(ai|bj) if they are opposite spins
MatrixXd sameSpinPairExcitations;
MatrixXd oppositeSpinPairExcitations;
double epsilon;
twoIntHeatBathSHM(double epsilon_) : epsilon(fabs(epsilon_)) {}
void constructClass(int norbs, twoIntHeatBath& I2, bool cas) ;
void getIntegralArray(int i, int j, const float* &integrals,
const short* &orbIndices, size_t& numIntegrals) const ;
void getIntegralArrayCAS(int i, int j, const float* &integrals,
const short* &orbIndices, size_t& numIntegrals) const ;
};
#ifdef Complex
void readSOCIntegrals(oneInt& I1soc, int norbs, string fileprefix);
void readGTensorIntegrals(vector<oneInt>& I1soc, int norbs, string fileprefix);
#endif
int readNorbs(string fcidump);
void readIntegralsAndInitializeDeterminantStaticVariables(string fcidump);
void readIntegralsHDF5AndInitializeDeterminantStaticVariables(string fcidump);
#endif
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PermutedTRWalker_HEADER_H
#define PermutedTRWalker_HEADER_H
#include "TRWalker.h"
using namespace Eigen;
/**
Vector of Jastrow-Slater walkers to work with the PermutedWavefunction
*
*/
class PermutedTRWalker
{
public:
vector<TRWalker> walkerVec;
// stored in both the wave function and here
MatrixXd permutations;
// constructors
// default
PermutedTRWalker(){};
// the following constructors are used by the wave function initWalker function
// for deterministic
PermutedTRWalker(Jastrow &corr, const Slater &ref, Determinant &pd, MatrixXd &pPermutations)
{
walkerVec.push_back(TRWalker(corr, ref, pd));
vector<int> occA, occB;
pd.getClosedAlphaBeta(occA, occB);
permutations = pPermutations;
for (int i = 0; i < permutations.rows(); i++) {
Determinant dcopy;
for (int j = 0; j < occA.size(); j++) {
dcopy.setoccA(permutations(i, occA[j]), true);
}
for (int j = 0; j < occB.size(); j++) {
dcopy.setoccB(permutations(i, occB[j]), true);
}
walkerVec.push_back(TRWalker(corr, ref, dcopy));
}
};
PermutedTRWalker(Jastrow &corr, const Slater &ref, MatrixXd &pPermutations)
{
walkerVec.push_back(TRWalker(corr, ref));
vector<int> occA, occB;
walkerVec[0].d.getClosedAlphaBeta(occA, occB);
permutations = pPermutations;
for (int i = 0; i < permutations.rows(); i++) {
Determinant dcopy;
for (int j = 0; j < occA.size(); j++) {
dcopy.setoccA(permutations(i, occA[j]), true);
}
for (int j = 0; j < occB.size(); j++) {
dcopy.setoccB(permutations(i, occB[j]), true);
}
walkerVec.push_back(TRWalker(corr, ref, dcopy));
}
};
// this is used for storing bestDet
Determinant getDet() { return walkerVec[0].getDet(); }
// used during sampling
void updateWalker(const Slater &ref, Jastrow &corr, int ex1, int ex2, bool doparity = true) {
walkerVec[0].updateWalker(ref, corr, ex1, ex2, doparity);
int norbs = Determinant::norbs;
// calculate corresponding excitaitons for the permuted determinants
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
int i = I / 2, a = A / 2;
int j = J / 2, b = B / 2;
int sz1 = I%2, sz2 = J%2;
for (int n = 0; n < permutations.rows(); n++) {
int ex1p = 0, ex2p = 0;
int ip = permutations(n, i);
int ap = permutations(n, a);
ex1p = (2 * ip + sz1) * 2 * norbs + (2 * ap + sz1);
if (ex2 != 0) {
int jp = permutations(n, j);
int bp = permutations(n, b);
ex2p = (2 * jp + sz2) * 2 * norbs + (2 * bp + sz2);
}
walkerVec[n+1].updateWalker(ref, corr, ex1p, ex2p, doparity);
}
}
//to be defined for metropolis
void update(int i, int a, bool sz, const Slater &ref, const Jastrow &corr) { return; };
// used for debugging
friend ostream& operator<<(ostream& os, const PermutedTRWalker& w) {
for (int i = 0; i < w.walkerVec.size(); i++) {
os << "Walker " << i << endl << endl;
os << w.walkerVec[i] << endl;
}
return os;
}
};
#endif
<file_sep>#!/bin/bash
printf "\n\nRunning Tests for NEVPT2\n"
printf "======================================================\n"
MPICOMMAND="mpirun -np 4"
NEVPTPATH="../../../../bin/VMC nevpt.json"
NEVPTPRINTPATH="../../../../bin/VMC nevpt_print.json"
NEVPTREADPATH="../../../../bin/VMC nevpt_read.json"
here=`pwd`
tol=1.0e-7
clean=1
# SC-NEVPT2 tests
cd $here/NEVPT2/n2_vdz/stoch
../../../clean.sh
printf "...running NEVPT2/n2_vdz/stoch\n"
$MPICOMMAND $NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'nevpt' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/n2_vdz/continue_norms
../../../clean_wo_bkp.sh
printf "...running NEVPT2/n2_vdz/continue_norms PRINT\n"
$MPICOMMAND $NEVPTPRINTPATH > nevpt_print.out
python2 ../../../testEnergy.py 'nevpt_print' $tol
if [ $clean == 1 ]
then
../../../clean_wo_bkp.sh
fi
cd $here/NEVPT2/n2_vdz/continue_norms
../../../clean_wo_bkp.sh
printf "...running NEVPT2/n2_vdz/continue_norms READ\n"
$MPICOMMAND $NEVPTREADPATH > nevpt_read.out
python2 ../../../testEnergy.py 'nevpt_read' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/n2_vdz/exact_energies
../../../clean.sh
printf "...running NEVPT2/n2_vdz/exact_energies PRINT\n"
$NEVPTPRINTPATH > nevpt_print.out
python2 ../../../testEnergy.py 'nevpt_print' $tol
if [ $clean == 1 ]
then
../../../clean_wo_bkp.sh
fi
cd $here/NEVPT2/n2_vdz/exact_energies
../../../clean_wo_bkp.sh
printf "...running NEVPT2/n2_vdz/exact_energies READ\n"
$NEVPTREADPATH > nevpt_read.out
python2 ../../../testEnergy.py 'nevpt_read' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/h4_631g/determ
../../../clean.sh
printf "...running NEVPT2/h4_631g/determ\n"
$MPICOMMAND $NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'nevpt' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here/NEVPT2/polyacetylene/stoch
../../../clean.sh
printf "...running NEVPT2/polyacetylene/stoch\n"
$MPICOMMAND $NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'nevpt' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
# SC-NEVPT2 single perturber
cd $here/NEVPT2/n2_vdz/single_perturber
../../../clean.sh
printf "...running NEVPT2/n2_vdz/single_perturber\n"
$NEVPTPATH > nevpt.out
python2 ../../../testEnergy.py 'single_perturber' $tol
if [ $clean == 1 ]
then
../../../clean.sh
fi
cd $here
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NNBS_HEADER_H
#define NNBS_HEADER_H
#include "NNBSWalker.h"
#include <algorithm>
using namespace std;
using namespace std::placeholders;
using namespace Eigen;
// determinant cost function
double costDet(VectorXd& v, const MatrixXd& slice) {
int norbs = Determinant::norbs;
int nelec = Determinant::nalpha + Determinant::nbeta;
MatrixXd bfSlice = Map<MatrixXd>(v.data(), nelec, nelec) + slice;
FullPivLU<MatrixXd> lua(bfSlice);
return lua.determinant();
}
// this returns gradient ratio
void costDetGradient(VectorXd& v, VectorXd& grad, const MatrixXd& slice) {
int norbs = Determinant::norbs;
int nelec = Determinant::nalpha + Determinant::nbeta;
MatrixXd bfSlice = Map<MatrixXd>(v.data(), nelec, nelec) + slice;
FullPivLU<MatrixXd> lua(bfSlice);
MatrixXd deriv = lua.inverse().transpose();
grad = Map<VectorXd>(deriv.data(), nelec*nelec);
}
/**
*/
struct NNBS {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & fnnb
& moCoeffs;
}
public:
fnn fnnb;
MatrixXd moCoeffs;
// default constructor
NNBS() {
int norbs = Determinant::norbs;
int nelec = Determinant::nalpha + Determinant::nbeta;
vector<int> sizes = {2*norbs, schd.numHidden, nelec * nelec};
fnnb = fnn(sizes);
int size = 2*norbs;
moCoeffs = MatrixXd::Zero(size, size);
readMat(moCoeffs, "hf.txt");
};
// no ref and corr for this wave function
MatrixXd& getRef() { return moCoeffs; }
fnn& getCorr() { return fnnb; }
// used at the start of each sampling run
void initWalker(NNBSWalker &walk)
{
walk = NNBSWalker(moCoeffs);
}
// used in deterministic calculations
void initWalker(NNBSWalker &walk, Determinant &d)
{
walk = NNBSWalker(moCoeffs, d);
}
// used in HamAndOvlp below
// used in rdm calculations
double Overlap(const NNBSWalker &walk) const
{
return fnnb.evaluate(walk.occ, std::bind(costDet, std::placeholders::_1, walk.occSlice));
}
// used in rdm calculations
double getOverlapFactor(int i, int a, const NNBSWalker& walk, bool doparity) const
{
return 0.;
}
// used in rdm calculations
double getOverlapFactor(int I, int J, int A, int B, const NNBSWalker& walk, bool doparity) const
{
return 0.;
}
// gradient overlap ratio, used during sampling
void OverlapWithGradient(const NNBSWalker &walk,
double &factor,
Eigen::VectorXd &grad) const
{
fnnb.backPropagate(walk.occ, std::bind(costDetGradient, std::placeholders::_1, std::placeholders::_2, walk.occSlice), grad);
}
void printVariables() const
{
cout << fnnb;
}
// update after vmc optimization
void updateVariables(Eigen::VectorXd &v)
{
fnnb.updateVariables(v);
}
void getVariables(Eigen::VectorXd &v) const
{
fnnb.getVariables(v);
}
long getNumVariables() const
{
return fnnb.getNumVariables();
}
string getfileName() const {
return "NNBS";
}
void writeWave() const
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
//if (commrank == 0)
//{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
//}
#ifndef SERIAL
//boost::mpi::communicator world;
//boost::mpi::broadcast(world, *this, 0);
#endif
}
// calculates local energy and overlap
// used directly during sampling
void HamAndOvlp(const NNBSWalker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true, double epsilon = schd.epsilon) const
{
int norbs = Determinant::norbs;
ovlp = Overlap(walk);
ham = walk.det.Energy(I1, I2, coreE);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.det, epsilon, schd.screen,
work, true);
generateAllScreenedDoubleExcitation(walk.det, epsilon, schd.screen,
work, true);
//loop over all the screened excitations
if (schd.debug) {
cout << "eloc excitations" << endl;
cout << "phi0 d.energy " << ham << endl;
}
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
NNBSWalker excitedWalker = walk;
excitedWalker.updateWalker(moCoeffs, fnnb, ex1, ex2);
double ovlpRatio = Overlap(excitedWalker) / ovlp;
ham += tia * ovlpRatio;
if (schd.debug) cout << ex1 << " " << ex2 << " tia " << tia << " ovlpRatio " << ovlpRatio << endl;
work.ovlpRatio[i] = ovlpRatio;
}
if (schd.debug) cout << endl;
}
void HamAndOvlpLanczos(const NNBSWalker &walk,
Eigen::VectorXd &lanczosCoeffsSample,
double &ovlpSample,
workingArray& work,
workingArray& moreWork, double &alpha)
{
return ;
}
};
#endif
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
#ifndef SRCI_HEADER
#define SRCI_HEADER
#include <sys/time.h> // for gettimeofday()
#include <string.h> // for memset and strcmp
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <cmath>
#include <boost/format.hpp>
#include "CxPodArray.h"
#ifdef _OPENMP
#define omprank omp_get_thread_num()
#define numthrds std::max(atoi(std::getenv("OMP_NUM_THREADS")), 1)
#else
#define omprank 0
#define numthrds 1
#endif
void SplitStackmem(ct::FMemoryStack2 *Mem);
void MergeStackmem(ct::FMemoryStack2 *Mem);
namespace ct {
class FMemoryStack2;
};
namespace srci {
double GetTime();
};
unsigned const
EQINFO_MaxRhs = 11;
enum FTensorUsage {
USAGE_Amplitude,
USAGE_Residual,
USAGE_Hamiltonian,
USAGE_Density,
USAGE_Intermediate,
USAGE_PlaceHolder
};
enum FTensorStorage {
STORAGE_Memory,
STORAGE_Disk
};
struct FTensorDecl
{
char const
*pName,
*pDomain, // name:domain. E.g., 't:eecc' is a T^ij_ab T2 tensor.
// *pSpin, // spin class of the slots: A (alpha), B (beta), _ (spatial)
*pSymmetry; // ITF-style permutation symmetry declaration.
FTensorUsage
Usage;
FTensorStorage
Storage;
};
struct FDomainDecl
{
char const *pName;
char const *pRelatedTo;
int (*f)(int) ; //this is a function pointer that takes the size of the
//pRelatedTo Domain and returns the size of the current Domain
};
struct FEqInfo
{
char const
*pCoDecl; // <- note that these are only used to determine the
// permutations. The names of the indices do not matter.
FScalar
Factor;
unsigned
nTerms;
int
// first one is lhs, the others are rhs.
iTerms[1+EQINFO_MaxRhs];
};
// FEqInfo a = { "ikac,kjcb->ijab", 1.000, 3, {4,2,4} };
struct FEqSet
{
FEqInfo const
*pEqs;
size_t
nEqs;
char const
*pDesc;
FEqSet() {};
FEqSet(FEqInfo const *pEqs_, size_t nEqs_, char const *pDesc_)
: pEqs(pEqs_), nEqs(nEqs_), pDesc(pDesc_)
{}
};
struct FMethodInfo
{
char const
*pName, *pSpinClass;
char const
*perturberClass;
FDomainDecl const *pDomainDecls; //if we need other domains besides e,a,c
uint nDomainDecls;
FTensorDecl const
*pTensorDecls;
uint
nTensorDecls;
FEqSet
EqsRes, Overlap, MakeS1, MakeS2, EqsHandCode, EqsHandCode2;
};
enum FOrbType
{
ORBTYPE_Spatial,
ORBTYPE_SpinOrb
};
struct FWfDecl
{
uint
nElec;
uint
nActElec;
uint
nActOrb;
int
Ms2;
FOrbType
OrbType;
uint nElecA() const { return (nElec + Ms2)/2; }
uint nElecB() const { return (nElec - Ms2)/2; }
};
enum FMethodClass {
METHOD_MinE, // minimization of energy.
METHOD_ProjSgl // projected schroedinger equation
};
struct FJobData
{
std::string
MethodName;
FWfDecl
WfDecl;
FScalar
RefEnergy;
ct::FArrayNpy
Int1e_Fock,
Int1e_CoreH,
Int2e_4ix,
Int1e_Fock_A,
Int1e_Fock_B,
Int2e_3ix, // Frs fitting integrals.
Int2e_3ix_A,
Int2e_3ix_B,
Int2e_4ix_AA,
Int2e_4ix_BB,
Int2e_4ix_AB,
Int2e_4ix_BA;
bool
MakeFockAfterIntegralTrafo;
ct::FArrayNpy
// orbital matrix supplied in input: integrals are transformed to/from
// this. (may need different ones for A/B)
Orbs,
// overlap matrix supplied in input. Used to transform stuff back to input
// basis (e.g., RDMs). May be empty; if empty, basis is assumed
// orthogonal.
Overlap;
FScalar
ThrTrun,
ThrDen,
ThrVar,
LevelShift,
Shift;
uint
nOrb,
MaxIt,
nMaxDiis;
size_t WorkSpaceMb;
FMethodClass
MethodClass;
std::string orbitalFile;
std::string resultOut;
std::string guessInput;
void ReadInputFile(char const *pArgFile);
FJobData() ;
};
template <class FMap>
typename FMap::mapped_type const &value(FMap const &Map, typename FMap::key_type const &Key)
{
typename FMap::const_iterator it = Map.find(Key);
if (it == Map.end())
throw std::runtime_error("map value which was expected to exist actually didn't.");
return it->second;
}
template <class FMap>
bool exists(typename FMap::key_type const &Key, FMap const &Map)
{
typename FMap::const_iterator it = Map.find(Key);
return it != Map.end();
}
typedef FNdArrayView
FSrciTensor;
struct FAmpResPair {
FSrciTensor
*pRes, *pAmp;
char const
*pDomain;
TArrayFix<FScalar const*,nMaxRank>
// diagonal denominators for the domains. One for each slot.
pEps;
};
// index domain. That is effectively a special case of the slot properties
// in ITF
typedef char
FDomainName;
struct FDomainInfo
{
uint
// base offset and size in the full orbital space
iBase, nSize;
ct::TArray<FScalar>
// orbital energies (for denominators)
Eps;
};
typedef std::map<FDomainName, FDomainInfo>
FDomainInfoMap;
static FScalar pow2(FScalar x) {
return x*x;
}
struct FJobContext : FJobData
{
// TArray<double>
// // this is where the tensor data for the amplitude/residual/other
// // tensors go.
// AmpData, ResData, OtherData;
FMethodInfo
Method;
void ReadMethodFile();
void Run(ct::FMemoryStack2 *Mem);
// print time elapsed since since t0 = GetTime() was set.
void PrintTimingT0(char const *p, FScalar t0);
// print time "t"
void PrintTiming(char const *p, FScalar t);
void PrintResult(std::string const &s, FScalar f, int iState, char const *pAnnotation=0);
// look up a tensor by name and domain, and return a pointer to it.
FSrciTensor *TND(std::string const &NameAndDomain);
// look up a tensor by name and return a pointer to it.
FSrciTensor *TN(std::string const &Name);
FSrciTensor *TensorById(int iTensorRef);
void DeleteData(ct::FMemoryStack2 &Mem);
void readorbitalsfile(std::string& orbitalfile);
private:
void Init(ct::FMemoryStack2 &Mem);
void CreateTensors(ct::FMemoryStack2 &Mem);
void InitDomains();
void InitAmpResPairs();
void ExecHandCoded(ct::FMemoryStack2 *Mem);
void MakeOrthogonal(std::string s, std::string s2);
void BackToNonOrthogonal(std::string s, std::string s2);
void MakeOverlapAndOrthogonalBasis(ct::FMemoryStack2 *Mem);
void InitAmplitudes(ct::FMemoryStack2 &Mem);
void ClearTensors(size_t UsageFlags);
void UpdateAmplitudes(FScalar LevelShift, ct::FMemoryStack2 *Mem);
void ExecEquationSet(FEqSet const &Eqs, std::vector<FSrciTensor>& m_Tensors, ct::FMemoryStack2 &Mem);
void CleanAmplitudes(std::string const &r_or_t);
void FillData (int i, ct::FMemoryStack2 &Mem);
void SaveToDisk(std::string file, std::string op);
void DeAllocate(std::string op, ct::FMemoryStack2 &Mem);
void Allocate(std::string op, ct::FMemoryStack2 &Mem);
size_t m_TensorDataSize;
double*
// data of resident tensors is stored in here.
m_TensorData;
FDomainInfoMap
m_Domains;
std::vector<FSrciTensor>
m_Tensors;
typedef std::map<std::string, FSrciTensor* >
FTensorByNameMap;
FTensorByNameMap
m_TensorsByNameAndDomain,
m_TensorsByName;
};
#endif
<file_sep>#include <stdio.h>
#include <pvfmm.hpp>
#include <ctime>
#include "mkl.h"
#include <finufft.h>
#include <Eigen/Dense>
#include "fmmInterface.h"
#include "pythonInterface.h"
using namespace Eigen;
//#FMM TREE
pvfmm::ChebFMM_Tree<double>* tree;
vector<double> LegCoord, LegWts;
vector<double> AoValsAtLegCoord;
vector<complex<double>> AoValsAtLegCoordComplex;
vector<double> ChebCoord;
vector<double> AoValsAtChebCoord;
vector<complex<double>> AoValsAtChebCoordComplex;
vector<double> density;
template<typename T>
void writeNorm(T* mat, size_t size) {
T norm = 0.0;
for (int i=0; i<size; i++)
norm += mat[i];
cout << norm<<endl;
}
void populateChebyshevCoordinates(int leafNodes, int cheb_deg) {
size_t nCheb = (cheb_deg+1)*(cheb_deg+1)*(cheb_deg+1);
size_t index = 0;
double volume = 0.0;
auto nodes = tree->GetNodeList();
//chebyshev coord
ChebCoord.resize(leafNodes*nCheb*3, 0.0);
std::vector<double> Chebcoord=pvfmm::cheb_nodes<double>(cheb_deg,nodes[0]->Dim());
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf()) {
double s=pvfmm::pow<double>(0.5,nodes[i]->Depth());
for (int j=0; j<nCheb; j++) {
ChebCoord[index*3+0] = Chebcoord[j*3+0]*s+nodes[i]->Coord()[0];
ChebCoord[index*3+1] = Chebcoord[j*3+1]*s+nodes[i]->Coord()[1];
ChebCoord[index*3+2] = Chebcoord[j*3+2]*s+nodes[i]->Coord()[2];
index++;
}
}
}
void populateLegendreCoordinates(int leafNodes) {
auto nodes = tree->GetNodeList();
const int legdeg = 11;
size_t nLeg = legdeg * legdeg * legdeg;
size_t numCoords = leafNodes * nLeg;
size_t index = 0;
double volume = 0.0;
vector<double> Legcoord, Legwts;
getLegCoords<legdeg>(nodes[0]->Dim(), Legcoord, Legwts);
LegCoord.resize(numCoords*3, 0.0); LegWts.resize(numCoords, 0.0);
vector<double> nodeTrgCoords(nLeg*3, 0.0);
//legendre coord for each leaf node and make them also the target coords
//so that the potential is calculated at those points
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf()) {
double s=pvfmm::pow<double>(0.5,nodes[i]->Depth());
double wt = s*s*s/8;
volume += wt;
for (int j=0; j<nLeg; j++) {
LegCoord[index*3+0] = Legcoord[j*3+0]*s+nodes[i]->Coord()[0];
LegCoord[index*3+1] = Legcoord[j*3+1]*s+nodes[i]->Coord()[1];
LegCoord[index*3+2] = Legcoord[j*3+2]*s+nodes[i]->Coord()[2];
LegWts[index] = Legwts[j] * wt;//j == 0 ? wt: 0.0;//wt;//s*s*s * scal;
nodeTrgCoords[j*3+0] = LegCoord[index*3+0];
nodeTrgCoords[j*3+1] = LegCoord[index*3+1];
nodeTrgCoords[j*3+2] = LegCoord[index*3+2];
nodes[i]->trg_coord = nodeTrgCoords;
index++;
}
}
}
int printTreeStats() {
auto nodes = tree->GetNodeList();
int leafNodes;
MPI_Comm comm = MPI_COMM_WORLD;
{
int myrank;
MPI_Comm_rank(comm, &myrank);
std::vector<size_t> all_nodes(PVFMM_MAX_DEPTH+1,0);
std::vector<size_t> leaf_nodes(PVFMM_MAX_DEPTH+1,0);
for (int i=0; i<nodes.size(); i++) {
auto n=nodes[i];
if(!n->IsGhost()) all_nodes[n->Depth()]++;
if(!n->IsGhost() && n->IsLeaf()) leaf_nodes[n->Depth()]++;
if (nodes[i]->IsLeaf())
leafNodes++;
}
if(!myrank) std::cout<<"All Nodes: ";
for(int i=0;i<PVFMM_MAX_DEPTH;i++){
int local_size=all_nodes[i];
int global_size;
MPI_Allreduce(&local_size, &global_size, 1, MPI_INT, MPI_SUM, comm);
if(!myrank) std::cout<<global_size<<' ';
}
if(!myrank) std::cout<<'\n';
if(!myrank) std::cout<<"Leaf Nodes: ";
for(int i=0;i<PVFMM_MAX_DEPTH;i++){
int local_size=leaf_nodes[i];
int global_size;
MPI_Allreduce(&local_size, &global_size, 1, MPI_INT, MPI_SUM, comm);
if(!myrank) std::cout<<global_size<<' ';
}
if(!myrank) std::cout<<'\n';
}
return leafNodes;
}
void initFMMGridAndTree(double* pdm, double* pcentroid, double pscale, double tol,
double eta, int Periodic) {
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
cout.precision(12);
if (!Periodic)
dm = pdm;
else {
dmComplex.resize(nkpts * nao * nao);
for (int i=0; i<dmComplex.size(); i++)
dmComplex[i] = pdm[i];
}
centroid = pcentroid;
coordScale = pscale;
//auto getDensity = getValuesAtGrid;
auto getDensity = Periodic == 0 ? getValuesAtGrid : getValuesAtGridPeriodic;
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
MPI_Comm comm = MPI_COMM_WORLD;
int cheb_deg = 10, max_pts = 10000, mult_order = 10;
const pvfmm::Kernel<double>& kernel_fn = (abs(eta)<1.e-10) ?
pvfmm::LaplaceKernel<double>::potential() :
pvfmm::ShortRangeCoulomb<double,1>::potential();
int nt = omp_get_max_threads();
omp_set_num_threads(1);
vector<double> dummy(3,0.0);
tree=ChebFMM_CreateTree(cheb_deg, kernel_fn.ker_dim[0],
getDensity,
//dummy, comm, tol, max_pts, pvfmm::FreeSpace);
dummy, comm, tol, max_pts, pvfmm::Periodic);
current_time = time(NULL);
cout << "time to make tree "<<current_time - Initcurrent_time<<endl;
int leafNodes = printTreeStats();
omp_set_num_threads(nt);
populateLegendreCoordinates(leafNodes);
populateChebyshevCoordinates(leafNodes, cheb_deg);
//calculate the ao values at the legendre coordinates
if (Periodic) {
AoValsAtLegCoordComplex.resize(LegCoord.size() * nao/3 * nkpts, 0.0);
getAoValuesAtGridPeriodic(&LegCoord[0], LegCoord.size()/3, &AoValsAtLegCoordComplex[0]);
current_time = time(NULL);
cout << "legendre coordinates "<<current_time - Initcurrent_time<<" "<<LegCoord.size()/3<<endl;
AoValsAtChebCoordComplex.resize(ChebCoord.size() * nao/3 * nkpts, 0.0);
getAoValuesAtGridPeriodic(&ChebCoord[0], ChebCoord.size()/3, &AoValsAtChebCoordComplex[0]);
current_time = time(NULL);
cout << "chebyshev coordinates "<<current_time - Initcurrent_time<<" "<<ChebCoord.size()/3<<endl;
}
else {
AoValsAtLegCoord.resize(LegCoord.size() * nao/3, 0.0);
getAoValuesAtGrid(&LegCoord[0], LegCoord.size()/3, &AoValsAtLegCoord[0]);
AoValsAtChebCoord.resize(ChebCoord.size() * nao/3, 0.0);
getAoValuesAtGrid(&ChebCoord[0], ChebCoord.size()/3, &AoValsAtChebCoord[0]);
}
cout << "calculated density"<<endl;
}
void getFockFMMPeriodic(double* pdm, complex<double>* fock, double tol) {
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
for (int i=0; i<dmComplex.size(); i++)
dmComplex[i] = pdm[i];
getDensity(density, AoValsAtLegCoordComplex);
vector<double> potential(density.size(), 0.0);
getElectronicFFTPeriodic(&LegCoord[0], &LegWts[0], LegWts.size(), &density[0], &potential[0],
RLattice, 0.0, 80, 80, 80, tol);
getFock(potential, AoValsAtLegCoordComplex, fock);
getElectronicFFTPeriodicUniform(RLattice, potential, 0.0, 100, 100, 100);
return;
int rank;MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm comm = MPI_COMM_WORLD;
//const pvfmm::Kernel<double>& kernel_fn = pvfmm::ShortRangeCoulomb<double,1>::potential();
const pvfmm::Kernel<double>& kernel_fn = pvfmm::LaplaceKernel<double>::potential();
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
//construct the density from density matrix and ao values stored on chebyshev grid
int cheb_deg = 10, mult_order = 10;
{
int ngrid = ChebCoord.size()/3;
if (intermediateComplex.size() < nao*ngrid) {
intermediateComplex.resize(nao*ngrid, 0.0);
}
complex<double> alpha = 1.0, beta = 0.0;
cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
ngrid, nao, nao, &alpha, &AoValsAtChebCoordComplex[0], ngrid, &dmComplex[0], nao,&beta,
&intermediateComplex[0], ngrid);
if (density.size() < ngrid) density.resize(ngrid, 0.0);
std::fill(&density[0], &density[0]+ngrid, 0.0);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
density[g] += (intermediateComplex[p*ngrid + g] * std::conj(AoValsAtChebCoordComplex[p*ngrid + g])).real();
}
//use the density on the chebyshev grid points to fit the
//chebyshev polynomials of the leaf nodes
int index = 0, nCheb = (cheb_deg+1)*(cheb_deg+1)*(cheb_deg+1);;
auto nodes = tree->GetNodeList();
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf()) {
nodes[i]->ChebData().SetZero();
pvfmm::cheb_approx<double,double>(&density[nCheb*index], cheb_deg, nodes[i]->DataDOF(), &(nodes[i]->ChebData()[0]));
index++;
}
pvfmm::ChebFMM<double> matrices;
matrices.Initialize(mult_order, cheb_deg, comm, &kernel_fn);
tree->SetupFMM(&matrices);
std::vector<double> trg_value;
size_t n_trg=LegCoord.size()/PVFMM_COORD_DIM;
pvfmm::ChebFMM_Evaluate(tree, trg_value, n_trg);
//construct the fock matrix using potential and AOvals on the legendre grid
{
int ngrid = LegCoord.size()/3;
if (intermediateComplex.size() < nao*ngrid)
intermediateComplex.resize(nao*ngrid, 0.0);
vector<complex<double>>& aovals = AoValsAtLegCoordComplex;
cout << "before intermediate"<<endl;
cout << aovals.size()<<" "<<trg_value.size()<<" "<<LegWts.size()<<" "<<nao<<" "<<ngrid<<endl;
double scale = pow(coordScale, 5);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
intermediateComplex[p*ngrid + g] = aovals[p*ngrid + g] * trg_value[g] * LegWts[g] * scale * 4 * M_PI;
cout << "before zgemm"<<endl;
complex<double> alpha = 1.0, beta = 0.0;
cblas_zgemm(CblasColMajor, CblasTrans, CblasNoTrans,
nao, nao, ngrid, &alpha, &intermediateComplex[0], ngrid, &aovals[0], ngrid, &beta,
&fock[0], nao);
cout << "after zgemm"<<endl;
}
return;
}
void getFockFMM(double* pdm, double* fock, double tol) {
int rank;MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm comm = MPI_COMM_WORLD;
const pvfmm::Kernel<double>& kernel_fn=pvfmm::LaplaceKernel<double>::potential();
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
//construct the density from density matrix and ao values stored on chebyshev grid
int cheb_deg = 10, mult_order = 10;
int nao = ao_loc[shls[1]] - ao_loc[shls[0]];
{
int ngrid = ChebCoord.size()/3;
if (intermediate.size() < nao*ngrid) {
intermediate.resize(nao*ngrid, 0.0);
}
double alpha = 1.0, beta = 0.0;
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
ngrid, nao, nao, alpha, &AoValsAtChebCoord[0], ngrid, &pdm[0], nao, beta,
&intermediate[0], ngrid);
if (density.size() < ngrid) density.resize(ngrid, 0.0);
std::fill(&density[0], &density[0]+ngrid, 0.0);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
density[g] += intermediate[p*ngrid + g] * AoValsAtChebCoord[p*ngrid + g];
}
//use the density on the chebyshev grid points to fit the
//chebyshev polynomials of the leaf nodes
int index = 0, nCheb = (cheb_deg+1)*(cheb_deg+1)*(cheb_deg+1);;
auto nodes = tree->GetNodeList();
for (int i=0; i<nodes.size(); i++)
if (nodes[i]->IsLeaf()) {
nodes[i]->ChebData().SetZero();
pvfmm::cheb_approx<double,double>(&density[nCheb*index], cheb_deg, nodes[i]->DataDOF(), &(nodes[i]->ChebData()[0]));
index++;
}
pvfmm::ChebFMM<double> matrices;
matrices.Initialize(mult_order, cheb_deg, comm, &kernel_fn);
tree->SetupFMM(&matrices);
std::vector<double> trg_value;
size_t n_trg=LegCoord.size()/PVFMM_COORD_DIM;
pvfmm::ChebFMM_Evaluate(tree, trg_value, n_trg);
//construct the fock matrix using potential and AOvals on the legendre grid
{
int ngrid = LegCoord.size()/3;
if (intermediate.size() < nao*ngrid)
intermediate.resize(nao*ngrid, 0.0);
vector<double>& aovals = AoValsAtLegCoord;
double scale = pow(coordScale, 5);
for (int p = 0; p<nao; p++)
for (int g = 0; g<ngrid; g++)
intermediate[p*ngrid + g] = aovals[p*ngrid + g] * trg_value[g] * LegWts[g] * scale * 4 * M_PI;
double alpha = 1.0, beta = 0.0;
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,
nao, nao, ngrid, alpha, &intermediate[0], ngrid, &aovals[0], ngrid, beta,
&fock[0], nao);
}
return;
}
void getPotentialFMM(int nTarget, double* coordsTarget, double* potential, double* pdm,
double* pcentroid, double pscale, double tol) {
cout.precision(12);
ncalls = 0;
dm = pdm;
centroid = pcentroid;
coordScale = pscale;
int rank;MPI_Comm_rank(MPI_COMM_WORLD, &rank);
time_t Initcurrent_time, current_time;
Initcurrent_time = time(NULL);
MPI_Comm comm = MPI_COMM_WORLD;
int cheb_deg = 10, max_pts = 10000, mult_order = 10;
vector<double> trg_coord(3*nTarget), input_coord(3*nTarget);
for (int i=0; i<nTarget; i++) {
trg_coord[3*i+0] = (coordsTarget[3*i+0] - centroid[0])/coordScale + 0.5;
trg_coord[3*i+1] = (coordsTarget[3*i+1] - centroid[1])/coordScale + 0.5;
trg_coord[3*i+2] = (coordsTarget[3*i+2] - centroid[2])/coordScale + 0.5;
}
const pvfmm::Kernel<double>& kernel_fn=pvfmm::LaplaceKernel<double>::potential();
auto* tree=ChebFMM_CreateTree(cheb_deg, kernel_fn.ker_dim[0],
getValuesAtGrid,
trg_coord, comm, tol, max_pts, pvfmm::FreeSpace);
current_time = time(NULL);
//if (rank == 0) cout << "make tree "<<(current_time - Initcurrent_time)<<endl;
// Load matrices.
pvfmm::ChebFMM<double> matrices;
matrices.Initialize(mult_order, cheb_deg, comm, &kernel_fn);
// FMM Setup
tree->SetupFMM(&matrices);
current_time = time(NULL);
//if (rank == 0) cout << "fmm setup "<<(current_time - Initcurrent_time)<<endl;
// Run FMM
std::vector<double> trg_value;
size_t n_trg=trg_coord.size()/PVFMM_COORD_DIM;
pvfmm::ChebFMM_Evaluate(tree, trg_value, n_trg);
current_time = time(NULL);
//if (rank == 0) cout << "evalstep setup "<<(current_time - Initcurrent_time)<<endl;
for (int i=0; i<nTarget; i++)
potential[i] = trg_value[i]*4*M_PI;
delete tree;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BFSlater_HEADER_H
#define BFSlater_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <Eigen/Dense>
#include "Determinants.h"
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
class workingArray;
enum HartreeFock {Restricted, UnRestricted, Generalized};
/**
* This is the wavefunction, it is a linear combination of
* slater determinants made of Hforbs
*/
class BFSlater {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & hftype
& det
& HforbsA
& HforbsB
& bf;
}
public:
HartreeFock hftype; //r/u/ghf
Determinant det;
Eigen::MatrixXcd HforbsA, HforbsB; //mo coeffs, HforbsA=HforbsB for r/ghf
Eigen::MatrixXd bf; //backflow varibales \eta_ij, where i and j are spatial orbitals, assumed to be the same for up and down spins
//read mo coeffs fomr hf.txt
void initDet();
void initHforbs();
void initBf();
BFSlater();
//variables are ordered as:
//cicoeffs of the reference multidet expansion, followed by hforbs (row major): real and complex parts alternating
//in case of uhf all alpha first followed by beta
void getVariables(Eigen::VectorBlock<Eigen::VectorXd> &v) const;
long getNumVariables() const;
void updateVariables(const Eigen::VectorBlock<Eigen::VectorXd> &v);
void printVariables() const;
const Determinant &getDeterminant() const { return det; }
//int getNumOfDets() const;
//const std::vector<double> &getciExpansion() const { return ciExpansion; }
const Eigen::MatrixXcd& getHforbsA() const { return HforbsA;}
const Eigen::MatrixXcd& getHforbsB() const {return HforbsB;}
const Eigen::MatrixXcd& getHforbs(bool sz = 0) const { if(sz == 0) return HforbsA; else return HforbsB;}
const Eigen::MatrixXd& getBf() const {return bf;}
string getfileName() const {return "BFSlater";};
};
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef excitFCIQMC_HEADER_H
#define excitFCIQMC_HEADER_H
// Map two integers to a single integer by a one-to-one mapping,
// using the triangular indexing approach
inline int triInd(const int p, const int q)
{
int Q = min(p,q);
int P = max(p,q);
return P*(P-1)/2 + Q;
}
// This class holds the arrays needed to use heat bath excitation generators.
// This was described in J. Chem. Theory Comput., 2016, 12 (4), 1561.
// Arrays are labelled by the same names as in the above paper.
class heatBathFCIQMC {
public:
// Used to construct probabilities for selecting the first electron, p.
vector<double> S_p;
// Used to construct probabilities for selecting the second electron, q,
// given that p has already been chosen.
vector<double> D_pq;
// The probabilities for selecting the first unoccupied orbital, r,
// given that p and q have been chosen already.
// Depending on whether p and q have the same or opposite spin, use the
// 'same' or 'opp' objects.
// Note that r is chosen such that it has the same spin as p.
vector<double> P_same_r_pq;
vector<double> P_opp_r_pq;
// Cumulative arrays
vector<double> P_same_r_pq_cum;
vector<double> P_opp_r_pq_cum;
// The probabilities for selecting the second unoccupied orbital, s,
// given that p, q and r have been chosen already.
// Depending on whether p and q have the same or opposite spin, use the
// 'same' or 'opp' objects.
vector<double> P_same_s_pqr;
vector<double> P_opp_s_pqr;
// Cumulative arrays
vector<double> P_same_s_pqr_cum;
vector<double> P_opp_s_pqr_cum;
// These objects are used to decide whether to generate a single or double
// excitation, after first choosing p, q and r.
vector<double> H_tot_same;
vector<double> H_tot_opp;
// Constructors
heatBathFCIQMC() {}
heatBathFCIQMC(int norbs, const twoInt& I2);
void createArrays(int norbs, const twoInt& I2);
};
void generateExcitation(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2,
const Determinant& parentDet, const int nel, Determinant& childDet,
Determinant& childDet2, double& pGen, double& pGen2, int& ex1, int& ex2);
void generateExcitationSingDoub(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2,
const Determinant& parentDet, const int nel, Determinant& childDet,
Determinant& childDet2, double& pgen, double& pgen2,
int& ex1, int& ex2);
void generateSingleExcit(const Determinant& parentDet, Determinant& childDet, double& pgen_ia, int& ex1);
void generateDoubleExcit(const Determinant& parentDet, Determinant& childDet, double& pgen_ijab,
int& ex1, int& ex2);
void pickROrbitalHB(const heatBathFCIQMC& hb, const int norbs, const int p, const int q, int& r,
double& rProb, double& H_tot_pqr);
void pickSOrbitalHB(const heatBathFCIQMC& hb, const int norbs, const int p, const int q, const int r,
int& s, double& sProb);
double calcSinglesProb(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2, const int norbs,
const vector<int>& closed, const double pProb, const double D_pq_tot,
const double hSingAbs, const int p, const int r);
double calcProbDouble(const Determinant& parentDet, const oneInt& I1, const twoInt& I2,
const double H_tot_pqr, const int p, const int r);
void calcProbsForRAndS(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2, const int norbs,
const Determinant& parentDet, const int p, const int q, const int r, const int s,
double& rProb, double& sProb, double& doubleProb, const bool calcDoubleProb);
void generateExcitHB(const heatBathFCIQMC& hb, const oneInt& I1, const twoInt& I2, const Determinant& parentDet,
const int nel, Determinant& childDet, Determinant& childDet2, double& pGen, double& pGen2,
int& ex1, int& ex2, const bool attemptSingleExcit);
#endif
<file_sep>#include "global.h"
#include "walkersFCIQMC.h"
void stochastic_round(const double minPop, double& amp, bool& roundedUp) {
auto random = bind(uniform_real_distribution<double>(0, 1), ref(generator));
double pAccept = abs(amp)/minPop;
if (random() < pAccept) {
amp = copysign(minPop, amp);
roundedUp = true;
} else {
amp = 0.0;
roundedUp = false;
}
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Lanczos_HEADER_H
#define Lanczos_HEADER_H
#include <vector>
#include <set>
#include "Determinants.h"
#include "workingArray.h"
#include "excitationOperators.h"
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/array.hpp>
#include <utility>
using namespace std;
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
template<typename Wfn>
class Lanczos
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & wave
& alpha;
}
public:
double alpha;
Wfn wave;
workingArray morework;
Lanczos()
{
wave.readWave();
alpha = 0.;
}
Lanczos(Wfn &w1, double alpha0) : alpha(alpha0)
{
wave = w1;
}
typename Wfn::ReferenceType& getRef() { return wave.getRef(); }
typename Wfn::CorrType& getCorr() { return wave.getCorr(); }
template<typename Walker>
void initWalker(Walker& walk) {
this->wave.initWalker(walk);
}
template<typename Walker>
double optimizeWave(Walker& walk, double alphaInit = 0.1) {
Eigen::VectorXd stddev = Eigen::VectorXd::Zero(4);
Eigen::VectorXd rk = Eigen::VectorXd::Zero(4);
//double rk = 0;
Eigen::VectorXd lanczosCoeffs = Eigen::VectorXd::Zero(4);
alpha = alphaInit;
auto initTime = getTime();
if (schd.deterministic) getLanczosCoeffsDeterministic(wave, walk, alpha, lanczosCoeffs);
else getLanczosCoeffsContinuousTime(wave, walk, alpha, lanczosCoeffs, stddev, rk, schd.stochasticIter, 1.e-5);
double a = lanczosCoeffs[2]/lanczosCoeffs[3];
double b = lanczosCoeffs[1]/lanczosCoeffs[3];
double c = lanczosCoeffs[0]/lanczosCoeffs[3];
double delta = pow(a, 2) + 4 * pow(b, 3) - 6 * a * b * c - 3 * pow(b * c, 2) + 4 * a * pow(c, 3);
double numP = a - b * c + pow(delta, 0.5);
double numM = a - b * c - pow(delta, 0.5);
double denom = 2 * pow(b, 2) - 2 * a * c;
double alphaP = numP/denom;
double alphaM = numM/denom;
double eP = (a * pow(alphaP, 2) + 2 * b * alphaP + c) / (b * pow(alphaP, 2) + 2 * c * alphaP + 1);
double eM = (a * pow(alphaM, 2) + 2 * b * alphaM + c) / (b * pow(alphaM, 2) + 2 * c * alphaM + 1);
if (commrank == 0) {
cout << "wall time: " << getTime() - initTime << endl;
cout << "coeffs\n" << lanczosCoeffs << endl;
cout << "stddev\n" << stddev << endl;
//cout << "a " << a << " b " << b << " b " << " c " << c << endl;
cout << "alpha(+/-) " << alphaP << " " << alphaM << endl;
cout << "energy(+/-) " << eP << " " << eM << endl;
}
if (eP < eM) alpha = alphaP;
else alpha = alphaM;
return alpha;
}
template<typename Walker>
void initWalker(Walker& walk, Determinant& d) {
this->wave.initWalker(walk, d);
}
void getVariables(VectorXd& vars) {
if (vars.rows() != getNumVariables())
{
vars = VectorXd::Zero(getNumVariables());
}
vars[0] = alpha;
}
void printVariables() {
cout << "alpha " << alpha << endl;
}
void updateVariables(VectorXd& vars) {
alpha = vars[0];
}
long getNumVariables() {
return 1;
}
template<typename Walker>
double Overlap(Walker& walk) {
int norbs = Determinant::norbs;
double totalovlp = 0.0;
double ovlp = wave.Overlap(walk);
double ham = walk.d.Energy(I1, I2, coreE);
morework.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
morework, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
morework, false);
//loop over all the screened excitations
for (int i=0; i<morework.nExcitations; i++) {
int ex1 = morework.excitation1[i], ex2 = morework.excitation2[i];
double tia = morework.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double ovlpRatio = wave.getOverlapFactor(I, J, A, B, walk, false);
ham += tia * ovlpRatio;
morework.ovlpRatio[i] = ovlpRatio;
}
totalovlp = ovlp*(1 + alpha * ham);
return totalovlp;
}
template<typename Walker>
void HamAndOvlp(const Walker &walk,
double &ovlp, double& ham,
workingArray& work, bool fillExcitations = true)
{
int norbs = Determinant::norbs;
ham = walk.d.Energy(I1, I2, coreE);
//ovlp = Overlap(walk);
morework.setCounterToZero();
double ovlp0, ham0;
wave.HamAndOvlp(walk, ovlp0, ham0, morework);
ovlp = ovlp0*(1 + alpha*ham0);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
auto walkCopy = walk;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(),
work.excitation1[i], work.excitation2[i], false);
//double ovlp0 = Overlap(walkCopy);
morework.setCounterToZero();
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework);
ovlp0 = ovlp0*(1 + alpha*ham0);
ham += tia * ovlp0/ovlp;
work.ovlpRatio[i] = ovlp0/ovlp;
}
}
string getfileName() const {
return "lanczos"+wave.getfileName();
}
void writeWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
#endif
}
};
#endif
<file_sep>import numpy as np
from pyscf import gto, scf, ao2mo, tools, fci
from pyscf.lo import pipek
from scipy.linalg import fractional_matrix_power
#n = nelec
n = 50
norb = 50
sqrt2 = 2**0.5
matr = np.full((2*norb, 2*norb), 0.)
mati = np.full((2*norb, 2*norb), 0.)
row = 0
fileh = open("ghf.txt", 'r')
for line in fileh:
col = 0
for coeff in line.split():
m = coeff.strip()[1:-1]
matr[row, col], mati[row, col] = [float(x) for x in m.split(',')]
col = col + 1
row = row + 1
fileh.close()
ghf = matr + 1j * mati
theta = ghf[::,:n]
amat = np.full((n, n), 0.)
for i in range(n/2):
amat[2 * i + 1, 2 * i] = -1.
amat[2 * i, 2 * i + 1] = 1.
pairMat = theta.dot(amat).dot(theta.T)
pairMatr = pairMat.real
pairMati = pairMat.imag
#randMat = np.random.rand(2*norb,2*norb)
#randMat = (randMat - randMat.T)/10
filePfaff = open("pairMat.txt", 'w')
for i in range(2*norb):
for j in range(2*norb):
filePfaff.write('%16.10e '%(pairMatr[i,j]))
filePfaff.write('\n')
filePfaff.close()
filePfaff = open("pairMati.txt", 'w')
for i in range(2*norb):
for j in range(2*norb):
filePfaff.write('%16.10e '%(pairMati[i,j]))
filePfaff.write('\n')
filePfaff.close()
<file_sep>#include "CalculateSphHarmonics.h"
#include <Eigen/Dense>
#include <boost/math/special_functions/spherical_harmonic.hpp>
#include "pythonInterface.h"
#include <boost/math/interpolators/cubic_b_spline.hpp>
#include <ctime>
#include <stdio.h>
#include "mpi.h"
#include "fittedFunctions.h"
//#### BECKE GRID VARIABLES ######
vector<RawDataOnGrid> densityYlm;
vector<RawDataOnGrid> potentialYlm;
vector<SplineFit> splinePotential;
MatrixXdR RawDataOnGrid::lebdevgrid;
MatrixXd RawDataOnGrid::SphericalCoords;
MatrixXd RawDataOnGrid::sphVals;
MatrixXd RawDataOnGrid::WeightedSphVals;
VectorXd RawDataOnGrid::densityStore;
int RawDataOnGrid::lmax;
vector<int> RawDataOnGrid::lebdevGridSize{ 1, 6, 14, 26, 38, 50, 74, 86, 110, 146, 170,
194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030,
2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810 };
void initAtomGrids() {
int natom = natm;
densityYlm.resize(natom);
potentialYlm.resize(natom);
splinePotential.resize(natom);
for (int i=0; i<natom; i++) {
densityYlm[i].coord(0) = env[atm[6*i+1] + 0];
densityYlm[i].coord(1) = env[atm[6*i+1] + 1];
densityYlm[i].coord(2) = env[atm[6*i+1] + 2];
potentialYlm[i].coord = densityYlm[i].coord;
splinePotential[i].coord = densityYlm[i].coord;
}
}
void initAngularData(int lmax, int lebdevOrder){
RawDataOnGrid::InitStaticVariables(lmax, lebdevOrder);
}
void initDensityRadialGrid(int ia, int rmax, double rm) {
densityYlm[ia].InitRadialGrids(rmax, rm);
}
void fitDensity(int ia, int rindex) {
int GridSize = RawDataOnGrid::lebdevgrid.rows();
MatrixXdR grid(GridSize, 3);
grid = RawDataOnGrid::lebdevgrid.block(0,0,GridSize, 3) * densityYlm[ia].radialGrid(rindex);
for (int i=0; i<grid.rows(); i++) {
grid(i,0) += densityYlm[ia].coord(0);
grid(i,1) += densityYlm[ia].coord(1);
grid(i,2) += densityYlm[ia].coord(2);
}
vector<double> density(GridSize, 0.0), becke(natm*GridSize, 0.0), beckenorm(GridSize,0.0);
getValuesAtGrid(&grid(0,0), GridSize, &density[0]);
getBeckePartition(&grid(0,0), GridSize, &becke[0]);
for (int i = 0; i<GridSize; i++) {
for (int a =0; a<natm; a++)
beckenorm[i] += becke[a * GridSize + i];
}
for (int i = 0; i<GridSize; i++) {
density[i] *= becke[ia*GridSize + i]/beckenorm[i];
}
densityYlm[ia].fit(rindex, &density[0]);
}
//void getDensityOnLebdevGridAtGivenR(int rindex, double* densityOut) {
//densityYlm.getValue(rindex, densityOut);
//}
void solvePoissonsEquation(int ia) {
double totalQ = densityYlm[ia].wts.dot(densityYlm[ia].GridValues * densityYlm[ia].lebdevgrid.col(3));
potentialYlm[ia] = densityYlm[ia];
int nr = densityYlm[ia].radialGrid.size();
double h = 1./(1.*nr+1.), rm = densityYlm[ia].rm;
VectorXd drdz(nr), d2rdz2(nr), b(nr);
VectorXd& z = densityYlm[ia].zgrid, &r = densityYlm[ia].radialGrid;
for (int i=0; i<nr; i++) {
drdz(i) = (-2.*M_PI * rm * sin(M_PI * z(i))) / pow(1. - cos(M_PI * z(i)), 2);
d2rdz2(i) = ( 2.* M_PI * M_PI * rm) *
(2 * pow(sin(M_PI * z(i)), 2.) + pow(cos(M_PI * z(i)), 2) - cos(M_PI * z(i)))
/ pow(1. - cos(M_PI * z(i)), 3);
}
MatrixXd A1Der(nr, nr), A2Der(nr, nr), A(nr, nr);
A1Der.setZero(); A2Der.setZero(); A.setZero();
A2Der.block(0,0,1,6) << -147., -255., 470., -285., 93., -13.;
A1Der.block(0,0,1,6) << -77., 150., -100., 50., -15., 2.;
A2Der.block(1,0,1,6) << 228., -420., 200., 15., -12., 2.;
A1Der.block(1,0,1,6) << -24., -35., 80., -30., 8., -1.;
A2Der.block(2,0,1,6) << -27., 270., -490., 270., -27., 2.;
A1Der.block(2,0,1,6) << 9., -45., 0., 45., -9., 1.;
for (int i=3; i<nr-3; i++) {
A2Der.block(i,i-3,1,7) << 2., -27., 270., -490., 270., -27., 2.;
A1Der.block(i,i-3,1,7) << -1., 9., -45., 0., 45., -9., 1.;
}
A2Der.block(nr-1, nr-6, 1, 6) << -13., 93., -285., 470.,-255.,-147.;
A1Der.block(nr-1, nr-6, 1, 6) << -2., 15., -50., 100.,-150., 77.;
A2Der.block(nr-2, nr-6, 1, 6) << 2., -12., 15., 200.,-420., 228.;
A1Der.block(nr-2, nr-6, 1, 6) << 1., -8., 30., -80., 35., 24.;
A2Der.block(nr-3, nr-6, 1, 6) << 2., -27., 270., -490., 270., -27.;
A1Der.block(nr-3, nr-6, 1, 6) << -1., 9., -45., 0., 45., -9.;
int lmax = densityYlm[ia].lmax;
for (int l = 0; l < lmax; l++) {
for (int m = -l; m < l+1; m++) {
int lm = l * l + (l + m);
b = -4 * M_PI * r.cwiseProduct(densityYlm[ia].CoeffsYlm.col(lm));
if (l == 0) {
b(0) += sqrt(4 * M_PI) * (-137. / (180. * h * h)/(drdz(0) * drdz(0))) * totalQ;
b(1) += sqrt(4 * M_PI) * ( 13. / (180. * h * h)/(drdz(1) * drdz(1))) * totalQ;
b(2) += sqrt(4 * M_PI) * ( -2. / (180. * h * h)/(drdz(2) * drdz(2))) * totalQ;
b(0) += sqrt(4 * M_PI) * ( 10. / (60. * h)*(-d2rdz2(0) / pow(drdz(0),3))) * totalQ;
b(1) += sqrt(4 * M_PI) * ( -2. / (60. * h)*(-d2rdz2(1) / pow(drdz(1),3))) * totalQ;
b(2) += sqrt(4 * M_PI) * ( 1. / (60. * h)*(-d2rdz2(2) / pow(drdz(2),3))) * totalQ;
}
for (int i=0; i<nr; i++) {
A.row(i) = A2Der.row(i) / (180. * h * h)/(drdz(i) * drdz(i))
+ A1Der.row(i) / (60 * h) * (-d2rdz2(i) / pow(drdz(i), 3));
A(i, i) += (-l * (l + 1) / r(i) / r(i));
}
potentialYlm[ia].CoeffsYlm.col(lm) = A.colPivHouseholderQr().solve(b);
}
}
}
void solveScreenedPoissonsEquation(int ia, double lambda) {
double totalQ = densityYlm[ia].wts.dot(densityYlm[ia].GridValues * densityYlm[ia].lebdevgrid.col(3));
totalQ = 0.0;
potentialYlm[ia] = densityYlm[ia];
int nr = densityYlm[ia].radialGrid.size();
double h = 1./(1.*nr+1.), rm = densityYlm[ia].rm;
VectorXd drdz(nr), d2rdz2(nr), b(nr);
VectorXd& z = densityYlm[ia].zgrid, &r = densityYlm[ia].radialGrid;
for (int i=0; i<nr; i++) {
drdz(i) = (-2.*M_PI * rm * sin(M_PI * z(i))) / pow(1. - cos(M_PI * z(i)), 2);
d2rdz2(i) = ( 2.* M_PI * M_PI * rm) *
(2 * pow(sin(M_PI * z(i)), 2.) + pow(cos(M_PI * z(i)), 2) - cos(M_PI * z(i)))
/ pow(1. - cos(M_PI * z(i)), 3);
}
MatrixXd A1Der(nr, nr), A2Der(nr, nr), A(nr, nr);
A1Der.setZero(); A2Der.setZero(); A.setZero();
A2Der.block(0,0,1,6) << -147., -255., 470., -285., 93., -13.;
A1Der.block(0,0,1,6) << -77., 150., -100., 50., -15., 2.;
A2Der.block(1,0,1,6) << 228., -420., 200., 15., -12., 2.;
A1Der.block(1,0,1,6) << -24., -35., 80., -30., 8., -1.;
A2Der.block(2,0,1,6) << -27., 270., -490., 270., -27., 2.;
A1Der.block(2,0,1,6) << 9., -45., 0., 45., -9., 1.;
for (int i=3; i<nr-3; i++) {
A2Der.block(i,i-3,1,7) << 2., -27., 270., -490., 270., -27., 2.;
A1Der.block(i,i-3,1,7) << -1., 9., -45., 0., 45., -9., 1.;
}
A2Der.block(nr-1, nr-6, 1, 6) << -13., 93., -285., 470.,-255.,-147.;
A1Der.block(nr-1, nr-6, 1, 6) << -2., 15., -50., 100.,-150., 77.;
A2Der.block(nr-2, nr-6, 1, 6) << 2., -12., 15., 200.,-420., 228.;
A1Der.block(nr-2, nr-6, 1, 6) << 1., -8., 30., -80., 35., 24.;
A2Der.block(nr-3, nr-6, 1, 6) << 2., -27., 270., -490., 270., -27.;
A1Der.block(nr-3, nr-6, 1, 6) << -1., 9., -45., 0., 45., -9.;
for (int i=0; i<nr; i++)
A2Der(i,i) = -lambda*lambda;
int lmax = densityYlm[ia].lmax;
for (int l = 0; l < lmax; l++) {
for (int m = -l; m < l+1; m++) {
int lm = l * l + (l + m);
b = -4 * M_PI * r.cwiseProduct(densityYlm[ia].CoeffsYlm.col(lm));
if (l == 0) {
b(0) += sqrt(4 * M_PI) * (-137. / (180. * h * h)/(drdz(0) * drdz(0))) * totalQ;
b(1) += sqrt(4 * M_PI) * ( 13. / (180. * h * h)/(drdz(1) * drdz(1))) * totalQ;
b(2) += sqrt(4 * M_PI) * ( -2. / (180. * h * h)/(drdz(2) * drdz(2))) * totalQ;
b(0) += sqrt(4 * M_PI) * ( 10. / (60. * h)*(-d2rdz2(0) / pow(drdz(0),3))) * totalQ;
b(1) += sqrt(4 * M_PI) * ( -2. / (60. * h)*(-d2rdz2(1) / pow(drdz(1),3))) * totalQ;
b(2) += sqrt(4 * M_PI) * ( 1. / (60. * h)*(-d2rdz2(2) / pow(drdz(2),3))) * totalQ;
}
for (int i=0; i<nr; i++) {
A.row(i) = A2Der.row(i) / (180. * h * h)/(drdz(i) * drdz(i))
+ A1Der.row(i) / (60 * h) * (-d2rdz2(i) / pow(drdz(i), 3));
A(i, i) += (-l * (l + 1) / r(i) / r(i));
}
potentialYlm[ia].CoeffsYlm.col(lm) = A.colPivHouseholderQr().solve(b);
}
}
}
void fitSplinePotential(int ia) {
splinePotential[ia].Init(potentialYlm[ia]);
}
void getPotentialBeckeOfAtom(int ia, int ngrid, double* grid, double* potential) {
splinePotential[ia].getPotential(ngrid, grid, potential);
}
void getPotentialBecke(int ngrid, double* grid, double* potential, int lmax,
int* nrad, double* rm, double* pdm) {
coordScale = 1.0;
centroid = new double[3];
centroid[0] = 0.5; centroid[1] = 0.5; centroid[2] = 0.5;
dm = pdm;
int lebedevOrder = 2*lmax + 1;
initAngularData(lmax, lebedevOrder);
initAtomGrids();
//time_t Initcurrent_time, current_time;
//Initcurrent_time = time(NULL);
int rank, psize;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &psize);
for (int ia=rank; ia<natm; ia+=psize) {
//current_time = time(NULL); cout << "atom "<<ia<<" "<<current_time-Initcurrent_time<<endl;
initDensityRadialGrid(ia, nrad[ia], rm[ia]);
//cout << densityYlm[ia].radialGrid.rows()<<" num r rows "<<endl;
for (int rindex = 0; rindex < nrad[ia] ; rindex++)
fitDensity(ia, rindex);
//current_time = time(NULL); cout << "fit density "<<ia<<" "<<current_time-Initcurrent_time<<endl;
solvePoissonsEquation(ia);
//current_time = time(NULL); cout << "solve poisson "<<ia<<" "<<current_time-Initcurrent_time<<endl;
fitSplinePotential(ia);
//current_time = time(NULL); cout << "fit spline "<<ia<<" "<<current_time-Initcurrent_time<<endl;
getPotentialBeckeOfAtom(ia, ngrid, grid, potential);
//current_time = time(NULL); cout << "get potential "<<ia<<" "<<current_time-Initcurrent_time<<endl;
}
cout.precision(15);
MPI_Allreduce(MPI_IN_PLACE, potential, ngrid, MPI_DOUBLE, MPI_SUM, comm);
delete [] centroid;
}
<file_sep>#pragma once
#include <vector>
struct Coulomb {
std::vector<double> exponents;
std::vector<double> weights;
};
struct Coulomb_14_8_8 : public Coulomb {
Coulomb_14_8_8();
};
struct Coulomb_14_14_8 : public Coulomb{
Coulomb_14_14_8();
};
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Global_HEADER_H
#define Global_HEADER_H
#include <boost/interprocess/managed_shared_memory.hpp>
#include <random>
#include <Eigen/Dense>
#include "input.h"
#ifndef SERIAL
#include "mpi.h"
extern MPI_Comm shmcomm, localcomm;
#endif
//class schedule;
class Profile;
class twoInt;
class oneInt;
class twoIntHeatBathSHM;
extern int commrank, shmrank, localrank;
extern int commsize, shmsize, localsize;
#ifdef Complex
#define MatrixXx MatrixXcd
#define CItype std::complex<double>
#else
#define MatrixXx Eigen::MatrixXd
#define CItype double
#endif
const int DetLen = 10;
const int innerDetLen = 2;
const int max_nreplicas = 8;
extern boost::interprocess::shared_memory_object int2Segment;
extern boost::interprocess::mapped_region regionInt2;
extern std::string shciint2;
extern boost::interprocess::shared_memory_object int2SHMSegment;
extern boost::interprocess::mapped_region regionInt2SHM;
extern std::string shciint2shm;
extern boost::interprocess::shared_memory_object int2SHMCASSegment;
extern boost::interprocess::mapped_region regionInt2SHMCAS;
extern std::string shciint2shmcas;
extern std::mt19937 generator;
double getTime();
void license();
extern schedule schd;
extern double startofCalc;
extern Profile prof;
extern twoInt I2;
extern oneInt I1;
extern double coreE;
extern twoIntHeatBathSHM I2hb;
extern twoIntHeatBathSHM I2hbCAS;
#endif
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef CX_ALGEBRA_H
#define CX_ALGEBRA_H
#include <cstddef>
#include "CxDefs.h"
#define RESTRICT AIC_RP
#include "CxFortranInt.h"
using std::ptrdiff_t;
using std::size_t;
typedef unsigned int uint;
// behold the elegance of FORTRAN77/C interfaces!
extern "C"{
// declaration of FORTRAN77 blas/lapack routines... (to exist in ACML/MKL/etc.)
void dcopy_(const size_t& n, double *A, const size_t& inxa, double*B, const size_t& inxb);
// C := alpha*op( A )*op( B ) + beta*C,
// Trans*: 'N' (notranspose), 'T' (transpose) or 'C' (conjugate-transpose)(=T)
void sgemm_( char const &TransA, char const &TransB, size_t &M, size_t &N, size_t &K,
float &alpha, FScalar const *A, size_t &lda, FScalar const *B, size_t &ldb,
float &beta, FScalar *C, size_t &ldc );
void dgemm_( char const &TransA, char const &TransB, FINTARG M, FINTARG N, FINTARG K,
FDBLARG alpha, double const *A, FINTARG lda, double const *B, FINTARG ldb,
FDBLARG beta, double *C, FINTARG ldc );
// C := alpha*op(A)*op(A^T) + beta*C,
#define SSYRK FORT_Extern(ssyrk,SSYRK)
void SSYRK( char const &UpLo, char const &TransA, FINTARG N, FINTARG K,
FDBLARG alpha, FScalar const *A, FINTARG lda,
FDBLARG beta, FScalar *C, FINTARG ldc );
#define SGEMV FORT_Extern(sgemv,SGEMV)
void SGEMV(char const &Trans, FINTARG M, FINTARG N, FDBLARG Alpha, FScalar const *A, FINTARG lda, FScalar const *X, FINTARG incx, FDBLARG Beta, FScalar *y, FINTARG incy);
#define DGEMV FORT_Extern(dgemv,DGEMV)
void DGEMV(char const &Trans, FINTARG M, FINTARG N, FDBLARG Alpha, FScalar const *A, FINTARG lda, FScalar const *X, FINTARG incx, FDBLARG Beta, FScalar *y, FINTARG incy);
// computes eigenvalues and eigenvectors of a symmetric matrix:
// jobz: 'N'/'V': compute eigenvalues only/compute also eigenvectors
// uplo: 'U'/'L': upper/lower triangle of A is stored.
// N: matrix size. A is N x N matrix.
// A: input matrix, output vectors. LDA: row stride A.
// W: output, eigenvectors in ascending order. (vector of length N).
// Work: work space
// lWork: Work space size. "For optimal efficiency, LWORK >= (NB+2)*N,
// where NB is the blocksize for DSYTRD returned by ILAENV."
#define SSYEV FORT_Extern(ssyev,SSYEV)
void ssyev_(char const &jobz, char const &uplo, size_t& N, FScalar *A, size_t& LDA, FScalar *W, FScalar *WORK, size_t& LWORK, size_t &INFO );
void dsyev_(char const &jobz, char const &uplo, size_t& N, FScalar *A, size_t& LDA, FScalar *W, FScalar *WORK, size_t& LWORK, size_t &INFO );
#define SSYGV FORT_Extern(ssygv,SSYGV)
void ssygv_(FINTARG ITYPE, char const &JOBZ, char const &UPLO, size_t N,
FScalar *A, size_t LDA, FScalar const *B, size_t LDB, FScalar *EW,
FScalar *WORK, size_t &LWORK, size_t &INFO );
void dsygv_(size_t ITYPE, char const &JOBZ, char const &UPLO, size_t N,
FScalar *A, size_t LDA, FScalar const *B, size_t LDB, FScalar *EW,
FScalar *WORK, size_t &LWORK, size_t &INFO );
// compute m x n matrix LU factorization.
// info: =0 success. > 0: matrix is singular, factorization cannot be used
// to solve linear systems.
#define SGETRF FORT_Extern(sgetrf,SGETRF)
void SGETRF(FINTARG M, FINTARG N, FScalar const *pA, FINTARG LDA, FORTINT *ipiv, FORTINT *INFO );
#define STRTRI FORT_Extern(strtri,STRTRI)
void STRTRI(char const &Uplo, char const &Diag, FINTARG N, FScalar *pA, FINTARG LDA, FORTINT *info);
// solves A * X = B for X. n: number of equations (order of A).
// needs LU decomposition as input.
#define SGESV FORT_Extern(sgesv,SGESV)
void SGESV( FINTARG n, FINTARG nrhs, FScalar *A, FINTARG lda, FINTARG ipivot, FScalar *B,
FINTARG ldb, FORTINT &info );
#define SPOTRF FORT_Extern(spotrf,SPOTRF)
void SPOTRF(char const &UpLo, FINTARG n, FScalar *A, FINTARG lda, FORTINT *info);
#define DPOTRS FORT_Extern(spotrs,SPOTRS)
void SPOTRS(char const &UpLo, FINTARG n, FINTARG nRhs, FScalar *A, FINTARG lda, FScalar *B, FINTARG ldb, FORTINT *info);
#define STRTRS FORT_Extern(strtrs,STRTRS)
void STRTRS(char const &UpLo, char const &Trans, char const &Diag, FINTARG N, FINTARG NRHS, FScalar *A, FINTARG lda, FScalar *B, FINTARG ldb, FORTINT *info);
// ^- gna.. dtrtrs is rather useless. It just does some argument checks and
// then calls dtrsm with side == 'L' (which probably does the same checks again).
#define STRSM FORT_Extern(strsm,STRSM)
void STRSM(char const &Side, char const &UpLo, char const &Trans, char const &Diag, FINTARG nRowsB, FINTARG nColsB, FScalar const &Alpha, FScalar *A, FINTARG lda, FScalar *B, FINTARG ldb, FORTINT *info);
#define STRMM FORT_Extern(strmm,STRMM)
void STRMM(char const &Side, char const &UpLo, char const &Trans, char const &Diag, FINTARG nRowsB, FINTARG nColsB, FScalar const &Alpha, FScalar *A, FINTARG lda, FScalar *B, FINTARG ldb);
// linear least squares using divide & conquer SVD.
#define SGELSS FORT_Extern(sgelss,SGELSS)
void SGELSS(FINTARG M, FINTARG N, FINTARG NRHS, FScalar *A, FINTARG LDA, FScalar *B, FINTARG LDB, FScalar *S, FScalar const &RCOND, FORTINT *RANK,
FScalar *WORK, FINTARG LWORK, FORTINT *INFO );
}
namespace ct {
void Mxm(FScalar *pOut, ptrdiff_t iRowStO, ptrdiff_t iColStO,
FScalar const *pA, ptrdiff_t iRowStA, ptrdiff_t iColStA,
FScalar const *pB, ptrdiff_t iRowStB, ptrdiff_t iColStB,
size_t nRows, size_t nLink, size_t nCols, bool AddToDest = false, FScalar fFactor = 1.0);
// note: both H and S are overwritten. Eigenvectors go into H.
void DiagonalizeGen(FScalar *pEw, FScalar *pH, size_t ldH, FScalar *pS, size_t ldS, size_t N);
void Diagonalize(FScalar *pEw, FScalar *pH, size_t ldH, size_t N);
inline void Mxv(FScalar *pOut, ptrdiff_t iStO, FScalar const *pMat, ptrdiff_t iRowStM, ptrdiff_t iColStM,
FScalar const *pIn, ptrdiff_t iStI, uint nRows, uint nLink, bool AddToDest = false, FScalar fFactor = 1.0)
{
#ifdef _SINGLE_PRECISION
if ( iRowStM == 1 )
SGEMV('N', nRows, nLink, fFactor, pMat, iColStM, pIn,iStI, AddToDest? 1.0 : 0.0, pOut,iStO);
else
SGEMV('T', nLink, nRows, fFactor, pMat, iRowStM, pIn,iStI, AddToDest? 1.0 : 0.0, pOut,iStO);
#else
if ( iRowStM == 1 )
DGEMV('N', nRows, nLink, fFactor, pMat, iColStM, pIn,iStI, AddToDest? 1.0 : 0.0, pOut,iStO);
else
DGEMV('T', nLink, nRows, fFactor, pMat, iRowStM, pIn,iStI, AddToDest? 1.0 : 0.0, pOut,iStO);
#endif
}
template<class FScalar>
inline FScalar Dot( FScalar const *a, FScalar const *b, std::size_t n )
{
FScalar
r = 0;
for ( std::size_t i = 0; i < n; ++ i )
r += a[i] * b[i];
return r;
};
// r += f * x
template<class FScalar>
inline void Add( FScalar * RESTRICT r, FScalar const * RESTRICT x, FScalar f, std::size_t n )
{
if ( f != 1.0 ) {
for ( std::size_t i = 0; i < n; ++ i )
r[i] += f * x[i];
} else {
for ( std::size_t i = 0; i < n; ++ i )
r[i] += x[i];
}
};
// r *= f
template<class FScalar>
inline void Scale( FScalar *r, FScalar f, std::size_t n )
{
for ( std::size_t i = 0; i < n; ++ i )
r[i] *= f;
};
// r = f * x
template<class FScalar>
inline void Move( FScalar * RESTRICT r, FScalar const * RESTRICT x, FScalar f, std::size_t n )
{
for ( std::size_t i = 0; i < n; ++ i )
r[i] = f * x[i];
};
} // namespace ct
#endif // CX_ALGEBRA_H
// kate: indent-width 4
<file_sep>#!/bin/bash
rm *.bkp BestDeterminant.txt vmc.out gfmc.out pt2_energies* -f >/dev/null 2>&1
find . -name *.bkp |xargs rm >/dev/null 2>&1
find . -name BestDeterminant.txt|xargs rm >/dev/null 2>&1
find . -name amsgrad.bkp |xargs rm >/dev/null 2>&1
find . -name cpsslaterwave.bkp|xargs rm >/dev/null 2>&1
find . -name vmc.out | xargs rm >/dev/null 2>&1
find . -name gfmc.out | xargs rm >/dev/null 2>&1
find . -name ci.out | xargs rm >/dev/null 2>&1
find . -name nevpt.out | xargs rm >/dev/null 2>&1
find . -name nevpt_print.out | xargs rm >/dev/null 2>&1
find . -name nevpt_read.out | xargs rm >/dev/null 2>&1
find . -name pt2_energies* | xargs rm >/dev/null 2>&1
find . -name stoch_samples_* | xargs rm >/dev/null 2>&1
find . -name fciqmc.out | xargs rm >/dev/null 2>&1
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CPS_HEADER_H
#define CPS_HEADER_H
#include "Correlator.h"
#include <Eigen/Dense>
#include <vector>
#include <iostream>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <string>
class Determinant;
/*
* CPS is a product of correlators
*/
class CPS {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize (Archive & ar, const unsigned int version) {
ar & cpsArray
& mapFromOrbitalToCorrelator
& commonCorrelators;
}
public:
bool twoSiteOrSmaller;
std::vector<Correlator> cpsArray;
std::vector<std::vector<int>> mapFromOrbitalToCorrelator;
std::vector<int> commonCorrelators;
//reads correlator file and makes cpsArray, orbitalToCPS
CPS ();
CPS (std::vector<Correlator>& pcpsArray);
void generateMapFromOrbitalToCorrelators();
double Overlap(const Determinant& d) const ;
/*
* Takes an occupation number representation of two determinants
* in the local orbital basis and calculates the ratio of overlaps
* <d1|CPS>/<d2|CPS>
* PARAMS:
*
* Determinant: the occupation number representation of dets
*
* RETURN:
* <d1|CPS>/<d2|CPS>
*
*/
double OverlapRatio(const Determinant& d1, const Determinant& d2) const ;
/*
* return ratio of overlaps of CPS with d and (i->a,j->b)excited-d (=dcopy)
*/
double OverlapRatio(int i, int a, const Determinant &dcopy, const Determinant &d) const ;
double OverlapRatio(int i, int j, int a, int b, const Determinant &dcopy, const Determinant &d) const;
double OverlapRatio(int i, int a, const BigDeterminant &dcopy, const BigDeterminant &d) const ;
double OverlapRatio(int i, int j, int a, int b, const BigDeterminant &dcopy, const BigDeterminant &d) const;
/*
* Takes an occupation number representation of a determinant
* in the local orbital basis and calculates the overlap
* the CPS and also the overlap of the determinant
* with respect to the tangent vector w.r.t to all the
* parameters in the wavefuncion
*
* PARAMS:
*
* Determinant: the occupation number representation of the determinant
* grad : the vector of the gradient. This vector is long and contains
* the space for storing gradients with respect to all the parameters
* in the wavefunction and not just this CPS and so the index startIndex
* is needed to indentify at what index should we start populating the
* gradient w.r.t to this CPS in the vector
* ovlp : <d|CPS>
* startIndex : The location in the vector gradient from where to start populating
* the gradient w.r.t to the current Correlator
*/
void OverlapWithGradient (const Determinant& d,
Eigen::VectorBlock<Eigen::VectorXd>& grad,
const double& ovlp) const;
void getVariables(Eigen::VectorBlock<Eigen::VectorXd> &v) const ;
long getNumVariables() const;
void updateVariables(const Eigen::VectorBlock<Eigen::VectorXd> &v);
void printVariables() const;
std::string getfileName() const {return "CPS";};
};
#endif
<file_sep>#include <iostream>
#include <cmath>
#include <string.h>
#include <algorithm>
#include <numeric>
#include <complex>
#include "CxMemoryStack.h"
#include "GeneratePolynomials.h"
#include "IrAmrr.h"
#include "IrBoysFn.h"
#include "BasisShell.h"
#include "Integral2c_Boys.h"
#include "LatticeSum.h"
#include "interface.h"
using namespace std;
using namespace ir;
void Add2(double * pOut, double const * pIn, double f, size_t n)
{
size_t i = 0;
for ( ; i < (n & ~3); i += 4 ) {
pOut[i] += f * pIn[i];
pOut[i+1] += f * pIn[i+1];
pOut[i+2] += f * pIn[i+2];
pOut[i+3] += f * pIn[i+3];
}
pOut += i;
pIn += i;
switch(n - i) {
case 3: pOut[2] += f*pIn[2];
case 2: pOut[1] += f*pIn[1];
case 1: pOut[0] += f*pIn[0];
default: break;
}
}
// output: contracted kernels Fm(rho,T), format: (TotalL+1) x nCoA x nCoC
void Int2e2c_EvalCoKernels(double *pCoFmT, uint TotalL,
BasisShell *pA, BasisShell *pC,
double Tx, double Ty, double Tz,
double PrefactorExt, double* pInv2Alpha, double* pInv2Gamma,
Kernel* kernel,
LatticeSum& latsum, ct::FMemoryStack &Mem)
{
double t = Tx*Tx + Ty*Ty + Tz*Tz;
double *pFmT;
Mem.Alloc(pFmT, TotalL + 1); // FmT for current primitive.
double Eta2Rho = kernel->getname() == coulombKernel ? latsum.Eta2RhoCoul : latsum.Eta2RhoOvlp;
// loop over primitives (that's all the per primitive stuff there is)
for (uint iExpC = 0; iExpC < pC->nFn; ++ iExpC)
for (uint iExpA = 0; iExpA < pA->nFn; ++ iExpA)
{
double
Alpha = pA->exponents[iExpA],
Gamma = pC->exponents[iExpC],
InvEta = 1./(Alpha + Gamma),
Rho = (Alpha * Gamma)*InvEta, // = (Alpha * Gamma)*/(Alpha + Gamma)
Prefactor = (M_PI*InvEta)*std::sqrt(M_PI*InvEta); // = (M_PI/(Alpha+Gamma))^{3/2}
Prefactor *= PrefactorExt;
Prefactor *= pInv2Gamma[iExpC] * pInv2Alpha[iExpA];
//If eta is smaller than desiredrho then no contribution from real space
double eta = 1.0;
if (Rho <= Eta2Rho) continue;
else {
eta = sqrt(Eta2Rho/Rho);
}
if (Rho > Eta2Rho && kernel->getname() != coulombKernel) eta = 1.0;
// calculate derivatives (D/Dt)^m exp(-rho t) with t = (A-C)^2.
kernel->getValueRSpace(pFmT, Rho*t, TotalL, Prefactor, Rho, eta, Mem);
// convert from Gm(rho,T) to Fm(rho,T) by absorbing powers of rho
// (those would normally be present in the R of the MDRR)
double
RhoPow = 1.;
double maxVal = 0;
for ( uint i = 0; i < TotalL + 1; ++ i ){
pFmT[i] *= RhoPow;
RhoPow *= -2*Rho;
if (maxVal < abs(pFmT[i])) maxVal = abs(pFmT[i]);
}
if (maxVal*max(1., pow(t,TotalL/2)) < latsum.screen) continue;
// contract (lamely). However, normally either nCo
// or nFn, or TotalL (or even all of them at the same time)
// will be small, so I guess it's okay.
for (uint iCoC = 0; iCoC < pC->nCo; ++ iCoC)
for (uint iCoA = 0; iCoA < pA->nCo; ++ iCoA) {
double CoAC = pC->contractions(iExpC, iCoC) *
pA->contractions(iExpA, iCoA);
Add2(&pCoFmT[(TotalL+1)*(iCoA + pA->nCo*iCoC)],
pFmT, CoAC, (TotalL+1));
}
}
Mem.Free(pFmT);
}
void makeRealSummation(double *&pOutR, unsigned &TotalCo, BasisShell *pA, BasisShell *pC,
double Tx, double Ty, double Tz, double Prefactor, unsigned TotalLab,
double* pInv2Alpha, double* pInv2Gamma, Kernel* kernel,
LatticeSum& latsum, ct::FMemoryStack& Mem) {
double* pOutR_loc, *pCoFmT, *pDataR_LapC;
int L = TotalLab + (kernel->getname() == kineticKernel ? 2 : 0);
Mem.ClearAlloc(pOutR_loc, (TotalLab+1)*(TotalLab+2)/2 * TotalCo);
Mem.ClearAlloc(pDataR_LapC, (L+1)*(L+2)/2);
size_t *Tidx; //indexed such that T will increase
latsum.getIncreasingIndex(Tidx, Tx, Ty, Tz, Mem);
for (int r = 0; r<latsum.Rdist.size(); r++) {
double Tx_r = Tx + latsum.Rcoord[3*Tidx[r]+0],
Ty_r = Ty + latsum.Rcoord[3*Tidx[r]+1],
Tz_r = Tz + latsum.Rcoord[3*Tidx[r]+2];
Mem.ClearAlloc(pCoFmT, (L+1) * TotalCo);
Int2e2c_EvalCoKernels(pCoFmT, L, pA, pC, Tx_r, Ty_r, Tz_r, Prefactor,
pInv2Alpha, pInv2Gamma, kernel, latsum, Mem);
//go from [0]^m -> [r]^0 using mcmurchie-davidson
for (uint iCoC = 0; iCoC < pC->nCo; ++ iCoC)
for (uint iCoA = 0; iCoA < pA->nCo; ++ iCoA) {
double
*pFmT = &pCoFmT[(L+1) * (iCoA + pA->nCo*iCoC)],
*pDataR_ = &pOutR_loc[nCartY(TotalLab) * (iCoA + pA->nCo*iCoC)];
if (kernel->getname() == kineticKernel) {
ShellMdrr(pDataR_LapC, pFmT, Tx_r, Ty_r, Tz_r, L);
ShellLaplace(pDataR_, pDataR_LapC, 1, L - 2);
}
else
ShellMdrr(pDataR_, pFmT, Tx_r, Ty_r, Tz_r, L);
}
double maxPout = 0;
for (int i=0; i<(TotalLab+1)*(TotalLab+2)/2 * TotalCo; i++) {
pOutR[i] += pOutR_loc[i];
maxPout = max(maxPout, abs(pOutR_loc[i]));
pOutR_loc[i] = 0.0;
}
Mem.Free(pCoFmT);
if (maxPout < latsum.screen) {
break;
}
}
}
void makeReciprocalSummation(double *&pOutR, unsigned &TotalCo, BasisShell *pA, BasisShell *pC, double Tx, double Ty, double Tz, double Prefactor, unsigned TotalLab, double* pInv2Alpha, double* pInv2Gamma, Kernel* kernel, LatticeSum& latsum, ct::FMemoryStack& Mem)
{
int L = TotalLab ;
int LA = pA->l, LC = pC->l;
//calcualte the reciprocal space contribution
double background ;
double *pReciprocalSum;
Mem.Alloc(pReciprocalSum, (L+1)*(L+2)/2);
double Eta2Rho = kernel->getname() == coulombKernel ? latsum.Eta2RhoCoul : latsum.Eta2RhoOvlp;
double screen = latsum.screen;
//this will work for all rho that are above the Et2Rho in coulomb kernel
ksumTime1.start();
if (kernel->getname() == coulombKernel) {
//for (int i=0; i<(L+1)*(L+2)/2; i++)
//pReciprocalSum[i] = 0.0 ;
ksumKsum.start();
int T1 = latsum.indexCenter(*pA);
int T2 = latsum.indexCenter(*pC);
int T = T1 == T2 ? 0 : max(T1, T2)*(max(T1, T2)+1)/2 + min(T1, T2);
int startIdx = latsum.KSumIdx[T][L];
for (int i=0; i<(L+1)*(L+2)/2; i++)
pReciprocalSum[i] = latsum.KSumVal[startIdx+i] ;
ksumKsum.stop();
for (uint iCoC = 0; iCoC < pC->nCo; ++ iCoC)
for (uint iCoA = 0; iCoA < pA->nCo; ++ iCoA) {
double CoAC = 0;
double bkgrnd = 0.0;
for (uint iExpC = 0; iExpC < pC->nFn; ++ iExpC)
for (uint iExpA = 0; iExpA < pA->nFn; ++ iExpA)
{
double
Alpha = pA->exponents[iExpA],
Gamma = pC->exponents[iExpC],
InvEta = 1./(Alpha + Gamma),
Rho = (Alpha * Gamma)*InvEta;
if (Rho <= Eta2Rho) continue;
double Eta = sqrt(Eta2Rho/Rho);
double Omega = Rho <= Eta2Rho ? 1.0e9 : sqrt(Rho * Eta * Eta /(1. - Eta * Eta)) ;
double Eta2rho = Eta2Rho;
double scale = Prefactor * pInv2Gamma[iExpC] * pInv2Alpha[iExpA];
scale *= M_PI*M_PI*M_PI*M_PI/pow(Alpha*Gamma, 1.5)/ latsum.RVolume;
CoAC += pC->contractions(iExpC, iCoC) *
pA->contractions(iExpA, iCoA) * scale;
if (LA == 0 && LC == 0)
bkgrnd += pC->contractions(iExpC, iCoC) *
pA->contractions(iExpA, iCoA) *
M_PI * 16.*M_PI*M_PI * tgamma((LA+3)/2.)/(2. * pow(Alpha,0.5*(LA+3)))
* tgamma((LC+3)/2.)/(2. * pow(Gamma,0.5*(LC+3)))/Omega/Omega/ latsum.RVolume;
}
Add2(&pOutR[(TotalLab+1)*(TotalLab+2)/2*(iCoA + pA->nCo*iCoC)],
pReciprocalSum, CoAC, (TotalLab+1)*(TotalLab+2)/2);
if (LA == 0 && LC == 0)
Add2(&pOutR[(TotalLab+1)*(TotalLab+2)/2*(iCoA + pA->nCo*iCoC)],
&bkgrnd, -1., (TotalLab+1)*(TotalLab+2)/2);
}
}
ksumTime1.stop();
ksumTime2.start();
//now go back to calculating contribution from reciprocal space
for (uint iExpC = 0; iExpC < pC->nFn; ++ iExpC)
for (uint iExpA = 0; iExpA < pA->nFn; ++ iExpA)
{
double
Alpha = pA->exponents[iExpA],
Gamma = pC->exponents[iExpC],
InvEta = 1./(Alpha + Gamma),
Rho = (Alpha * Gamma)*InvEta; // = (Alpha * Gamma)*/(Alpha + Gamma)
//if (Rho < latsum.Kdist[0]/120) continue;
double Eta = Rho <= Eta2Rho ? 1. : sqrt(Eta2Rho/Rho);
double Omega = Rho <= Eta2Rho ? 1.0e9 : sqrt(Rho * Eta * Eta /(1. - Eta * Eta)) ;
double Eta2rho = Eta * Eta * Rho;
//coulomb kernel always includes reciprocal space summations
//if (Rho > Eta2Rho && kernel->getname() != coulombKernel) continue;
if (Rho > Eta2Rho ) continue;
else if (Rho <= Eta2Rho && kernel->getname() != coulombKernel) Eta2rho = Rho;
double scale = Prefactor * pInv2Gamma[iExpC] * pInv2Alpha[iExpA];
if (kernel->getname() == coulombKernel)
scale *= M_PI*M_PI*M_PI*M_PI/pow(Alpha*Gamma, 1.5)/ latsum.RVolume;
else if (kernel->getname() != coulombKernel)
scale *= pow(M_PI*M_PI/Alpha/Gamma, 1.5)/latsum.RVolume;
for (int i=0; i<(L+1)*(L+2)/2; i++)
pReciprocalSum[i] = 0.0;
//this is ugly, in coulomb kernel the G=0 term is discarded but not in others
if (kernel->getname() == overlapKernel) {
double expVal = kernel->getValueKSpace(0, 1.0, Eta2rho);
double maxG = getHermiteReciprocal(L, pReciprocalSum,
0., 0., 0., Tx, Ty, Tz, expVal, scale);
}
for (int k=0; k<latsum.Kdist.size(); k++) {
double expVal = kernel->getValueKSpace(latsum.Kdist[k], 1.0, Eta2rho);
double maxG = getHermiteReciprocal(L, pReciprocalSum,
latsum.Kcoord[3*k+0],
latsum.Kcoord[3*k+1], latsum.Kcoord[3*k+2],
Tx, Ty, Tz,
expVal, scale);
if (abs(maxG * scale * expVal) < screen ) {
break;
}
}
//the background term, only applies to coulomb kernel
if (!(Rho <= Eta2Rho) && LA == 0 && LC == 0 && kernel->getname() == coulombKernel) {
pReciprocalSum[0] -= M_PI * 16.*M_PI*M_PI * tgamma((LA+3)/2.)/(2. * pow(Alpha,0.5*(LA+3)))
* tgamma((LC+3)/2.)/(2. * pow(Gamma,0.5*(LC+3)))/Omega/Omega/ latsum.RVolume;
}
//cout <<"bkgrnd "<< pReciprocalSum[0]<<endl;
for (uint iCoC = 0; iCoC < pC->nCo; ++ iCoC)
for (uint iCoA = 0; iCoA < pA->nCo; ++ iCoA) {
double CoAC = pC->contractions(iExpC, iCoC) *
pA->contractions(iExpA, iCoA);
Add2(&pOutR[(TotalLab+1)*(TotalLab+2)/2*(iCoA + pA->nCo*iCoC)],
pReciprocalSum, CoAC, (TotalLab+1)*(TotalLab+2)/2);
}
}
ksumTime2.stop();
Mem.Free(pReciprocalSum);
}
void Int2e2c_EvalCoShY(double *&pOutR, unsigned &TotalCo, BasisShell *pA, BasisShell *pC, double Prefactor, unsigned TotalLab, double* pInv2Alpha, double* pInv2Gamma, Kernel* kernel, LatticeSum& latsum, ct::FMemoryStack& Mem)
{
//CHANGE THIS to minimum distance between A and periodic image of C
double Tx, Ty, Tz;
latsum.getRelativeCoords(pA, pC, Tx, Ty, Tz);
TotalCo = pA->nCo * pC->nCo;
unsigned
L = TotalLab ;
Mem.ClearAlloc(pOutR, (L+1)*(L+2)/2 * TotalCo);
realSumTime.start();
makeRealSummation(pOutR, TotalCo, pA, pC, Tx, Ty, Tz, Prefactor, TotalLab, pInv2Alpha, pInv2Gamma, kernel, latsum, Mem);
realSumTime.stop();
kSumTime.start();
Tx = pA->Xcoord - pC->Xcoord;
Ty = pA->Ycoord - pC->Ycoord;
Tz = pA->Zcoord - pC->Zcoord;
makeReciprocalSummation(pOutR, TotalCo, pA, pC, Tx, Ty, Tz, Prefactor, TotalLab, pInv2Alpha, pInv2Gamma, kernel, latsum, Mem);
kSumTime.stop();
}
void EvalInt2e2c( double *pOut, size_t StrideA, size_t StrideC,
BasisShell *pA, BasisShell *pC, double Prefactor, bool Add,
Kernel* kernel,
LatticeSum& latsum, ct::FMemoryStack &Mem )
{
uint
lc = pC->l, la = pA->l,
TotalCo;
//we will need these in both the real and reciprocal space summations
double
*pInv2Alpha, *pInv2Gamma;
Mem.Alloc(pInv2Alpha, pA->nFn);
Mem.Alloc(pInv2Gamma, pC->nFn);
for (uint iExpA = 0; iExpA < pA->nFn; ++ iExpA)
pInv2Alpha[iExpA] = bool(pA->l)? std::pow(+1.0/(2*pA->exponents[iExpA]), (int)pA->l) : 1.;
for (uint iExpC = 0; iExpC < pC->nFn; ++ iExpC)
pInv2Gamma[iExpC] = bool(pC->l)? std::pow(-1.0/(2*pC->exponents[iExpC]), (int)pC->l) : 1.;
double
*pDataR, *pR1, *pFinal;
Int2e2c_EvalCoShY(pDataR, TotalCo, pA, pC, Prefactor, la + lc, pInv2Alpha, pInv2Gamma, kernel, latsum, Mem);
Mem.Alloc(pR1, nCartY(la)*(2*lc+1) * TotalCo);
Mem.Alloc(pFinal, (2*la+1)*(2*lc+1) * TotalCo);
ShTrA_YY(pR1, pDataR, lc, (la + lc), TotalCo);
ShTrA_YY(pFinal, pR1, la, la, (2*lc + 1)*TotalCo);
// now: (2*la+1) x (2*lc+1) x nCoA x nCoC
Scatter2e2c(pOut, StrideA, StrideC, pFinal, la, lc, 1, pA->nCo, pC->nCo, Add);
Mem.Free(pInv2Alpha);
}
// write (2*la+1) x (2*lc+1) x nCoA x nCoC matrix to final destination.
void Scatter2e2c(double * pOut, size_t StrideA, size_t StrideC,
double const * pIn, size_t la, size_t lc,
size_t nComp, size_t nCoA, size_t nCoC, bool Add)
{
size_t nShA = 2*la+1, nShC = 2*lc+1;
if ( Add ) {
for (size_t iCoC = 0; iCoC < nCoC; ++ iCoC)
for (size_t iCoA = 0; iCoA < nCoA; ++ iCoA)
for (size_t iShC = 0; iShC < nShC; ++ iShC)
for (size_t iShA = 0; iShA < nShA; ++ iShA)
pOut[(iShA + nShA*iCoA)*StrideA + (iShC + nShC*iCoC)*StrideC]
+= pIn[iShA + nShA * (iShC + nShC * nComp * (iCoA + nCoA * iCoC))];
} else {
for (size_t iCoC = 0; iCoC < nCoC; ++ iCoC)
for (size_t iCoA = 0; iCoA < nCoA; ++ iCoA)
for (size_t iShC = 0; iShC < nShC; ++ iShC)
for (size_t iShA = 0; iShA < nShA; ++ iShA)
pOut[(iShA + nShA*iCoA)*StrideA + (iShC + nShC*iCoC)*StrideC]
= pIn[iShA + nShA * (iShC + nShC * nComp *(iCoA + nCoA * iCoC))];
}
}
<file_sep>import numpy as np
nsites = 20
sqrt2 = 2**0.5
orbUp = np.zeros(shape=(nsites, nsites))
orbDn = np.zeros(shape=(nsites, nsites))
fh = open('uhf.txt', 'r')
i = 0
for line in fh:
for j in range(nsites):
orbUp[i, j] = line.split()[j]
for j in range(nsites):
orbDn[i, j] = line.split()[j + nsites]
i = i + 1
fileHF = open("ghf.txt", 'w')
for i in range(nsites):
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbDn[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j+nsites/2]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbDn[i,j+nsites/2]/sqrt2))
fileHF.write('\n')
for i in range(nsites):
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(-orbDn[i,j]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(orbUp[i,j+nsites/2]/sqrt2))
for j in range(nsites/2):
fileHF.write('%16.10e '%(-orbDn[i,j+nsites/2]/sqrt2))
fileHF.write('\n')
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef CX_INDENTSTREAM_H
#define CX_INDENTSTREAM_H
#include <ostream>
#include <sstream>
#include <string>
#include "assert.h"
typedef unsigned int
uint;
namespace fmt {
extern int
g_IndentIndex,
g_PreIndentIndex;
extern bool
g_IndentIndexInitialized;
/// stream modifier which changes the indendation level on an
/// ostream. Has effect only if the ostream/ostream adapter
/// supports this functionality.
struct ind{
ind( int IndentDelta = +1, bool endl = false )
: nIndentDelta(IndentDelta), EmitEndl(endl)
{}
int nIndentDelta;
bool EmitEndl;
};
struct unind : public ind { unind() : ind(-1,false) {}; };
struct eind : public ind { eind() : ind(+1,true) {}; };
struct eunind : public ind { eunind() : ind(-1,true) {}; };
template<class FChar>
std::basic_ostream<FChar> &operator << ( std::basic_ostream<FChar> &out, ind const &in )
{
if ( in.EmitEndl )
out << std::endl;
else
out.flush();
long
&nIndentLevel = out.iword(g_IndentIndex);
nIndentLevel += in.nIndentDelta;
return out;
}
// a pre-indent is a string which is emitted at the start of each line, before
// the spaces for the indendation take effect. This allows emitting some left-
// aligned data before the structured data. It can be used, for example, to
// implement line numbers or similar debug information.
template<class FChar>
struct set_preindent {
// If used, pre-indent for the stream will be taken from the referenced
// string; if set to 0, pre-indent is dsiabled. Note that this sets a
// *pointer*. MAKE SURE that the corresponding string object is not
// destroyed until pre-indent is reset to 0! Otherwise crash! (in the
// best case!)
set_preindent(std::basic_string<FChar> *p)
: pString(p)
{};
std::basic_string<FChar>
*pString;
};
template<class FChar>
std::basic_ostream<FChar> &operator << ( std::basic_ostream<FChar> &out, set_preindent<FChar> const &in )
{
out.flush();
void
*&pStrElm = out.pword(g_PreIndentIndex);
pStrElm = static_cast<void*>(in.pString);
return out;
}
}
#ifdef INDENTSTREAM_IMPL
namespace fmt {
// stream_buf which allows appending prefixes at the beginning of
// any new line.
// It does so by caching a line each, which is transmitted to the
// target stream_buf when full.
template<class FChar>
class TIndentStreamBuf : public std::basic_stringbuf<FChar>
{
public:
typedef std::basic_stringbuf<FChar>
FBase;
TIndentStreamBuf( std::basic_streambuf<FChar> &Target,
uint nIndentLength, FChar const *pIndentStr,
std::basic_ostream<FChar> *pParentStream )
: FBase(std::ios_base::out), m_Target(Target), m_pParentStream(pParentStream),
m_pIndentStr(pIndentStr), m_IndentLength(nIndentLength)
{
if (!g_IndentIndexInitialized) {
g_IndentIndex = std::ios_base::xalloc();
g_PreIndentIndex = std::ios_base::xalloc();
g_IndentIndexInitialized = true;
}
};
~TIndentStreamBuf() throw();
protected:
int sync() throw(); // override
private:
std::basic_streambuf<FChar>
&m_Target;
std::basic_ostream<FChar>
*m_pParentStream;
std::basic_string<FChar>
m_EmptyString;
FChar const
*m_pIndentStr;
int
m_IndentLength;
};
extern char const
*const g_pSpaces;
/// ostream adapter class adding support for indentation to another
/// ostream object. Indendation level is either modified using ind()
/// objects (UseStreamModifiers==true) of by building TIndentOstream
/// cascades (less efficient, UseStreamModifiers==false).
template<class FChar>
class TIndentOstream : public std::basic_ostream<FChar>
{
public:
typedef std::basic_ostream<FChar>
FBase;
/// UseStreamModifiers: if true, use reind(), ind() and unind()
TIndentOstream( TIndentStreamBuf<FChar> &Buf )
: FBase( &Buf )
{};
};
// holds a indent-streambuf and a indent-stream object.
template<class FChar>
class TIndentStream1
{
TIndentStreamBuf<FChar>
m_IndentBuf;
public:
typedef std::basic_ostream<FChar>
FBase;
TIndentOstream<FChar>
stream;
TIndentStream1( FBase &Target, bool UseStreamModifiers = false,
int IndentWidth = 3, FChar const *pIndentStr = g_pSpaces )
: m_IndentBuf( *Target.rdbuf(), IndentWidth, pIndentStr, UseStreamModifiers? &this->stream : 0 ),
stream( m_IndentBuf )
{};
};
typedef TIndentStream1<char>
FIndentStream1;
} // namespace fmt
#endif // INDENTSTREAM_IMPL
#endif // CX_INDENTSTREAM_H
// kate: space-indent on; indent-width 3; indent-mode normal;
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ResonatingWavefunction_HEADER_H
#define ResonatingWavefunction_HEADER_H
#include "CorrelatedWavefunction.h"
#include "ResonatingWalker.h"
/**
This is a linear combination of Jastrow Slater correlated wave functions.
Only the last element of the list is optimized
*/
struct ResonatingWavefunction {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & waveVec
& corr
& ref;
}
public:
vector<CorrelatedWavefunction<Jastrow, Slater>> waveVec;
// these are for convenience in passing to updateWalker, the information is already present in waveVec
vector<Jastrow> corr;
vector<Slater> ref;
bool singleJastrow;
// default constructor
ResonatingWavefunction() {
if (schd.singleJastrow) singleJastrow = true;
else singleJastrow = false;
if (schd.readTransOrbs) {
int norbs = Determinant::norbs;
for (int i = 0; i < schd.numResonants; i++) {
auto wave = CorrelatedWavefunction<Jastrow, Slater>();
string file = "hf" + to_string(i) + ".txt";
MatrixXcd Hforbs = MatrixXcd::Zero(2*norbs, 2*norbs);
readMat(Hforbs, file);
wave.ref.HforbsA = Hforbs;
wave.ref.HforbsB = Hforbs;
waveVec.push_back(wave);
corr.push_back(waveVec[i].corr);
ref.push_back(waveVec[i].ref);
}
if (commrank == 0) {
cout << "Numer of resonants: " << waveVec.size() << endl;
}
}
else {
try {// if a ResonatingWavefunction is present, add a new CorrelatedWavefunction by reading hf.txt, (and possibly Jastrow.txt)
readWave();
if (waveVec.size() > schd.numResonants - 1) {
waveVec.resize(schd.numResonants - 1);
corr.resize(schd.numResonants - 1);
ref.resize(schd.numResonants - 1);
}
waveVec.push_back(CorrelatedWavefunction<Jastrow, Slater>());
corr.push_back(waveVec[waveVec.size() - 1].corr);
ref.push_back(waveVec[waveVec.size() - 1].ref);
if (!schd.restart) {
assert(waveVec.size() == schd.numResonants);
if (commrank == 0) {
cout << "Numer of resonants: " << waveVec.size() << endl;
}
}
}
catch (const boost::archive::archive_exception &e) {
try {// if a CorrelatedWavefunction is present, add it, and add another by reading hf.txt, (and possibly Jastrow.txt)
CorrelatedWavefunction<Jastrow, Slater> wave0;
wave0.readWave();
waveVec.push_back(wave0);
waveVec.push_back(CorrelatedWavefunction<Jastrow, Slater>());
VectorXd v = VectorXd::Zero(waveVec[0].getNumVariables());
waveVec[0].getVariables(v);
waveVec[1].updateVariables(v);
v.resize(0);
corr.push_back(waveVec[0].corr);
ref.push_back(waveVec[0].ref);
corr.push_back(waveVec[1].corr);
ref.push_back(waveVec[1].ref);
assert(waveVec.size() == 2);
if (commrank == 0) cout << "Number of resonants: 2\n";
}
catch (const boost::archive::archive_exception &e) {// if no wave function files are present, read a single CorrelatedWavefunction
waveVec.push_back(CorrelatedWavefunction<Jastrow, Slater>());
corr.push_back(waveVec[0].corr);
ref.push_back(waveVec[0].ref);
assert(waveVec.size() == 1);
if (commrank == 0) cout << "Number of resonants: 1\n";
}
}
}
};
vector<Slater>& getRef() { return ref; }
vector<Jastrow>& getCorr() { return corr; }
// used at the start of each sampling run
void initWalker(ResonatingWalker &walk)
{
walk = ResonatingWalker(corr, ref);
}
// used in deterministic calculations
void initWalker(ResonatingWalker &walk, Determinant &d)
{
walk = ResonatingWalker(corr, ref, d);
}
// used in rdm calculations
double Overlap(const ResonatingWalker &walk) const
{
double overlap = 0.;
if (singleJastrow) {
double jastrowOverlap = corr[0].Overlap(walk.walkerVec[0].d);
double detOverlap = 0.;
for (int i = 0; i < waveVec.size(); i++) {
detOverlap += walk.walkerVec[i].getDetOverlap(ref[i]);
}
overlap = jastrowOverlap * detOverlap;
}
else {
for (int i = 0; i < waveVec.size(); i++) {
overlap += waveVec[i].Overlap(walk.walkerVec[i]);
}
}
return overlap;
}
// used in HamAndOvlp below
double Overlap(const ResonatingWalker &walk, vector<double> &overlaps) const
{
overlaps.resize(waveVec.size(), 0.);
double totalOverlap = 0.;
if (singleJastrow) {
double jastrowOverlap = corr[0].Overlap(walk.walkerVec[0].d);
double detOverlap = 0.;
for (int i = 0; i < waveVec.size(); i++) {
overlaps[i] = walk.walkerVec[i].getDetOverlap(ref[i]);
detOverlap += overlaps[i];
}
totalOverlap = jastrowOverlap * detOverlap;
}
else {
for (int i = 0; i < waveVec.size(); i++) {
overlaps[i] = waveVec[i].Overlap(walk.walkerVec[i]);
totalOverlap += overlaps[i];
}
}
return totalOverlap;
}
// used in rdm calculations
// needs to be adapted for singleJastrow
double getOverlapFactor(int i, int a, const ResonatingWalker& walk, bool doparity) const
{
vector<double> overlaps;
double totalOverlap = Overlap(walk, overlaps);
double numerator = 0.;
for (int n = 0; n < waveVec.size(); n++) {
numerator += waveVec[n].getOverlapFactor(i, a, walk.walkerVec[n], doparity) * overlaps[n];
}
return numerator / totalOverlap;
}
// used in rdm calculations
// needs to be adapted for singleJastrow
double getOverlapFactor(int I, int J, int A, int B, const ResonatingWalker& walk, bool doparity) const
{
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, doparity);
vector<double> overlaps;
double totalOverlap = Overlap(walk, overlaps);
double numerator = 0.;
for (int n = 0; n < waveVec.size(); n++) {
numerator += waveVec[n].getOverlapFactor(I, J, A, B, walk.walkerVec[n], doparity) * overlaps[n];
}
return numerator / totalOverlap;
}
double getOverlapFactor(int i, int a, const ResonatingWalker& walk, vector<double>& overlaps, double& totalOverlap, bool doparity) const
{
double numerator = 0.;
if (singleJastrow) {
Determinant dcopy = walk.walkerVec[0].d;
dcopy.setocc(i, false);
dcopy.setocc(a, true);
double jastrowRatio = walk.walkerVec[0].corrHelper.OverlapRatio(i, a, corr[0], dcopy, walk.walkerVec[0].d);
for (int n = 0; n < waveVec.size(); n++) {
numerator += walk.walkerVec[n].getDetFactor(i, a, ref[n]) * overlaps[n];
}
return jastrowRatio * numerator / walk.detOverlap;
}
else {
for (int n = 0; n < waveVec.size(); n++) {
numerator += waveVec[n].getOverlapFactor(i, a, walk.walkerVec[n], doparity) * overlaps[n];
}
return numerator / totalOverlap;
}
}
// used in HamAndOvlp below
double getOverlapFactor(int I, int J, int A, int B, const ResonatingWalker& walk, vector<double>& overlaps, double& totalOverlap, bool doparity) const
{
if (J == 0 && B == 0) return getOverlapFactor(I, A, walk, overlaps, totalOverlap, doparity);
double numerator = 0.;
if (singleJastrow) {
Determinant dcopy = walk.walkerVec[0].d;
dcopy.setocc(I, false);
dcopy.setocc(J, false);
dcopy.setocc(A, true);
dcopy.setocc(B, true);
double jastrowRatio = walk.walkerVec[0].corrHelper.OverlapRatio(I, J, A, B, corr[0], dcopy, walk.walkerVec[0].d);
for (int n = 0; n < waveVec.size(); n++) {
numerator += walk.walkerVec[n].getDetFactor(I, J, A, B, ref[n]) * overlaps[n];
}
return jastrowRatio * numerator / walk.detOverlap;
}
else {
for (int n = 0; n < waveVec.size(); n++) {
numerator += waveVec[n].getOverlapFactor(I, J, A, B, walk.walkerVec[n], doparity) * overlaps[n];
}
return numerator / totalOverlap;
}
}
// gradient overlap ratio, used during sampling
// just calls OverlapWithGradient on the last wave function
void OverlapWithGradient(const ResonatingWalker &walk,
double &factor,
Eigen::VectorXd &grad) const
{
vector<double> overlaps;
double totalOverlap = Overlap(walk, overlaps);
if (singleJastrow) {
size_t index = 0;
size_t numVars_i = waveVec[0].getNumVariables();
VectorXd grad_0 = VectorXd::Zero(numVars_i);
waveVec[0].OverlapWithGradient(walk.walkerVec[0], factor, grad_0);
grad.segment(index, numVars_i) = grad_0 * overlaps[0] / walk.detOverlap;
index += numVars_i;
for (int i = 1; i < waveVec.size(); i++) {
numVars_i = ref[i].getNumVariables();
VectorBlock<VectorXd> grad_i = grad.segment(index, numVars_i);
walk.walkerVec[i].OverlapWithGradient(ref[i], grad_i);
grad.segment(index, numVars_i) *= overlaps[i] / totalOverlap;
index += numVars_i;
}
}
else {
size_t index = 0;
for (int i = 0; i < waveVec.size(); i++) {
size_t numVars_i = waveVec[i].getNumVariables();
VectorXd grad_i = VectorXd::Zero(numVars_i);
waveVec[i].OverlapWithGradient(walk.walkerVec[i], factor, grad_i);
grad.segment(index, numVars_i) = grad_i * overlaps[i] / totalOverlap;
index += numVars_i;
}
}
}
void printVariables() const
{
for (int i = 0; i < waveVec.size(); i++) {
cout << "Wave " << i << endl << endl;
waveVec[i].printVariables();
}
}
// update after vmc optimization
// updates the wave function helpers as well
void updateVariables(Eigen::VectorXd &v)
{
size_t index = 0;
ref.resize(0);
corr.resize(0);
if (singleJastrow) {
size_t numVars_i = waveVec[0].getNumVariables();
VectorXd v_i = v.segment(index, numVars_i);
waveVec[0].updateVariables(v_i);
ref.push_back(waveVec[0].ref);
corr.push_back(waveVec[0].corr);
index += numVars_i;
for (int i = 1; i < waveVec.size(); i++) {
numVars_i = ref[i].getNumVariables();
VectorBlock<VectorXd> v_i = v.segment(index, numVars_i);
waveVec[i].ref.updateVariables(v_i);
ref.push_back(waveVec[i].ref);
corr.push_back(waveVec[i].corr);
index += numVars_i;
}
}
else {
for (int i = 0; i < waveVec.size(); i++) {
size_t numVars_i = waveVec[i].getNumVariables();
VectorXd v_i = v.segment(index, numVars_i);
waveVec[i].updateVariables(v_i);
ref.push_back(waveVec[i].ref);
corr.push_back(waveVec[i].corr);
index += numVars_i;
}
}
}
void getVariables(Eigen::VectorXd &v) const
{
v = VectorXd::Zero(getNumVariables());
size_t index = 0;
if (singleJastrow) {
size_t numVars_i = waveVec[0].getNumVariables();
VectorXd v_i = VectorXd::Zero(numVars_i);
waveVec[0].getVariables(v_i);
v.segment(index, numVars_i) = v_i;
index += numVars_i;
for (int i = 1; i < waveVec.size(); i++) {
numVars_i = ref[i].getNumVariables();
VectorBlock<VectorXd> v_i = v.segment(index, numVars_i);
waveVec[i].ref.getVariables(v_i);
//v.segment(index, numVars_i) = v_i;
index += numVars_i;
}
}
else {
for (int i = 0; i < waveVec.size(); i++) {
size_t numVars_i = waveVec[i].getNumVariables();
VectorXd v_i = VectorXd::Zero(numVars_i);
waveVec[i].getVariables(v_i);
v.segment(index, numVars_i) = v_i;
index += numVars_i;
}
}
}
long getNumVariables() const
{
long numVariables = 0;
if (singleJastrow) {
numVariables += waveVec[0].getNumVariables();
for (int i = 1; i < waveVec.size(); i++) numVariables += waveVec[i].ref.getNumVariables();
}
else {
for (int i = 0; i < waveVec.size(); i++) numVariables += waveVec[i].getNumVariables();
}
return numVariables;
}
string getfileName() const {
return "ResonatingWavefunction";
}
void writeWave() const
{
if (commrank == 0)
{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
//if (commrank == 0)
//{
char file[5000];
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
sprintf(file, (getfileName()+".bkp").c_str() );
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
//}
#ifndef SERIAL
//boost::mpi::communicator world;
//boost::mpi::broadcast(world, *this, 0);
#endif
}
// calculates local energy and overlap
// used directly during sampling
void HamAndOvlp(const ResonatingWalker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true) const
{
int norbs = Determinant::norbs;
vector<double> overlaps;
ovlp = Overlap(walk, overlaps);
if (schd.debug) {
cout << "overlaps\n";
for (int i = 0; i <overlaps.size(); i++) cout << overlaps[i] << " ";
cout << endl;
}
ham = walk.walkerVec[0].d.Energy(I1, I2, coreE);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.walkerVec[0].d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.walkerVec[0].d, schd.epsilon, schd.screen,
work, false);
//loop over all the screened excitations
if (schd.debug) {
cout << "eloc excitations" << endl;
cout << "phi0 d.energy" << ham << endl;
}
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
double tia = work.HijElement[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double ovlpRatio = getOverlapFactor(I, J, A, B, walk, overlaps, ovlp, false);
//double ovlpRatio = getOverlapFactor(I, J, A, B, walk, dbig, dbigcopy, false);
ham += tia * ovlpRatio;
if (schd.debug) cout << ex1 << " " << ex2 << " tia " << tia << " ovlpRatio " << ovlpRatio << endl;
work.ovlpRatio[i] = ovlpRatio;
}
if (schd.debug) cout << endl;
}
};
#endif
<file_sep>#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <chrono>
#include "interface.h"
#include "CxMemoryStack.h"
#include "Integral2c_Boys.h"
#include "IrBoysFn.h"
#include "LatticeSum.h"
#include "timer.h"
using namespace std;
using namespace std::chrono;
cumulTimer realSumTime, kSumTime, ksumTime1, ksumTime2, ksumKsum;
void testIntegral(Kernel& kernel, int nbas, int natm, vector<double>& Lattice, ct::FMemoryStack2& Mem) ;
template<typename T>
void readFile(vector<T>& vec, string fname) {
streampos begin,end;
ifstream myfile (fname.c_str(), ios::binary);
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
vec.resize(end/sizeof(T));
myfile.seekg (0, ios::beg);
myfile.read (reinterpret_cast<char*>(&vec[0]), end);
myfile.close();
}
int main(int argc, char** argv) {
cout.precision(12);
size_t RequiredMem = 1e9;
ct::FMemoryStack2
Mem(RequiredMem);
vector<int> atm, bas, shls, ao_loc;
vector<double> env, Lattice;
readFile(atm, "atm");
readFile(bas, "bas");
readFile(shls, "shls");
readFile(ao_loc, "aoloc");
readFile(env, "env");
readFile(Lattice, "Lattice");
int n1 = ao_loc[shls[1]] - ao_loc[shls[0]];
int n2 = ao_loc[shls[3]] - ao_loc[shls[2]];
vector<double> integrals(n1*n2, 0.0);
initPeriodic(&shls[0], &ao_loc[0], &atm[0], atm.size()/6,
&bas[0], bas.size()/8/2, &env[0],
&Lattice[0]);
//basis.PrintAligned(cout, 0);
//exit(0);
LatticeSum latsum(&Lattice[0], 4, 13, 100., 8.0, 1.e-14); //latsum.makeKsum();
latsum.printLattice();
cout << "n Basis: "<<basis.getNbas()<<endl;
int sh1 = 0, sh2 = 0;
//cout << basis.BasisShells[sh1].exponents[0]<<endl;
//basis.BasisShells[sh1].exponents[0] = 20.; basis.BasisShells[sh2].exponents[0] = 20.;
int nbas1 = basis.BasisShells[sh1].nCo * (2 * basis.BasisShells[sh1].l + 1);
int nbas2 = basis.BasisShells[sh2].nCo * (2 * basis.BasisShells[sh2].l + 1);
CoulombKernel ckernel;
OverlapKernel okernel;
KineticKernel kkernel;
/*
EvalInt2e2c(&integrals[0], 1, nbas1, &basis.BasisShells[sh1],
&basis.BasisShells[sh2], 1.0, false, &ckernel, latsum, Mem);
*/
/*
for (int i=0; i<nbas1; i++) {
for (int j=0; j<nbas2; j++)
printf("%13.8f ", integrals[i + j * nbas1]);
cout << endl;
}
*/
/*
{
vector<double> integralsNew(n1*n2, 0.0);
LatticeSum latsum(&Lattice[0], 20, 20, 200., 8.0, 1.e-12);
EvalInt2e2c(&integralsNew[0], 1, nbas1, &basis.BasisShells[sh1],
&basis.BasisShells[sh2], 1.0, false, &ckernel, latsum, Mem);
double error = 0.0, maxError = 0.0; int maxInd = 0;
for (int i=0; i<nbas1*nbas2; i++) {
error += pow(integralsNew[i] - integrals[i], 2);
if (maxError < pow(integrals[i] - integralsNew[i], 2)) {
maxError = pow(integrals[i] - integralsNew[i], 2);
maxInd = i;
}
}
cout << "Total error: "<<sqrt(error)<<endl<<"Max error: "<<sqrt(maxError)<<endl;
cout <<maxInd<<" "<< integrals[maxInd]<<" "<<integralsNew[maxInd]<<endl;
cout << maxInd/nbas1<<" "<<maxInd%nbas1<<endl;
}
cout << endl<<endl;
*/
//exit(0);
testIntegral(okernel, basis.getNbas(), atm.size()/6, Lattice, Mem); cout << endl;
testIntegral(kkernel, basis.getNbas(), atm.size()/6, Lattice, Mem); cout << endl;
testIntegral(ckernel, basis.getNbas(), atm.size()/6, Lattice, Mem); cout << endl;
}
void testIntegral(Kernel& kernel, int nbas, int natm, vector<double>& Lattice, ct::FMemoryStack2& Mem) {
vector<double> integrals(nbas*nbas, 0.0);
{
LatticeSum latsum(&Lattice[0], 2, 14, 80., 8.0, 1.e-12);
auto start = high_resolution_clock::now();
if (kernel.getname() == coulombKernel) latsum.makeKsum(basis);
int inbas = 0, jnbas = 0, nbas1, nbas2;
for (int sh1 = 0 ; sh1 <basis.BasisShells.size(); sh1++) {
nbas1 = basis.BasisShells[sh1].nCo * (2 * basis.BasisShells[sh1].l + 1);
jnbas = 0;
for (int sh2 = 0 ; sh2 <=sh1; sh2++) {
nbas2 = basis.BasisShells[sh2].nCo * (2 * basis.BasisShells[sh2].l + 1);
EvalInt2e2c(&integrals[inbas + jnbas * nbas], 1, nbas, &basis.BasisShells[sh1],
&basis.BasisShells[sh2], 1.0, false, &kernel, latsum, Mem);
jnbas += nbas2;
}
inbas += nbas1;
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout <<"Executation time overlap--->: "<< duration.count()/1e6 << endl;
cout <<"spacetime: "<< realSumTime<<endl<<"kspacetime: "<<kSumTime<<" "<<ksumTime1<<" "<<ksumTime2<<" "<<ksumKsum<<endl;
//do it again with larger thresholds
string name = "coul_ref";
if (kernel.getname() == coulombKernel) name = "coul_ref";
if (kernel.getname() == overlapKernel) name = "ovlp_ref";
if (kernel.getname() == kineticKernel) name = "kin_ref";
ofstream file(name.c_str(), ios::binary);
file.write(reinterpret_cast<char*>(&integrals[0]), integrals.size()*sizeof(double));
file.close();
}
{
vector<double> integrals(nbas*nbas, 0.0);
auto start = high_resolution_clock::now();
LatticeSum latsum(&Lattice[0], 5, 15, 200.0, 8.0, 1.e-16);
if (kernel.getname() == coulombKernel) latsum.makeKsum(basis);
int inbas = 0, jnbas = 0, nbas1, nbas2;
for (int sh1 = 0 ; sh1 <basis.BasisShells.size(); sh1++) {
nbas1 = basis.BasisShells[sh1].nCo * (2 * basis.BasisShells[sh1].l + 1);
jnbas = 0;
for (int sh2 = 0 ; sh2 <=sh1; sh2++) {
nbas2 = basis.BasisShells[sh2].nCo * (2 * basis.BasisShells[sh2].l + 1);
EvalInt2e2c(&integrals[inbas + jnbas * nbas], 1, nbas, &basis.BasisShells[sh1],
&basis.BasisShells[sh2], 1.0, false, &kernel, latsum, Mem);
jnbas += nbas2;
}
inbas += nbas1;
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout <<"Executation time: "<< duration.count()/1e6 << endl;
vector<double> intRef;
if (kernel.getname() == coulombKernel) readFile(intRef, "coul_ref");
if (kernel.getname() == overlapKernel) readFile(intRef, "ovlp_ref");
if (kernel.getname() == kineticKernel) readFile(intRef, "kin_ref" );
double error = 0.0, maxError = 0.0; int maxInd = 0;
for (int i=0; i<integrals.size(); i++) {
error += pow(integrals[i] - intRef[i], 2);
if (maxError < pow(integrals[i] - intRef[i], 2)) {
maxError = pow(integrals[i] - intRef[i], 2);
maxInd = i;
}
}
cout << "Total error: "<<sqrt(error)<<endl<<"Max error: "<<sqrt(maxError)<<endl;
cout <<maxInd<<" "<< integrals[maxInd]<<" "<<intRef[maxInd]<<endl;
cout << maxInd/nbas<<" "<<maxInd%nbas<<endl;
}
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "excitationOperators.h"
#include "Determinants.h"
#include "integral.h"
#include "input.h"
Operator::Operator() : cre ({0,0,0,0}), des ({0,0,0,0}) {
n = 0;
nops = 1;
}
//a1^\dag i1
Operator::Operator(short a1, short i1) : cre ({a1}), des ({i1}) {
n = 1;
nops = 1;
}
//a2^\dag i2 a1^\dag i1
Operator::Operator(short a1, short a2, short i1, short i2) :cre ({a2, a1}), des ({i2, i1}) {
n = 2;
nops = 1;
}
ostream& operator << (ostream& os, Operator& o) {
for (int i=0; i<o.n; i++)
os<<o.cre[i]<<" "<<o.des[i]<<" ";
return os;
}
bool Operator::apply(Determinant &dcopy, int op)
{
bool valid = true;
for (int j = 0; j < n; j++)
{
if (dcopy.getocc(cre[j]) == true)
dcopy.setocc(cre[j], false);
else
return false;
if (dcopy.getocc(des[j]) == false)
dcopy.setocc(des[j], true);
else
return false;
}
return valid;
}
//used in active space calcs, excitedOrbs contains excited orbs in dcopy
bool Operator::apply(Determinant &dcopy, const unordered_set<int> &excitedOrbs)
{
if (excitedOrbs.size() == 2) {
for (int j = 0; j < n; j++) {
//if ((cre[j] >= 2*schd.nciAct) || (excitedOrbs.find(des[j]) == excitedOrbs.end())) return false;
//if (cre[j] >= 2*schd.nciAct) return false;
if (dcopy.getocc(des[j]) == true)
dcopy.setocc(des[j], false);
else
return false;
if (dcopy.getocc(cre[j]) == false)
dcopy.setocc(cre[j], true);
else
return false;
}
return true;
}
else if (excitedOrbs.size() == 1) {
//bool valid = false;
bool valid = true;
for (int j = 0; j < n; j++) {
//if (cre[j] >= 2*schd.nciAct) return false;
//if (excitedOrbs.find(des[j]) == excitedOrbs.end()) valid = true;
if (dcopy.getocc(des[j]) == true)
dcopy.setocc(des[j], false);
else
return false;
if (dcopy.getocc(cre[j]) == false)
dcopy.setocc(cre[j], true);
else
return false;
}
return valid;
}
else {
bool valid = true;
for (int j = 0; j < n; j++) {
//if ((des[j] >= 2*schd.nciAct) || (cre[j] >= 2*schd.nciAct)) return false;
if (des[j] >= 2*schd.nciAct) return false;
if (dcopy.getocc(des[j]) == true)
dcopy.setocc(des[j], false);
else
return false;
if (dcopy.getocc(cre[j]) == false)
dcopy.setocc(cre[j], true);
else
return false;
}
return valid;
}
}
//used in Lanczos
void Operator::populateSinglesToOpList(vector<Operator>& oplist, vector<double>& hamElements, double screen) {
int norbs = Determinant::norbs;
for (int i = 0; i < 2 * norbs; i++)
for (int j = 0; j < 2 * norbs; j++)
{
//if (I2hb.Singles(i, j) > schd.epsilon )
if (i % 2 == j % 2 && abs(I2hb.Singles(i,j)) > screen)
{
oplist.push_back(Operator(i, j));
hamElements.push_back(I1(i, j));
}
}
}
//used in Lanczos
void Operator::populateScreenedDoublesToOpList(vector<Operator>& oplist, vector<double>& hamElements, double screen) {
int norbs = Determinant::norbs;
for (int i = 0; i < 2 * norbs; i++)
{
for (int j = i + 1; j < 2 * norbs; j++)
{
int pair = (j / 2) * (j / 2 + 1) / 2 + i / 2;
size_t start = i % 2 == j % 2 ? I2hb.startingIndicesSameSpin[pair] : I2hb.startingIndicesOppositeSpin[pair];
size_t end = i % 2 == j % 2 ? I2hb.startingIndicesSameSpin[pair + 1] : I2hb.startingIndicesOppositeSpin[pair + 1];
float *integrals = i % 2 == j % 2 ? I2hb.sameSpinIntegrals : I2hb.oppositeSpinIntegrals;
short *orbIndices = i % 2 == j % 2 ? I2hb.sameSpinPairs : I2hb.oppositeSpinPairs;
for (size_t index = start; index < end; index++)
{
if (fabs(integrals[index]) < screen)
break;
int a = 2 * orbIndices[2 * index] + i % 2, b = 2 * orbIndices[2 * index + 1] + j % 2;
//cout << i<<" "<<j<<" "<<a<<" "<<b<<" spin orbs "<<integrals[index]<<endl;
oplist.push_back(Operator(i, j, a, b));
hamElements.push_back(integrals[index]);
}
}
}
}
//used in Lanczos
void Operator::populateDoublesToOpList(vector<Operator>& oplist, vector<double>& hamElements) {
int norbs = Determinant::norbs;
for (int i = 0; i < 2 * norbs; i++)
{
for (int j = i + 1; j < 2 * norbs; j++)
{
for (int a = 0; a < 2 * norbs ; a++)
for (int b = a+1; b < 2* norbs; b++) {
oplist.push_back(Operator(i, j, a, b));
hamElements.push_back(0.0);
}
}
}
}
SpinFreeOperator::SpinFreeOperator() {
ops.push_back(Operator());
nops = 1;
}
//a1^\dag i1
SpinFreeOperator::SpinFreeOperator(short a1, short i1) {
ops.push_back(Operator(2*a1, 2*i1));
ops.push_back(Operator(2*a1+1, 2*i1+1));
nops = 2;
}
//a2^\dag i2 a1^\dag i1
SpinFreeOperator::SpinFreeOperator(short a1, short a2, short i1, short i2) {
if (a1 == a2 && a1 == i1 && a1 == i2) {
ops.push_back(Operator(2*a1+1, 2*a2, 2*i1+1, 2*i2));
ops.push_back(Operator(2*a1, 2*a2+1, 2*i1, 2*i2+1));
nops = 2;
}
else {
ops.push_back(Operator(2*a1, 2*a2, 2*i1, 2*i2));
ops.push_back(Operator(2*a1+1, 2*a2, 2*i1+1, 2*i2));
ops.push_back(Operator(2*a1, 2*a2+1, 2*i1, 2*i2+1));
ops.push_back(Operator(2*a1+1, 2*a2+1, 2*i1+1, 2*i2+1));
nops = 4;
}
}
ostream& operator << (ostream& os, const SpinFreeOperator& o) {
for (int i=0; i<o.ops[0].n; i++)
os<<o.ops[0].cre[i]/2<<" "<<o.ops[0].des[i]/2<<" ";
return os;
}
bool SpinFreeOperator::apply(Determinant &dcopy, int op)
{
return ops[op].apply(dcopy, op);
}
void SpinFreeOperator::populateSinglesToOpList(vector<SpinFreeOperator>& oplist, vector<double>& hamElements, double screen) {
int norbs = Determinant::norbs;
for (int i = 0; i < norbs; i++)
for (int j = 0; j < norbs; j++)
{
if (abs(I2hb.Singles(2*i, 2*j)) < screen) continue;
oplist.push_back(SpinFreeOperator(i, j));
hamElements.push_back(I1(2*i, 2*j));
}
}
void SpinFreeOperator::populateScreenedDoublesToOpList(vector<SpinFreeOperator>& oplist, vector<double>& hamElements, double screen) {
int norbs = Determinant::norbs;
for (int i = 0; i < norbs; i++)
{
for (int j = i; j < norbs; j++)
{
int pair = (j) * (j + 1) / 2 + i ;
set<std::pair<int, int> > UniqueSpatialIndices;
vector<double> uniqueHamElements;
if (j != i) { //same spin
size_t start = I2hb.startingIndicesSameSpin[pair] ;
size_t end = I2hb.startingIndicesSameSpin[pair + 1];
float *integrals = I2hb.sameSpinIntegrals ;
short *orbIndices = I2hb.sameSpinPairs ;
for (size_t index = start; index < end; index++)
{
if (fabs(integrals[index]) < screen)
break;
int a = orbIndices[2 * index], b = orbIndices[2 * index + 1];
//cout << i<<" "<<j<<" "<<a<<" "<<b<<" same spin "<<integrals[index]<<endl;
UniqueSpatialIndices.insert(std::pair<int, int>(a,b));
uniqueHamElements.push_back(integrals[index]);
}
}
{ //opposite spin
size_t start = I2hb.startingIndicesOppositeSpin[pair];
size_t end = I2hb.startingIndicesOppositeSpin[pair + 1];
float *integrals = I2hb.oppositeSpinIntegrals;
short *orbIndices = I2hb.oppositeSpinPairs;
for (size_t index = start; index < end; index++)
{
if (fabs(integrals[index]) < screen)
break;
int a = orbIndices[2 * index], b = orbIndices[2 * index + 1];
//cout << i<<" "<<j<<" "<<a<<" "<<b<<" opp spin "<<integrals[index]<<endl;
UniqueSpatialIndices.insert(std::pair<int, int>(a,b));
uniqueHamElements.push_back(integrals[index]);
}
}
int index = 0;
for (auto it = UniqueSpatialIndices.begin();
it != UniqueSpatialIndices.end(); it++) {
int a = it->first, b = it->second;
oplist.push_back(SpinFreeOperator(a, b, i, j));
hamElements.push_back(uniqueHamElements[index]);
index++;
}
}
}
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INPUT_HEADER_H
#define INPUT_HEADER_H
#include <Eigen/Dense>
#include <string>
#include <map>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/map.hpp>
class Correlator;
class Determinant;
enum Method { sgd, amsgrad, ftrl, amsgrad_sgd, sr, linearmethod };
enum HAM {HUBBARD, ABINITIO};
/**
* This stores all the input options
* */
struct schedule {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & restart & deterministic
& tol & correlatorFiles
& fullRestart
& wavefunctionType
& ghfDets
& numResonants
& singleJastrow
& readTransOrbs
& numPermutations
& maxIter
& avgIter
& printLevel
& debug
& decay1
& decay2
& alpha
& beta
& method
& stochasticIter
& burnIter
& _sgdIter
& momentum
& integralSampleSize
& seed
& PTlambda
& epsilon
& screen
& determinantFile
& detsInCAS
& doHessian
& hf
& optimizeOrbs
& optimizeCiCoeffs
& optimizeCps
& optimizeJastrow
& optimizeRBM
& printVars
& printGrad
& printJastrow
& Hamiltonian
& useLastDet
& useLogTime
& ctmc
& nwalk
& tau
& fn_factor
& nGeneration
& excitationLevel
& normSampleThreshold
& numActive
& nciCore
& nciAct
& usingFOIS
& sDiagShift
& cgIter
& stepsize
& ifComplex
& uagp
& ciCeption
& actWidth
& lanczosEpsilon
& overlapCutoff
& diagMethod
& powerShift
& expCorrelator
& numHidden
& maxIterFCIQMC
& nreplicas
& nAttemptsEach
& mainMemoryFac
& spawnMemoryFac
& shiftDamping
& initialShift
& trialInitFCIQMC
& minSpawn
& minPop
& initialPop
& initialNDets
& targetPop
& initiator
& initiatorThresh
& semiStoch
& semiStochInit
& semiStochFile
& uniformExGen
& heatBathExGen
& heatBathUniformSingExGen
& calcEN2
& useTrialFCIQMC
& trialWFEstimator
& importanceSampling
& applyNodeFCIQMC
& releaseNodeFCIQMC
& releaseNodeIter
& diagonalDumping
& partialNodeFactor
& expApprox
& printAnnihilStats
// Options related to SC-NEVPT(s):
& numSCSamples
& printSCNorms
& printSCNormFreq
& readSCNorms
& continueSCNorms
& sampleNEVPT2Energy
& determCCVV
& efficientNEVPT
& efficientNEVPT_2
& exactE_NEVPT
& NEVPT_writeE
& NEVPT_readE
& continueMarkovSCPT
& stochasticIterNorms
& stochasticIterEachSC
& nIterFindInitDets
& printSCEnergies
& nWalkSCEnergies
& SCEnergiesBurnIn
& SCNormsBurnIn
& exactPerturber
& CASEnergy
& perturberOrb1
& perturberOrb2
& fixedResTimeNEVPT_Ene
& fixedResTimeNEVPT_Norm
& resTimeNEVPT_Ene
& resTimeNEVPT_Norm;
}
public:
//General options
bool restart; //option to restart calculation
bool fullRestart; //option to restart calculation
bool deterministic; //Performs a deterministic calculation
int printLevel; // How much stuff to print
bool expCorrelator; // exponential correlator parameters, to enforce positivity
bool debug;
bool ifComplex; // breaks and restores complex conjugation symmetry
bool uagp; // brakes S^2 symmetry in uagp
bool ciCeption; // true, when using ci on top of selectedCI
//input file to define the correlator parts of the wavefunction
std::string wavefunctionType;
std::map<int, std::string> correlatorFiles;
std::string determinantFile;
int numResonants;
bool ghfDets;
double normSampleThreshold;
bool singleJastrow;
bool readTransOrbs;
int numPermutations;
//Used in the stochastic calculation of E and PT evaluation
int stochasticIter; //Number of stochastic steps
int burnIter; //Number of burn in steps
int integralSampleSize; //This specifies the number of determinants to sample out of the o^2v^2 possible determinants after the action of V
size_t seed; // seed for the random number generator
bool detsInCAS;
double PTlambda; // In PT we have to apply H0- E0, here E0 = lambda x <psi0|H0|psi0> + (1 - lambda) x <psi0|H|psi0>
double epsilon; // This is the usual epsilon for the heat bath truncation of integrals
double screen; //This is the screening parameter, any integral below this is ignored
bool doHessian; //This calcules the Hessian and overlap for the linear method
std::string hf;
bool optimizeOrbs;
bool optimizeCiCoeffs;
bool optimizeCps;
bool optimizeJastrow; //used in jrbm
bool optimizeRBM; //used in jrbm
bool printVars;
bool printGrad;
bool printJastrow;
HAM Hamiltonian;
bool useLastDet; //stores last det instead of bestdet
bool useLogTime; //uses log sampled time in CTMC
// SC-NEVPT2(s) options:
bool determCCVV; // In NEVPT2 calculations, calculate the CCVV energy by the exact formula
bool efficientNEVPT; // More efficient sampling in the SC-NEVPT2(s) method
bool efficientNEVPT_2; // More efficient sampling in the SC-NEVPT2(s) method -
// a second approach to this sampling
bool exactE_NEVPT; // Follows the efficient approach to SC-NEVPT2(s), but the energies
// E_l^k are all calculated exactly, without statistical error
bool NEVPT_writeE; // These options are used to exactly calculate the energies of all NEVPT2
bool NEVPT_readE; // perturbers, and print them. The second option can then be
// used to read them back in again (for example if using different
// norms with a different seed) without recalculating them
bool exactPerturber; // Exactly calcualte the energy of a perturber in SC-NEVPT2
double CASEnergy; // User can input a CAS energy, for use in the exactPerturber option
int perturberOrb1; // The excited core and virtual (spin) orbitals which define the perturber,
int perturberOrb2; // in an 'exactPerturber' NEVPT2 calculation
int numSCSamples; // When performing SC-NEVPT2 with the efficientNEVPT_2 algorithm, how
// many samples of 1/(E_0-E_l^k) to take?
bool printSCNorms; // Should we print out the norms of strongly contracted states (in SC-NEVPT2)
int printSCNormFreq; // How often should we print out norms of strongly contracted states (for
// printSCNorms option)
bool readSCNorms; // Do not sample SC norms, but instead read them from previously-printed file
bool continueSCNorms; // Read SC norms from files, and then continue sampling them
bool sampleNEVPT2Energy; // If true, then perform sampling of the NEVPT2 energy
bool continueMarkovSCPT; // In SC-NEVPT2(s), option to store the final det in each sampling of a SC space
int stochasticIterNorms; // Number of stochastic steps when calculating norms of SC states,
// for the efficientNEVPT option
int stochasticIterEachSC; // Number of stochastic steps for each strongly contracted (SC) state,
// for the efficientNEVPT option
int nIterFindInitDets; // The number of iterations used to find initial determinants for
// SC-NEVPT2(s) calculations
bool printSCEnergies; // In SC-NEVPT2(s), print individual samples for the sampling of E_l^k.
int nWalkSCEnergies; // If printSCEnergies = true, then this specifies how many walkers to
// use when sampling E_l^k
int SCEnergiesBurnIn; // For SC-NEVPT2(s), this is the number of iterations used for burn in
//(thrown away), when sampling E_l^k
int SCNormsBurnIn; // For SC-NEVPT2(s), this is the number of iterations used for burn in
//(thrown away), when sampling N_l^k
bool fixedResTimeNEVPT_Ene; // If true, estimate E_l^k in SC-NEVPT2 with a fixed residence time.
// Otherwise, use a fixed iteration count
bool fixedResTimeNEVPT_Norm; // If true, estimate E_l^k in SC-NEVPT2 with a fixed residence time.
// Otherwise, use a fixed iteration count
double resTimeNEVPT_Ene; // For NEVPT2, this is the total residence time for each E_l^k sampling
double resTimeNEVPT_Norm; // For NEVPT2, this is the total residence time for each N_l^k sampling
//Deprecated options for optimizers
//because now we just use the python implementation
double tol;
double stepsize;
double decay1;
double decay2;
double alpha;
double beta;
double momentum;
int maxIter;
int avgIter;
int _sgdIter;
Method method;
double sDiagShift;
int cgIter;
bool ctmc;
/*
bool davidsonPrecondition;
int diisSize;
double gradientFactor;
double mingradientFactor;
double momentum;
double momentumDecay;
double decay;
int learningEpoch;
*/
//options for gfmc
int nwalk;
double tau;
double fn_factor;
int nGeneration;
//options for configuration interaction
int excitationLevel;
int numActive; //number of active spatial orbitals, assumed to be the first in the basis
int nciCore; //number of core spatial orbitals
int nciAct; //number of active spatial orbitals, assumed to be the first in the basis
bool usingFOIS; // Is this is a MRCI/MRPT calculation, sampling the FOIS only
double actWidth; //used in lanczos
double lanczosEpsilon; //used in lanczos
double overlapCutoff; //used in SCCI
std::string diagMethod;
double powerShift;
// Options for FCIQMC
int maxIterFCIQMC;
int nreplicas;
int nAttemptsEach;
double shiftDamping;
double mainMemoryFac;
double spawnMemoryFac;
double initialShift;
double minSpawn;
double minPop;
double initialPop;
int initialNDets;
bool trialInitFCIQMC;
double targetPop;
bool initiator;
double initiatorThresh;
bool semiStoch;
bool semiStochInit;
std::string semiStochFile;
bool uniformExGen;
bool heatBathExGen;
bool heatBathUniformSingExGen;
bool calcEN2;
bool useTrialFCIQMC;
bool trialWFEstimator;
bool importanceSampling;
bool applyNodeFCIQMC;
bool releaseNodeFCIQMC;
int releaseNodeIter;
bool diagonalDumping;
double partialNodeFactor;
bool expApprox;
bool printAnnihilStats;
//options for rbm
int numHidden;
};
/**
* This reads the matrix of MO coefficients from 'hf.txt'
* an alpha and a beta matrix
* params:
* Matrices: matrices of the mo coefficients (nxn for rhf and uhf, 2nx2n for ghf)
* hf string: rhf, uhf or ghf
*/
void readHF(Eigen::MatrixXd& hforbsA, Eigen::MatrixXd& hforbsB, std::string hf);
/**
* This reads the pairing matrix from 'pairMat.txt'
* params:
* Matrix: matrix to be read into
*/
void readPairMat(Eigen::MatrixXd& pairMat);
/**
* Reads the input file which by default is input.dat, but can be anything
* else that is specified on the command line
*
* params:
* input: the input file (unchanged)
* schd : this is the object of class schedule that is populated by the options
* print: How much to print
*/
void readMat(Eigen::MatrixXd& mat, std::string fileName);
void readMat(Eigen::MatrixXcd& mat, std::string fileName);
void readInput(const std::string inputFile, schedule& schd, bool print=true);
/**
* We need information about the correlators because the wavefunction is
* |Psi> = J|D>, where J is the set of jastro factors (correlators)
* The correlator file just contains the tuple of sites that form the correlators
* For instance, for two site correlators the file will contain lines just tell you the
* orbitals , e.g.
* 0 1
* 2 3 ...
*
* params:
* input: the input file (unchanged)
* correlatorSize: the size of the correlator (unchanged)
* correlators : the vector of correlators,
* its usually empty at input and then is filled with Correlators
*/
void readCorrelator(std::string input, int correlatorSize,
std::vector<Correlator>& correlators);
void readCorrelator(const std::pair<int, std::string>& p,
std::vector<Correlator>& correlators);
/**
* We are just reading the set of determinants and their ci coefficients
* for the multi-slater part of the multi-slater Jastrow wavefunction
*/
void readDeterminants(std::string input, std::vector<Determinant>& determinants,
std::vector<double>& ciExpansion);
//reads determinants from Dice, for now assumes rhf dets and converts them into ghf = block_diag(rhf, rhf)
//the reference determinant, assumed to be the first in the file, is read in as a list of integers
//the rest are stored as excitations from ref
//assumes Dice parity included ci coeffs
//the parity vector in the function arguments refers to parity of excitations required when using matrix det lemma
void readDeterminants(std::string input, std::vector<int>& ref, std::vector<int>& open, std::vector<std::array<Eigen::VectorXi, 2>>& ciExcitations,
std::vector<int>& ciParity, std::vector<double>& ciCoeffs);
void readDeterminantsGHF(std::string input, std::vector<int>& ref, std::vector<int>& open, std::vector<std::array<Eigen::VectorXi, 2>>& ciExcitations,
std::vector<int>& ciParity, std::vector<double>& ciCoeffs);
#endif
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <random>
#include <chrono>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Core>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#ifndef SERIAL
//#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
#include <boost/function.hpp>
#include <boost/functional.hpp>
#include <boost/bind.hpp>
#include "evaluateE.h"
#include "Determinants.h"
#include "input.h"
#include "integral.h"
#include "SHCIshm.h"
#include "math.h"
#include "Profile.h"
#include "CIWavefunction.h"
#include "CorrelatedWavefunction.h"
#include "Lanczos.h"
#include "propagate.h"
using namespace Eigen;
using namespace boost;
using namespace std;
int main(int argc, char *argv[])
{
#ifndef SERIAL
boost::mpi::environment env(argc, argv);
boost::mpi::communicator world;
#endif
startofCalc = getTime();
initSHM();
//license();
string inputFile = "input.dat";
if (argc > 1)
inputFile = string(argv[1]);
readInput(inputFile, schd, false);
generator = std::mt19937(schd.seed + commrank);
readIntegralsAndInitializeDeterminantStaticVariables("FCIDUMP");
if (schd.numActive == -1) schd.numActive = Determinant::norbs;
if (schd.wavefunctionType == "cpsslater") {
//initialize wavefunction
CorrelatedWavefunction<CPS, Slater> wave; Walker<CPS, Slater> walk;
wave.readWave(); wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
else if (schd.wavefunctionType == "cpspfaffian") {
//initialize wavefunction
CorrelatedWavefunction<CPS, Pfaffian> wave; Walker<CPS, Pfaffian> walk;
wave.readWave(); wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
else if (schd.wavefunctionType == "cpsagp") {
//initialize wavefunction
CorrelatedWavefunction<CPS, AGP> wave; Walker<CPS, AGP> walk;
wave.readWave(); wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
else if (schd.wavefunctionType == "jastrowslater") {
//initialize wavefunction
CorrelatedWavefunction<Jastrow, Slater> wave; Walker<Jastrow, Slater> walk;
wave.readWave(); wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
else if (schd.wavefunctionType == "jastrowpfaffian") {
//initialize wavefunction
CorrelatedWavefunction<Jastrow, Pfaffian> wave; Walker<Jastrow, Pfaffian> walk;
wave.readWave(); wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
else if (schd.wavefunctionType == "jastrowagp") {
//initialize wavefunction
CorrelatedWavefunction<Jastrow, AGP> wave; Walker<Jastrow, AGP> walk;
wave.readWave(); wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
else if (schd.wavefunctionType == "cicpslater") {
CIWavefunction<CorrelatedWavefunction<CPS, Slater>,
Walker<CPS, Slater>,
SpinFreeOperator> wave;
Walker<CPS, Slater> walk;
wave.readWave(); wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
else if (schd.wavefunctionType == "lanczosjastrowslater") {
Lanczos<CorrelatedWavefunction<Jastrow, Slater>> wave; Walker<Jastrow, Slater> walk;
wave.readWave();
wave.initWalker(walk);
//calculate the energy as a initial guess for shift
double ham, stddev, rk;
getStochasticEnergyContinuousTime(wave, walk, ham, stddev, rk, schd.stochasticIter);
if (commrank == 0) cout << "Energy of VMC wavefunction: "<<ham <<"("<<stddev<<")"<<endl;
//do the GFMC continous time
doGFMCCT(wave, walk, ham);
}
boost::interprocess::shared_memory_object::remove(shciint2.c_str());
boost::interprocess::shared_memory_object::remove(shciint2shm.c_str());
return 0;
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <sys/stat.h>
#include "input.h"
#include "evaluateE.h"
#include "amsgrad.h"
#include "sgd.h"
#include "ftrl.h"
#include "sr.h"
#include <functional>
namespace ph = std::placeholders;
using functor1 = std::function<void (VectorXd&, VectorXd&, double&, double&, double&)>;
using functor2 = std::function<void (VectorXd&, VectorXd&, VectorXd&, DirectMetric&, double&, double&, double&)>;
template<typename Wave, typename Walker>
void runVMC(Wave& wave, Walker& walk) {
if (schd.restart || schd.fullRestart) wave.readWave();
VectorXd vars; wave.getVariables(vars);
getGradientWrapper<Wave, Walker> wrapper(wave, walk, schd.stochasticIter, schd.ctmc);
functor1 getStochasticGradient = std::bind(&getGradientWrapper<Wave, Walker>::getGradient, &wrapper, ph::_1, ph::_2, ph::_3, ph::_4, ph::_5, schd.deterministic);
functor2 getStochasticGradientMetric = std::bind(&getGradientWrapper<Wave, Walker>::getMetric, &wrapper, ph::_1, ph::_2, ph::_3, ph::_4, ph::_5, ph::_6, ph::_7, schd.deterministic);
if (schd.method == amsgrad || schd.method == amsgrad_sgd) {
AMSGrad optimizer(schd.stepsize, schd.decay1, schd.decay2, schd.maxIter, schd.avgIter);
optimizer.optimize(vars, getStochasticGradient, schd.restart);
}
else if (schd.method == sgd) {
SGD optimizer(schd.stepsize, schd.momentum, schd.maxIter);
optimizer.optimize(vars, getStochasticGradient, schd.restart);
}
else if (schd.method == ftrl) {
SGD optimizer(schd.alpha, schd.beta, schd.maxIter);
optimizer.optimize(vars, getStochasticGradient, schd.restart);
}
else if (schd.method == sr) {
/*
mkdir("./Metric", 0777);
mkdir("./T", 0777);
*/
SR optimizer(schd.stepsize, schd.maxIter);
optimizer.optimize(vars, getStochasticGradientMetric, schd.restart);
}
else if (schd.method == linearmethod) {
}
if (schd.printVars && commrank==0) wave.printVariables();
}
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SCCI_HEADER_H
#define SCCI_HEADER_H
#include <vector>
#include <set>
#include <unordered_map>
#include "Determinants.h"
#include "workingArray.h"
#include "excitationOperators.h"
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/array.hpp>
#include <Eigen/Eigenvalues>
#include <utility>
#include <iomanip>
#ifndef SERIAL
#include "mpi.h"
#endif
using namespace std;
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
template<typename Wfn>
class SCCI
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & wave
& coeffs;
}
public:
VectorXd coeffs;
VectorXd moEne;
Wfn wave; //reference wavefunction
workingArray morework;
double ovlp_current;
//intermediates used in direct methods
vector<Eigen::VectorXd> largeHamSamples;
vector<double> largeSampleTimes;
vector<int> largeSampleIndices;
vector<int> nestedIndices;
DiagonalMatrix<double, Dynamic> largeNormInv;
VectorXd largeHamDiag;
double cumulativeTime;
// a list of the excitation classes being considered
vector<int> classesUsed;
// the total number of excitation classes (including the CAS itself, labelled as 0)
static const int NUM_EXCIT_CLASSES = 9;
// the number of coefficients in each excitation class
int numCoeffsPerClass[NUM_EXCIT_CLASSES];
// the cumulative sum of numCoeffsPerClass
int cumNumCoeffs[NUM_EXCIT_CLASSES];
unordered_map<std::array<int,3>, int, boost::hash<std::array<int,3>> > class_1h2p_ind;
unordered_map<std::array<int,3>, int, boost::hash<std::array<int,3>> > class_2h1p_ind;
unordered_map<std::array<int,4>, int, boost::hash<std::array<int,4>> > class_2h2p_ind;
SCCI()
{
wave.readWave();
// Find which excitation classes are being considered. The classes are
// labelled by integers from 0 to 8, and defined in SimpleWalker.h
if (schd.nciCore == 0) {
classesUsed.push_back(0);
classesUsed.push_back(1);
classesUsed.push_back(2);
} else {
classesUsed.push_back(0);
classesUsed.push_back(1);
classesUsed.push_back(2);
classesUsed.push_back(3);
classesUsed.push_back(4);
classesUsed.push_back(5);
classesUsed.push_back(6);
classesUsed.push_back(7);
classesUsed.push_back(8);
}
int numCore = schd.nciCore;
int numVirt = Determinant::norbs - schd.nciCore - schd.nciAct;
// The number of coefficients in each excitation class:
// 0 holes, 0 particles:
numCoeffsPerClass[0] = 1;
// 0 holes, 1 particle:
numCoeffsPerClass[1] = 2*numVirt;
// 0 holes, 2 particles:
numCoeffsPerClass[2] = 2*numVirt * (2*numVirt - 1) / 2;
// 1 hole, 0 particles:
numCoeffsPerClass[3] = 2*numCore;
// 1 hole, 1 particle:
numCoeffsPerClass[4] = (2*numCore) * (2*numVirt);
// 1 hole, 2 particle:
//numCoeffsPerClass[5] = (2*numCore) * (2*numVirt * (2*numVirt - 1) / 2);
// 2 hole, 0 particles:
numCoeffsPerClass[6] = 2*numCore * (2*numCore - 1) / 2;
// 2 hole, 1 particle:
//numCoeffsPerClass[7] = (2*numCore * (2*numCore - 1) / 2) * (2*numVirt);
// Class 5 (2 holes, 1 particle), class 7 (1 holes, 2 particles) and
// class 8 (2 holes, 2 particles) are more complicated. They are set up here:
createClassIndMap(numCoeffsPerClass[5], numCoeffsPerClass[7], numCoeffsPerClass[8]);
cumNumCoeffs[0] = 0;
for (int i = 1; i < 9; i++)
{
// If the previous class (labelled i-1) is being used, add it to the
// cumulative counter.
if (std::find(classesUsed.begin(), classesUsed.end(), i-1) != classesUsed.end()) {
cumNumCoeffs[i] = cumNumCoeffs[i-1] + numCoeffsPerClass[i-1];
}
else {
cumNumCoeffs[i] = cumNumCoeffs[i-1];
}
}
int numCoeffs = 0;
for (int i = 0; i < 9; i++)
{
// The total number of coefficients. Only include a class if that
// class is being used.
if (std::find(classesUsed.begin(), classesUsed.end(), i) != classesUsed.end()) numCoeffs += numCoeffsPerClass[i];
}
// Resize coeffs
coeffs = VectorXd::Zero(numCoeffs);
moEne = VectorXd::Zero(numCoeffs);
//coeffs order: phi0, singly excited (spin orb index), doubly excited (spin orb pair index)
// Use a constant amplitude for each contracted state except
// the CASCI wave function.
double amp = -std::min(0.5, 5.0/std::sqrt(numCoeffs));
coeffs(0) = 1.0;
for (int i=1; i < numCoeffs; i++) {
coeffs(i) = amp;
}
char file[5000];
sprintf(file, "ciCoeffs.txt");
ifstream ofile(file);
if (ofile) {
for (int i = 0; i < coeffs.size(); i++) {
ofile >> coeffs(i);
}
}
//char filem[5000];
//sprintf(filem, "moEne.txt");
//ifstream ofilem(filem);
//if (ofilem) {
// for (int i = 0; i < Determinant::norbs; i++) {
// ofilem >> moEne(i);
// }
//}
//else {
// if (commrank == 0) cout << "moEne.txt not found!\n";
// exit(0);
//}
}
void createClassIndMap(int& numStates_1h2p, int& numStates_2h1p, int& numStates_2h2p) {
// Loop over all combinations of vore and virtual pairs.
// For each, see if the corresponding Hamiltonian element is non-zero.
// If so, give it an index and put that index in a hash table for
// later access. If not, then we do not want to consider the corresponding
// internally contracted state.
int norbs = Determinant::norbs;
int first_virtual = 2*(schd.nciCore + schd.nciAct);
// Class 5 (1 holes, 2 particles)
numStates_1h2p = 0;
for (int i = first_virtual+1; i < 2*norbs; i++) {
for (int j = first_virtual; j < i; j++) {
for (int a = 0; a < 2*schd.nciCore; a++) {
// If this condition is not met, then it is not possible for this
// internally contracted state to be accessed by a single
// application of the Hamiltonian (due to spin conservation).
if (i%2 == a%2 || j%2 == a%2) {
std::array<int,3> inds = {i, j, a};
class_1h2p_ind[inds] = numStates_1h2p;
numStates_1h2p += 1;
}
}
}
}
// Class 7 (2 holes, 1 particles)
numStates_2h1p = 0;
for (int i = first_virtual; i < 2*norbs; i++) {
for (int a = 1; a < 2*schd.nciCore; a++) {
for (int b = 0; b < a; b++) {
// If this condition is not met, then it is not possible for this
// internally contracted state to be accessed by a single
// application of the Hamiltonian (due to spin conservation).
if (i%2 == a%2 || i%2 == b%2) {
std::array<int,3> inds = {i, a, b};
class_2h1p_ind[inds] = numStates_2h1p;
numStates_2h1p += 1;
}
}
}
}
// Class 8 (2 holes, 2 particles)
numStates_2h2p = 0;
for (int i = first_virtual+1; i < 2*norbs; i++) {
for (int j = first_virtual; j < i; j++) {
for (int a = 1; a < 2*schd.nciCore; a++) {
for (int b = 0; b < a; b++) {
morework.setCounterToZero();
generateAllScreenedExcitationsCAS_2h2p(schd.epsilon, morework, i, j, a, b);
if (morework.nExcitations > 0) {
std::array<int,4> inds = {i, j, a, b};
class_2h2p_ind[inds] = numStates_2h2p;
numStates_2h2p += 1;
}
}
}
}
}
}
typename Wfn::ReferenceType& getRef() { return wave.getRef(); }
typename Wfn::CorrType& getCorr() { return wave.getCorr(); }
template<typename Walker>
void initWalker(Walker& walk) {
this->wave.initWalker(walk);
}
template<typename Walker>
void initWalker(Walker& walk, Determinant& d) {
this->wave.initWalker(walk, d);
}
//void initWalker(Walker& walk) {
// this->wave.initWalker(walk);
//}
void getVariables(VectorXd& vars) {
vars = coeffs;
}
void printVariables() {
cout << "ci coeffs\n" << coeffs << endl;
}
void updateVariables(VectorXd& vars) {
coeffs = vars;
}
long getNumVariables() {
return coeffs.size();
}
template<typename Walker>
int coeffsIndex(Walker& walk) {
int norbs = Determinant::norbs;
if (walk.excitation_class == 0) {
// CAS det (0 holes, 0 particles)
return 0;
}
else if (walk.excitation_class == 1) {
// 0 holes, 1 particle
return cumNumCoeffs[1] + *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
}
else if (walk.excitation_class == 2) {
// 0 holes, 2 particles
int a = *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
int b = *(std::next(walk.excitedOrbs.begin())) - 2*schd.nciCore - 2*schd.nciAct;
int A = max(a,b) - 1, B = min(a,b);
return cumNumCoeffs[2] + A*(A+1)/2 + B;
}
else if (walk.excitation_class == 3) {
// 1 hole, 0 particles
return cumNumCoeffs[3] + *walk.excitedHoles.begin();
}
else if (walk.excitation_class == 4) {
// 1 hole, 1 particles
int i = *walk.excitedHoles.begin();
int a = *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
int numVirt = norbs - schd.nciCore - schd.nciAct;
return cumNumCoeffs[4] + 2*numVirt*i + a;
}
else if (walk.excitation_class == 5) {
// 1 hole, 2 particles
int i = *walk.excitedHoles.begin();
//int a = *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
//int b = *(std::next(walk.excitedOrbs.begin())) - 2*schd.nciCore - 2*schd.nciAct;
//int A = max(a,b) - 1, B = min(a,b);
int a = *walk.excitedOrbs.begin();
int b = *(std::next(walk.excitedOrbs.begin()));
int A = max(a,b), B = min(a,b);
// the number of *spatial* virtual orbitals
//int numVirt = norbs - schd.nciCore - schd.nciAct;
// Number of unique pairs of virtual orbitals
//int numVirtPairs = 2*numVirt * (2*numVirt - 1) / 2;
//return cumNumCoeffs[5] + numVirtPairs*i + A*(A+1)/2 + B;
std::array<int,3> inds = {A, B, i};
auto it1 = class_1h2p_ind.find(inds);
if (it1 != class_1h2p_ind.end())
return cumNumCoeffs[5] + it1->second;
else
return -1;
}
else if (walk.excitation_class == 6) {
// 2 hole, 0 particles
int i = *walk.excitedHoles.begin();
int j = *(std::next(walk.excitedHoles.begin()));
int I = max(i,j) - 1, J = min(i,j);
return cumNumCoeffs[6] + I*(I+1)/2 + J;
}
else if (walk.excitation_class == 7) {
// 2 holes, 1 particles
int i = *walk.excitedHoles.begin();
int j = *(std::next(walk.excitedHoles.begin()));
//int I = max(i,j) - 1, J = min(i,j);
int I = max(i,j), J = min(i,j);
//int a = *walk.excitedOrbs.begin() - 2*schd.nciCore - 2*schd.nciAct;
int a = *walk.excitedOrbs.begin();
// the number of *spatial* virtual orbitals
//int numVirt = norbs - schd.nciCore - schd.nciAct;
//return cumNumCoeffs[7] + (2*numVirt)*(I*(I+1)/2 + J) + a;
std::array<int,3> inds = {a, I, J};
auto it1 = class_2h1p_ind.find(inds);
if (it1 != class_2h1p_ind.end())
return cumNumCoeffs[7] + it1->second;
else
return -1;
}
else if (walk.excitation_class == 8) {
// 2 holes, 2 particles
int i = *walk.excitedHoles.begin();
int j = *(std::next(walk.excitedHoles.begin()));
int I = max(i,j), J = min(i,j);
int a = *walk.excitedOrbs.begin();
int b = *(std::next(walk.excitedOrbs.begin()));
int A = max(a,b), B = min(a,b);
std::array<int,4> inds = {A, B, I, J};
auto it1 = class_2h2p_ind.find(inds);
if (it1 != class_2h2p_ind.end())
return cumNumCoeffs[8] + it1->second;
else
return -1;
}
else return -1;
}
template<typename Walker>
double getOverlapFactor(int i, int a, const Walker& walk, bool doparity) const
{
return 1.;
}//not used
template<typename Walker>
double getOverlapFactor(int I, int J, int A, int B, const Walker& walk, bool doparity)
{
int norbs = Determinant::norbs;
auto walkCopy = walk;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(), I*2*norbs + A, J*2*norbs + B, false);
// Is this excitation class being used? If not, then move to the next excitation.
if (std::find(classesUsed.begin(), classesUsed.end(), walkCopy.excitation_class) == classesUsed.end()) {
return 0.0;
}
int coeffsCopyIndex = this->coeffsIndex(walkCopy);
if (coeffsCopyIndex == -1) {
return 0.0;
}
double ovlp0, ham0, ovlp_new;
double ciCoeff = coeffs(coeffsCopyIndex);
morework.setCounterToZero();
if (coeffsCopyIndex == 0) {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, true);
ovlp_new = ciCoeff * ovlp0;
}
else {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, false);
ovlp_new = ciCoeff * ovlp0;
}
return ovlp_new/ovlp_current;
}
template<typename Walker>
void OverlapWithGradient(Walker &walk,
double &factor,
Eigen::VectorXd &grad)
{
if (std::find(classesUsed.begin(), classesUsed.end(), walk.excitation_class) == classesUsed.end()) return;
int norbs = Determinant::norbs;
int coeffsIndex = this->coeffsIndex(walk);
if (coeffsIndex == -1) return;
double ciCoeff = coeffs(coeffsIndex);
//if (abs(ciCoeff) <= 1.e-8) return;
grad[coeffsIndex] += 1 / ciCoeff;
}
template<typename Walker>
bool checkWalkerExcitationClass(Walker &walk)
{
if (std::find(classesUsed.begin(), classesUsed.end(), walk.excitation_class) == classesUsed.end()) return false;
int coeffsIndex = this->coeffsIndex(walk);
if (coeffsIndex == -1)
return false;
else
return true;
}
template<typename Walker>
void HamAndOvlp(Walker &walk,
double &ovlp, double &ham,
workingArray& work, bool fillExcitations=true)
{
if (std::find(classesUsed.begin(), classesUsed.end(), walk.excitation_class) == classesUsed.end()) return;
int coeffsIndex = this->coeffsIndex(walk);
if (coeffsIndex == -1) return;
int norbs = Determinant::norbs;
double parity, tia;
double ciCoeff = coeffs(coeffsIndex);
morework.setCounterToZero();
double ovlp0, ham0;
if (coeffsIndex == 0) {
wave.HamAndOvlp(walk, ovlp0, ham0, morework, true);
ovlp = ciCoeff * ovlp0;
}
else {
wave.HamAndOvlp(walk, ovlp0, ham0, morework, false);
ovlp = ciCoeff * ovlp0;
}
ovlp_current = ovlp;
if (ovlp == 0.) return;
ham = walk.d.Energy(I1, I2, coreE);
double dEne = ham;
// Generate all excitations (after screening)
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen, work, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen, work, false);
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
auto walkCopy = walk;
Determinant dcopy = walkCopy.d;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(),
work.excitation1[i], work.excitation2[i], false);
// Is this excitation class being used? If not, then move to the next excitation.
if (std::find(classesUsed.begin(), classesUsed.end(), walkCopy.excitation_class) == classesUsed.end()) continue;
int coeffsCopyIndex = this->coeffsIndex(walkCopy);
if (coeffsCopyIndex == -1) continue;
parity = 1.;
parity *= dcopy.parity(A/2, I/2, I%2);
if (ex2 != 0) {
dcopy.setocc(I, false);
dcopy.setocc(A, true);
parity *= dcopy.parity(B/2, J/2, J%2);
}
tia = work.HijElement[i];
morework.setCounterToZero();
if (coeffsCopyIndex == 0) {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, true);
ham += parity * tia * ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
}
else {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, false);
ham += parity * tia * ham0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ham0 * coeffs(coeffsCopyIndex) / ovlp;
}
}
}
//ham is a sample of the diagonal element of the Dyall ham
//don't use
template<typename Walker>
void HamAndOvlp(Walker &walk,
double &ovlp, double &locEne, double &ham, double &norm, int coeffsIndex,
workingArray& work, bool fillExcitations=true)
{
int norbs = Determinant::norbs;
double ciCoeff = coeffs(coeffsIndex);
morework.setCounterToZero();
double ovlp0, ham0;
wave.HamAndOvlp(walk, ovlp0, ham0, morework, false);
if (coeffsIndex == 0) ovlp = ciCoeff * ovlp0;
else ovlp = ciCoeff * ham0;
if (ovlp == 0.) return; //maybe not necessary
if (abs(ciCoeff) < 1.e-5) norm = 0;
else norm = 1 / ciCoeff / ciCoeff;
locEne = walk.d.Energy(I1, I2, coreE);
Determinant dAct = walk.d;
//cout << "walker\n" << walk << endl;
//cout << "ovlp " << ovlp << endl;
if (walk.excitedOrbs.size() == 0) {
ham = walk.d.Energy(I1, I2, coreE) / ciCoeff / ciCoeff;
//cout << "ene " << ham << endl;
}
else {
dAct.setocc(*walk.excitedOrbs.begin(), false);
double ene1 = moEne((*walk.excitedOrbs.begin())/2);
if (walk.excitedOrbs.size() == 1) {
ham = (dAct.Energy(I1, I2, coreE) + ene1) / ciCoeff / ciCoeff;
//cout << "ene " << ham << endl;
}
else {
dAct.setocc(*(std::next(walk.excitedOrbs.begin())), false);
double ene2 = moEne((*(std::next(walk.excitedOrbs.begin())))/2);
ham = (dAct.Energy(I1, I2, coreE) + ene1 + ene2) / ciCoeff / ciCoeff;
//cout << "ene " << ham << endl;
}
}
work.setCounterToZero();
generateAllScreenedSingleExcitationsDyallOld(walk.d, dAct, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitationsDyallOld(walk.d, schd.epsilon, schd.screen,
work, false);
//loop over all the screened excitations
//cout << endl << "m dets\n" << endl << endl;
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
double tiaD = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
double isDyall = 0.;
if (work.ovlpRatio[i] != 0.) {
isDyall = 1.;
if (ex2 == 0) tiaD = work.ovlpRatio[i];
work.ovlpRatio[i] = 0.;
}
auto walkCopy = walk;
double parity = 1.;
Determinant dcopy = walkCopy.d;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(),
work.excitation1[i], work.excitation2[i], false);
//cout << walkCopy << endl;
if (walkCopy.excitedOrbs.size() > 2) continue;
parity *= dcopy.parity(A/2, I/2, I%2);
if (ex2 != 0) {
dcopy.setocc(I, false);
dcopy.setocc(A, true);
parity *= dcopy.parity(B/2, J/2, J%2);
}
int coeffsCopyIndex = this->coeffsIndex(walkCopy);
morework.setCounterToZero();
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework);
//cout << "ovlp " << ovlp0 << " ham " << ham0 << " tia " << tia << " parity " << parity << endl;
if (coeffsCopyIndex == 0) {
ham += isDyall * parity * tiaD * ovlp0 / ciCoeff / ovlp;
locEne += parity * tia * ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
}
else {
ham += isDyall * parity * tiaD * ham0 / ciCoeff / ovlp;
locEne += parity * tia * ham0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ham0 * coeffs(coeffsCopyIndex) / ovlp;
}
//cout << endl;
}
//cout << endl << "n ham " << ham << " norm " << norm << endl << endl;
}
//hamSample = <psi^k_l|n>/<psi|n> * <n|H|psi^k'_l'>/<n|psi>, ovlp = <n|psi>
template<typename Walker>
void HamAndOvlp(Walker &walk,
double &ovlp, double &normSample, double &locEne, VectorXd& hamSample, int coeffsIndex,
workingArray& work, bool fillExcitations = true)
{
int norbs = Determinant::norbs;
double ciCoeff = coeffs(coeffsIndex);
morework.setCounterToZero();
double ovlp0, ham0;
if (coeffsIndex == 0) {
wave.HamAndOvlp(walk, ovlp0, ham0, morework, true);
ovlp = ciCoeff * ovlp0;
}
else {
wave.HamAndOvlp(walk, ovlp0, ham0, morework, false);
ovlp = ciCoeff * ovlp0;
}
if (ovlp == 0. || ciCoeff == 0) return; //maybe not necessary
normSample = 1 / ciCoeff / ciCoeff;
locEne = walk.d.Energy(I1, I2, coreE);
double dEne = locEne;
hamSample(coeffsIndex) += locEne / ciCoeff / ciCoeff;
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
if (walk.excitedOrbs.size() == 0) {
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
}
else {
generateAllScreenedDoubleExcitationsFOIS(walk.d, schd.epsilon, schd.screen,
work, false);
}
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
auto walkCopy = walk;
double parity = 1.;
Determinant dcopy = walkCopy.d;
walkCopy.updateWalker(wave.getRef(), wave.getCorr(),
work.excitation1[i], work.excitation2[i], false);
if (walkCopy.excitedOrbs.size() > 2) continue;
parity *= dcopy.parity(A/2, I/2, I%2);
//if (ex2 == 0) {
// ham0 = dEne + walk.energyIntermediates[A%2][A/2] - walk.energyIntermediates[I%2][I/2]
// - (I2.Direct(I/2, A/2) - I2.Exchange(I/2, A/2));
//}
//else {
if (ex2 != 0) {
dcopy.setocc(I, false);
dcopy.setocc(A, true);
parity *= dcopy.parity(B/2, J/2, J%2);
//bool sameSpin = (I%2 == J%2);
//ham0 = dEne + walk.energyIntermediates[A%2][A/2] - walk.energyIntermediates[I%2][I/2]
// + walk.energyIntermediates[B%2][B/2] - walk.energyIntermediates[J%2][J/2]
// + I2.Direct(A/2, B/2) - sameSpin * I2.Exchange(A/2, B/2)
// + I2.Direct(I/2, J/2) - sameSpin * I2.Exchange(I/2, J/2)
// - (I2.Direct(I/2, A/2) - I2.Exchange(I/2, A/2))
// - (I2.Direct(J/2, B/2) - I2.Exchange(J/2, B/2))
// - (I2.Direct(I/2, B/2) - sameSpin * I2.Exchange(I/2, B/2))
// - (I2.Direct(J/2, A/2) - sameSpin * I2.Exchange(J/2, A/2));
}
int coeffsCopyIndex = this->coeffsIndex(walkCopy);
morework.setCounterToZero();
if (coeffsCopyIndex == 0) {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, true);
hamSample(coeffsCopyIndex) += parity * tia * ovlp0 / ciCoeff / ovlp;
locEne += parity * tia * ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
}
else {
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework, false);
hamSample(coeffsCopyIndex) += parity * tia * ham0 / ciCoeff / ovlp;
locEne += parity * tia * ham0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ham0 * coeffs(coeffsCopyIndex) / ovlp;
}
}
}
template<typename Walker>
void LocalEnergy(Walker &walk,
double &ovlp, double& locEne, int coeffsIndex,
workingArray& work, bool fillExcitations = true)
{
int norbs = Determinant::norbs;
double ciCoeff = coeffs(coeffsIndex);
morework.setCounterToZero();
double ovlp0, ham0;
wave.HamAndOvlp(walk, ovlp0, ham0, morework, false);
if (coeffsIndex == 0) ovlp = ciCoeff * ovlp0;
else ovlp = ciCoeff * ham0;
if (ovlp == 0.) return; //maybe not necessary
locEne = walk.d.Energy(I1, I2, coreE);
work.setCounterToZero();
generateAllScreenedSingleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
generateAllScreenedDoubleExcitation(walk.d, schd.epsilon, schd.screen,
work, false);
//loop over all the screened excitations
for (int i=0; i<work.nExcitations; i++) {
double tia = work.HijElement[i];
int ex1 = work.excitation1[i], ex2 = work.excitation2[i];
int I = ex1 / 2 / norbs, A = ex1 - 2 * norbs * I;
int J = ex2 / 2 / norbs, B = ex2 - 2 * norbs * J;
auto walkCopy = walk;
double parity = 1.;
Determinant dcopy = walkCopy.d;
//if (A > I) parity *= -1. * dcopy.parityCI(A/2, I/2, I%2);
//else parity *= dcopy.parityCI(A/2, I/2, I%2);
parity *= dcopy.parity(A/2, I/2, I%2);
dcopy.setocc(I, false);
dcopy.setocc(A, true);
if (ex2 != 0) {
//if (B > J) parity *= -1 * dcopy.parityCI(B/2, J/2, J%2);
//else parity *= dcopy.parityCI(B/2, J/2, J%2);
parity *= dcopy.parity(B/2, J/2, J%2);
}
walkCopy.updateWalker(wave.getRef(), wave.getCorr(),
work.excitation1[i], work.excitation2[i], false);
if (walkCopy.excitedOrbs.size() > 2) continue;
int coeffsCopyIndex = this->coeffsIndex(walkCopy);
morework.setCounterToZero();
wave.HamAndOvlp(walkCopy, ovlp0, ham0, morework);
if (coeffsCopyIndex == 0) {
locEne += parity * tia * ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ovlp0 * coeffs(coeffsCopyIndex) / ovlp;
}
else {
locEne += parity * tia * ham0 * coeffs(coeffsCopyIndex) / ovlp;
work.ovlpRatio[i] = ham0 * coeffs(coeffsCopyIndex) / ovlp;
}
}
}
//simulates hamiltonian multiplication
void HMult(VectorXd& x, VectorXd& hX) {
VectorXd sInvX = largeNormInv * x;
//VectorXd sInvX = x;
VectorXd hSInvX = VectorXd::Zero(x.size());
for (int j = 0; j < largeSampleIndices.size(); j++) {
hSInvX(nestedIndices[largeSampleIndices[j]]) += largeSampleTimes[j] * largeHamSamples[j].dot(sInvX);
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, hSInvX.data(), hSInvX.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
hSInvX /= cumulativeTime;
hX = largeNormInv * hSInvX;
}
void powerMethod(VectorXd& initGuess, VectorXd& eigenVec, double& eigenVal, const int& numPowerIter, const double& threshold) {
VectorXd oldIterVecNormal = initGuess;
VectorXd newIterVec(initGuess.size());
for (int i = 0; i < numPowerIter; i++) {
HMult(oldIterVecNormal, newIterVec);
newIterVec -= schd.powerShift * oldIterVecNormal;
eigenVal = newIterVec.dot(oldIterVecNormal);
VectorXd r = newIterVec - eigenVal * oldIterVecNormal;
if (r.norm() < threshold) {
eigenVec = newIterVec / newIterVec.norm();
eigenVal += schd.powerShift;
if (commrank == 0) cout << "power method converged in " << i << " iterations\n";
return;
}
oldIterVecNormal= newIterVec / newIterVec.norm();
}
eigenVec = oldIterVecNormal;
if (commrank == 0) cout << "power method did not converge in " << numPowerIter << " iterations\n";
}
void davidsonMethod(VectorXd& initGuess, VectorXd& eigenvec, double& eigenval, const int& maxDavidsonIter, const double& threshold) {
initGuess.normalize();
VectorXd vectorToBeAdded = initGuess;
int fullDim = initGuess.size(), subspaceDim = 0;
MatrixXd subspaceBasis = MatrixXd::Zero(1,1), hV = MatrixXd::Zero(1, 1), subspaceHam = MatrixXd::Zero(1, 1);
for (int i = 0; i < maxDavidsonIter; i++) {
//add a vector to the subspace
subspaceDim += 1;
subspaceBasis.conservativeResize(fullDim, subspaceDim);
subspaceBasis.col(subspaceDim - 1) = vectorToBeAdded;
//extend subspaceHam to include added vector
VectorXd hVectorToBeAdded = VectorXd::Zero(fullDim);
HMult(vectorToBeAdded, hVectorToBeAdded);
hV.conservativeResize(fullDim, subspaceDim);
hV.col(subspaceDim - 1) = hVectorToBeAdded;
subspaceHam = subspaceBasis.transpose() * hV;
//diagonalize subspaceHam
EigenSolver<MatrixXd> diag(subspaceHam);
VectorXd::Index minInd;
eigenval = diag.eigenvalues().real().minCoeff(&minInd);
eigenvec = subspaceBasis * diag.eigenvectors().col(minInd).real();
VectorXd hEigenvec = VectorXd::Zero(fullDim);
HMult(eigenvec, hEigenvec);
VectorXd resVec = hEigenvec - eigenval * eigenvec;
//cout << "resVec\n" << resVec << endl;
if (resVec.norm() < threshold) {
if (commrank == 0) cout << "Davidson converged in " << i << " iterations" << endl;
return;
}
else {//calculate vector to be added
//calculate delta
DiagonalMatrix<double, Dynamic> preconditioner;
preconditioner.diagonal() = largeHamDiag - VectorXd::Constant(fullDim, eigenval);
VectorXd delta = preconditioner.inverse() * resVec;
//orthonormalize
VectorXd overlaps = subspaceBasis.transpose() * delta;
vectorToBeAdded = delta - (subspaceBasis * overlaps);
vectorToBeAdded.normalize();
}
}
if (commrank == 0) cout << "Davidson did not converge in " << maxDavidsonIter << " iterations" << endl;
}
template<typename Walker>
double calcEnergy(Walker& walk) {
//sampling
int norbs = Determinant::norbs;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
double ovlp = 0., locEne = 0., ene = 0., correctionFactor = 0.;
int coeffsIndex = this->coeffsIndex(walk);
workingArray work;
HamAndOvlp(walk, ovlp, locEne, work);
int iter = 0, niter = schd.stochasticIter;
double cumdeltaT = 0., cumdeltaT2 = 0., S1 = 0.;
std::vector<double> gradError(niter * commsize, 0.);
std::vector<double> tauError(niter * commsize, 0.);
while (iter < niter) {
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
cumdeltaT2 += deltaT * deltaT;
double ratio = deltaT / cumdeltaT;
ene *= (1 - ratio);
ene += ratio * locEne;
double oldCorrectionFactor = correctionFactor;
correctionFactor *= (1 - ratio);
if (coeffsIndex == 0) {
correctionFactor += ratio;
S1 += deltaT * (1 - oldCorrectionFactor) * (1 - oldCorrectionFactor);
gradError[iter + commrank * niter] = 1.;
}
else {
S1 += deltaT * (oldCorrectionFactor) * (oldCorrectionFactor);
gradError[iter + commrank * niter] = 0.;
}
tauError[iter + commrank * niter] = deltaT;
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
coeffsIndex = this->coeffsIndex(walk);
HamAndOvlp(walk, ovlp, locEne, work);
iter++;
}
ene *= cumdeltaT;
correctionFactor *= cumdeltaT;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT2), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(ene), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(correctionFactor), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(S1), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(gradError[0]), gradError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(tauError[0]), tauError.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
cumulativeTime = cumdeltaT;
ene /= cumdeltaT;
correctionFactor /= cumdeltaT;
S1 /= cumdeltaT;
if (commrank == 0) {
vector<double> b_size, r_x;
block(b_size, r_x, gradError, tauError);
double rk = corrTime(gradError.size(), b_size, r_x);
double n_eff = (cumdeltaT * cumdeltaT) / cumdeltaT2;
double stddev = sqrt(S1 * rk / n_eff);
cout << "energy of sampling wavefunction " << setprecision(12) << ene << endl;
cout << "correctionFactor " << correctionFactor << endl;
cout << "correctionFactor error " << stddev << endl;
cout << "SCCI+Q energy = ene + (1 - correctionFactor) * (ene - ene0)" << endl;
if (schd.printVars) cout << endl << "ci coeffs\n" << coeffs << endl;
}
}
template<typename Walker>
double optimizeWaveCTDirect(Walker& walk) {
//add noise to avoid zero coeffs
if (commrank == 0) {
cout << "starting sampling at " << setprecision(4) << getTime() - startofCalc << endl;
auto random = std::bind(std::uniform_real_distribution<double>(0., 1.e-8), std::ref(generator));
for (int i=0; i < coeffs.size(); i++) {
if (coeffs(i) == 0) coeffs(i) = random();
}
}
#ifndef SERIAL
MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
//sampling
int norbs = Determinant::norbs;
auto random = std::bind(std::uniform_real_distribution<double>(0, 1),
std::ref(generator));
VectorXd ovlpDiag = VectorXd::Zero(coeffs.size());
VectorXd hamDiag = VectorXd::Zero(coeffs.size());
double ovlp = 0., normSample = 0., locEne = 0., ene = 0., ene0 = 0., correctionFactor = 0.;
VectorXd hamSample = VectorXd::Zero(coeffs.size());
vector<Eigen::VectorXf> hamSamples(schd.stochasticIter);
vector<double> sampleTimes; vector<int> sampleIndices;
int coeffsIndex = this->coeffsIndex(walk);
workingArray work;
Walker walkIn = walk;
HamAndOvlp(walk, ovlp, normSample, locEne, hamSample, coeffsIndex, work);
int iter = 0;
double cumdeltaT = 0.;
int printMod = schd.stochasticIter / 5;
while (iter < schd.stochasticIter) {
double cumovlpRatio = 0;
for (int i = 0; i < work.nExcitations; i++) {
cumovlpRatio += abs(work.ovlpRatio[i]);
work.ovlpRatio[i] = cumovlpRatio;
}
double deltaT = 1.0 / (cumovlpRatio);
double nextDetRandom = random() * cumovlpRatio;
int nextDet = std::lower_bound(work.ovlpRatio.begin(), (work.ovlpRatio.begin() + work.nExcitations),
nextDetRandom) - work.ovlpRatio.begin();
cumdeltaT += deltaT;
double ratio = deltaT / cumdeltaT;
ovlpDiag *= (1 - ratio);
ovlpDiag(coeffsIndex) += ratio * normSample;
hamDiag *= (1 - ratio);
hamDiag(coeffsIndex) += ratio * hamSample(coeffsIndex);
ene *= (1 - ratio);
ene += ratio * locEne;
correctionFactor *= (1 - ratio);
ene0 *= (1 - ratio);
if (coeffsIndex == 0) {
correctionFactor += ratio;
ene0 += ratio * hamSample(0);
}
hamSamples[iter] = hamSample.cast<float>();
//hamSamples[iter] = hamSample;
//hamSamples.push_back(hamSample);
sampleTimes.push_back(deltaT);
sampleIndices.push_back(coeffsIndex);
walk.updateWalker(wave.getRef(), wave.getCorr(), work.excitation1[nextDet], work.excitation2[nextDet]);
coeffsIndex = this->coeffsIndex(walk);
hamSample.setZero();
HamAndOvlp(walk, ovlp, normSample, locEne, hamSample, coeffsIndex, work);
iter++;
if (commrank == 0 && iter % printMod == 1) cout << "iter " << iter << " t " << getTime() - startofCalc << endl;
}
ovlpDiag *= cumdeltaT;
hamDiag *= cumdeltaT;
ene *= cumdeltaT;
ene0 *= cumdeltaT;
correctionFactor *= cumdeltaT;
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, ovlpDiag.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, hamDiag.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(cumdeltaT), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(ene), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(ene0), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(correctionFactor), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
cumulativeTime = cumdeltaT;
ovlpDiag /= cumdeltaT;
hamDiag /= cumdeltaT;
ene /= cumdeltaT;
ene0 /= (cumdeltaT * ovlpDiag(0));
correctionFactor /= cumdeltaT;
if (commrank == 0) {
cout << "ref energy " << setprecision(12) << ene0 << endl;
cout << "energy of sampling wavefunction " << ene << endl;
cout << "correctionFactor " << correctionFactor << endl;
cout << "sampling done in " << getTime() - startofCalc << endl;
}
//preparing for diagonalization
std::vector<int> largeNormIndices;
nestedIndices.resize(coeffs.size());
int counter = 0;
for (int i = 0; i < coeffs.size(); i++) {
if (ovlpDiag(i) > schd.overlapCutoff) {
largeNormIndices.push_back(i);
nestedIndices[i] = counter;
counter++;
}
}
Map<VectorXi> largeNormSlice(&largeNormIndices[0], largeNormIndices.size());
VectorXd largeNorms;
igl::slice(ovlpDiag, largeNormSlice, largeNorms);
largeNormInv.resize(coeffs.size());
largeNormInv.diagonal() = largeNorms.cwiseSqrt().cwiseInverse();
//largeNormInv.diagonal() = largeNorms.cwiseInverse();
igl::slice(hamDiag, largeNormSlice, largeHamDiag);
largeHamDiag = (largeNormInv.diagonal().cwiseProduct(largeHamDiag));
largeHamDiag = (largeNormInv.diagonal().cwiseProduct(largeHamDiag));
for (int i = 0; i < sampleIndices.size(); i++) {
if (ovlpDiag(sampleIndices[i]) <= schd.overlapCutoff) {
hamSamples[i].resize(0);
continue;
}
else {
largeSampleTimes.push_back(sampleTimes[i]);
largeSampleIndices.push_back(sampleIndices[i]);
VectorXd largeHamSample;
igl::slice(hamSamples[i], largeNormSlice, largeHamSample);
hamSamples[i].resize(0);
largeHamSamples.push_back(largeHamSample);
}
}
hamSamples.clear(); sampleTimes.clear(); sampleIndices.clear();
hamSamples.shrink_to_fit(); sampleTimes.shrink_to_fit(); sampleIndices.shrink_to_fit();
//diagonaliztion
VectorXd initGuess = VectorXd::Unit(largeNorms.size(), 0);
if (commrank == 0) {
auto random = std::bind(std::uniform_real_distribution<double>(-0.01, 0.01),
std::ref(generator));
for (int i=1; i < initGuess.size(); i++) {
initGuess(i) = random();
}
}
#ifndef SERIAL
MPI_Bcast(initGuess.data(), initGuess.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
double eigenVal;
VectorXd eigenVec;
if (schd.diagMethod == "power") powerMethod(initGuess, eigenVec, eigenVal, max(schd.maxIter, 5000), 1.e-4);
else if (schd.diagMethod == "davidson") davidsonMethod(initGuess, eigenVec, eigenVal, max(schd.maxIter, 1000), 1.e-4);
VectorXd largeCoeffs = largeNormInv * eigenVec;
//VectorXd largeCoeffs = eigenVec;
coeffs.setZero();
for (int i = 0; i < largeNormIndices.size(); i++) coeffs(largeNormIndices[i]) = largeCoeffs(i);
if (commrank == 0) {
cout << "diagonalization in time " << getTime() - startofCalc << endl;
cout << "retained " << largeNorms.size() << " out of " << coeffs.size() << " states" << endl;
cout << "energy eigenvalue " << eigenVal << endl;
cout << "SCCI+Q energy " << eigenVal + (1 - correctionFactor) * (eigenVal - ene0) << endl;
if (schd.printVars) cout << endl << "ci coeffs\n" << coeffs << endl;
}
largeHamSamples.clear(); largeSampleTimes.clear(); largeSampleIndices.clear(), nestedIndices.clear();
largeHamSamples.shrink_to_fit(); largeSampleTimes.shrink_to_fit(); largeSampleIndices.shrink_to_fit(), nestedIndices.shrink_to_fit();
}
template<typename Walker>
double optimizeWaveDeterministic(Walker& walk) {
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
workingArray work;
double overlapTot = 0.;
VectorXd hamSample = VectorXd::Zero(coeffs.size());
MatrixXd ciHam = MatrixXd::Zero(coeffs.size(), coeffs.size());
MatrixXd sMat = MatrixXd::Zero(coeffs.size(), coeffs.size());// + 1.e-6 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//w.printVariables();
for (int i = commrank; i < allDets.size(); i += commsize) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
if (walk.excitedOrbs.size() > 2) continue;
int coeffsIndex = this->coeffsIndex(walk);
double ovlp = 0., normSample = 0., locEne = 0.;
HamAndOvlp(walk, ovlp, normSample, locEne, hamSample, coeffsIndex, work);
//cout << "ham " << ham[0] << " " << ham[1] << " " << ham[2] << endl;
//cout << "ovlp " << ovlp[0] << " " << ovlp[1] << " " << ovlp[2] << endl << endl;
overlapTot += ovlp * ovlp;
ciHam.row(coeffsIndex) += (ovlp * ovlp) * hamSample;
sMat(coeffsIndex, coeffsIndex) += (ovlp * ovlp) * normSample;
hamSample.setZero();
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ciHam.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, sMat.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
double ene0 = 0.;
if (commrank == 0) {
ciHam = ciHam / overlapTot;
sMat = sMat / overlapTot;
ene0 = ciHam(0, 0) / sMat(0,0);
sMat += 1.e-8 * MatrixXd::Identity(coeffs.size(), coeffs.size());
cout << "ciHam\n" << ciHam << endl << endl;
cout << "sMat\n" << sMat << endl << endl;
GeneralizedEigenSolver<MatrixXd> diag(ciHam, sMat);
VectorXd::Index minInd;
double minEne = diag.eigenvalues().real().minCoeff(&minInd);
coeffs = diag.eigenvectors().col(minInd).real();
cout << "energy " << fixed << setprecision(5) << minEne << endl;
cout << "eigenvalues\n" << diag.eigenvalues() << endl;
cout << "ciHam\n" << ciHam << endl;
cout << "sMat\n" << sMat << endl;
cout << "coeffs\n" << coeffs << endl;
}
#ifndef SERIAL
MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
//MPI_Bcast(&(ene0), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
//davidson
overlapTot = 0.;
double ene = 0., correctionFac = 0.;
//w.printVariables();
for (int i = commrank; i < allDets.size(); i += commsize) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
if (walk.excitedOrbs.size() > 2) continue;
int coeffsIndex = this->coeffsIndex(walk);
double ovlp = 0., locEne = 0.;
LocalEnergy(walk, ovlp, locEne, coeffsIndex, work);
//cout << "ham " << ham[0] << " " << ham[1] << " " << ham[2] << endl;
//cout << "ovlp " << ovlp[0] << " " << ovlp[1] << " " << ovlp[2] << endl << endl;
if (coeffsIndex == 0) correctionFac += ovlp * ovlp;
overlapTot += ovlp * ovlp;
ene += (ovlp * ovlp) * locEne;
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(correctionFac), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(ene), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
if (commrank == 0) {
ene = ene / overlapTot;
correctionFac = correctionFac / overlapTot;
cout << "sampled optimized energy " << fixed << setprecision(5) << ene << endl;
cout << "ref energy " << fixed << setprecision(5) << ene0 << endl;
cout << "correctionFac " << correctionFac << endl;
cout << "SCCI+Q energy " << ene + (1 - correctionFac) * (ene - ene0) << endl;
}
//if (commrank == 0) cout << "energies\n" << diag.eigenvalues() << endl;
}
template<typename Walker>
double optimizeWaveDeterministicNesbet(Walker& walk) {
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
workingArray work;
double overlapTot = 0., correctionFactor = 0.;
VectorXd ham = VectorXd::Zero(coeffs.size()), norm = VectorXd::Zero(coeffs.size());
VectorXd eneGrad = VectorXd::Zero(coeffs.size()), waveGrad = VectorXd::Zero(coeffs.size());
double waveEne = 0.;
//w.printVariables();
coeffs /= coeffs(0);
for (int i = commrank; i < allDets.size(); i += commsize) {
wave.initWalker(walk, allDets[i]);
if (schd.debug) {
cout << "walker\n" << walk << endl;
}
if (walk.excitedOrbs.size() > 2) continue;
int coeffsIndex = this->coeffsIndex(walk);
double ovlp = 0., normSample = 0., hamSample = 0., locEne = 0.;
HamAndOvlp(walk, ovlp, locEne, hamSample, normSample, coeffsIndex, work);
//cout << "ham " << ham[0] << " " << ham[1] << " " << ham[2] << endl;
//cout << "ovlp " << ovlp[0] << " " << ovlp[1] << " " << ovlp[2] << endl << endl;
overlapTot += ovlp * ovlp;
ham(coeffsIndex) += (ovlp * ovlp) * hamSample;
norm(coeffsIndex) += (ovlp * ovlp) * normSample;
waveEne += (ovlp * ovlp) * locEne;
eneGrad(coeffsIndex) += (ovlp * ovlp) * locEne / coeffs(coeffsIndex);
waveGrad(coeffsIndex) += (ovlp * ovlp) / coeffs(coeffsIndex);
if (coeffsIndex == 0) correctionFactor += ovlp * ovlp;
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(correctionFactor), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &(waveEne), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ham.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, norm.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, eneGrad.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, waveGrad.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
if (commrank == 0) {
waveEne = waveEne / overlapTot;
//cout << "overlapTot " << overlapTot << endl;
ham = ham / overlapTot;
//cout << "ham\n" << ham << endl;
norm = norm / overlapTot;
// cout << "norm\n" << norm << endl;
VectorXd ene = VectorXd::Zero(coeffs.size());
ene = (ham.array() / norm.array()).matrix();
eneGrad /= overlapTot;
waveGrad /= overlapTot;
eneGrad -= waveEne * waveGrad;
correctionFactor = correctionFactor / overlapTot;
for (int i = 1; i < coeffs.size(); i++) coeffs(i) += eneGrad(i) / correctionFactor / (waveEne - ene(i));
cout << "waveEne " << waveEne << " gradNorm " << eneGrad.norm() << endl;
//cout << "ene\n" << ene << endl;
}
#ifndef SERIAL
MPI_Bcast(coeffs.data(), coeffs.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
//MPI_Bcast(&(ene0), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
}
template<typename Walker>
double optimizeWaveDeterministicDirect(Walker& walk) {
int norbs = Determinant::norbs;
int nalpha = Determinant::nalpha;
int nbeta = Determinant::nbeta;
vector<Determinant> allDets;
generateAllDeterminants(allDets, norbs, nalpha, nbeta);
workingArray work;
double overlapTot = 0.;
VectorXd hamSample = VectorXd::Zero(coeffs.size());
MatrixXd ciHam = MatrixXd::Zero(coeffs.size(), coeffs.size());
vector<Eigen::VectorXd> hamSamples;
vector<double> ovlpSqSamples; vector<int> sampleIndices;
MatrixXd sMat = MatrixXd::Zero(coeffs.size(), coeffs.size());// + 1.e-6 * MatrixXd::Identity(coeffs.size(), coeffs.size());
//w.printVariables();
for (int i = commrank; i < allDets.size(); i += commsize) {
wave.initWalker(walk, allDets[i]);
if (walk.excitedOrbs.size() > 2) continue;
int coeffsIndex = this->coeffsIndex(walk);
double ovlp = 0., normSample = 0., locEne = 0.;
HamAndOvlp(walk, ovlp, normSample, locEne, hamSample, coeffsIndex, work);
//cout << "walker\n" << walk << endl;
//cout << "hamSample\n" << hamSample << endl;
//cout << "ovlp " << ovlp << endl;
ciHam.row(coeffsIndex) += (ovlp * ovlp) * hamSample;
hamSamples.push_back(hamSample);
ovlpSqSamples.push_back(ovlp * ovlp);
sampleIndices.push_back(coeffsIndex);
overlapTot += ovlp * ovlp;
sMat(coeffsIndex, coeffsIndex) += (ovlp * ovlp) * normSample;
hamSample.setZero();
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, &(overlapTot), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, sMat.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, ciHam.data(), coeffs.size() * coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
double ene = 0.;
sMat = sMat / overlapTot;
ciHam = ciHam / overlapTot;
//if (commrank == 0) {
// cout << "sMat\n" << sMat.diagonal() << endl;
// cout << "ciHam\n" << ciHam << endl;
//}
sMat += 1.e-8 * MatrixXd::Identity(coeffs.size(), coeffs.size());
MatrixXd sMatInv = sMat.inverse().cwiseSqrt();
MatrixXd ciHamNorm = sMatInv * ciHam * sMatInv;
EigenSolver<MatrixXd> diag(ciHamNorm);
//cout << "ciHamNorm eigenvalues\n" << diag.eigenvalues() << endl;
VectorXd initGuess = VectorXd::Unit(coeffs.size(), 0);
VectorXd iterVec = 0. * initGuess;
VectorXd iterVecNormal = initGuess;
for (int i = 0; i < 20; i++) {
VectorXd sInvIterVec = sMatInv * iterVecNormal;
for (int j = 0; j < sampleIndices.size(); j ++) {
iterVec(sampleIndices[j]) += ovlpSqSamples[j] * hamSamples[j].dot(sInvIterVec);
}
#ifndef SERIAL
MPI_Allreduce(MPI_IN_PLACE, iterVec.data(), coeffs.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
iterVec /= overlapTot;
VectorXd newIterVec = sMatInv * iterVec;
VectorXd ciHamNormIterVec = ciHamNorm * iterVecNormal;
//cout << "iter " << i << endl;
//cout << "direct iterVec\n" << newIterVec << endl;
//cout << "non-direct iterVec\n" << ciHamNormIterVec << endl;
ene = iterVecNormal.dot(newIterVec);
iterVecNormal= newIterVec / newIterVec.norm();
iterVec.setZero();
}
coeffs = sMatInv * iterVecNormal;
cout << "energy power method " << ene << endl;
//cout << "coeffs\n" << coeffs << endl;
}
string getfileName() const {
return "scci"+wave.getfileName();
}
void writeWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ofstream outfs(file, std::ios::binary);
boost::archive::binary_oarchive save(outfs);
save << *this;
outfs.close();
}
}
void readWave()
{
if (commrank == 0)
{
char file[5000];
sprintf(file, (getfileName()+".bkp").c_str() );
//sprintf (file, "wave.bkp" , schd.prefix[0].c_str() );
//sprintf(file, "lanczoscpswave.bkp");
std::ifstream infs(file, std::ios::binary);
boost::archive::binary_iarchive load(infs);
load >> *this;
infs.close();
}
#ifndef SERIAL
boost::mpi::communicator world;
boost::mpi::broadcast(world, *this, 0);
#endif
}
};
#endif
<file_sep>#pragma once
#include <vector>
#include "CxMemoryStack.h"
class BasisShell;
class BasisSet;
struct LatticeSum {
double RVolume, KVolume, screen;
std::vector<double> RLattice, KLattice;
std::vector<double> Rcoord;
std::vector<double> Rdist;
std::vector<double> Kcoord;
std::vector<double> Kdist;
std::vector<std::vector<long>> KSumIdx;
std::vector<double> KSumVal;
std::vector<double> atomCenters;
double Eta2RhoOvlp, Eta2RhoCoul;
LatticeSum(double* Lattice, int nr, int nk, double _Eta2Rho=100.0, double _Eta2RhoCoul = 8.0, double screen=1.e-12);
void getRelativeCoords(BasisShell *pA, BasisShell *pC,
double& Tx, double& Ty, double& Tz);
void printLattice();
void getIncreasingIndex(size_t *&inx, double Tx, double Ty, double Tz, ct::FMemoryStack& Mem) ;
void makeKsum(BasisSet& basis);
int indexCenter(BasisShell& bas);
};
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
namespace NEVPT2_CCVV {
FTensorDecl TensorDecls[29] = {
/* 0*/{"t", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 1*/{"R", "eecc", "",USAGE_Residual, STORAGE_Memory},
/* 2*/{"f", "cc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 3*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 4*/{"f", "ee", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 5*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 6*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 7*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 8*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 9*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 10*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 11*/{"f", "aa", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 12*/{"E1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 13*/{"E2", "aaaa", "",USAGE_Density, STORAGE_Memory},
/* 14*/{"f", "aa", "",USAGE_Density, STORAGE_Memory},
/* 15*/{"S1", "aa", "",USAGE_Density, STORAGE_Memory},
/* 16*/{"S2", "aa", "",USAGE_Density, STORAGE_Memory},
/* 17*/{"T", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 18*/{"b", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 19*/{"p", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 20*/{"Ap", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 21*/{"P", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 22*/{"AP", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 23*/{"B", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
/* 24*/{"W", "eecc", "",USAGE_Hamiltonian, STORAGE_Memory},
/* 25*/{"delta", "cc", "",USAGE_Density, STORAGE_Memory},
/* 26*/{"delta", "aa", "",USAGE_Density, STORAGE_Memory},
/* 27*/{"delta", "ee", "",USAGE_Density, STORAGE_Memory},
/* 28*/{"t1", "eecc", "",USAGE_Amplitude, STORAGE_Memory},
};
//Number of terms : 16
FEqInfo EqsRes[16] = {
{"CDKL,IK,CDIL", -4.0 , 3, {20,2,19}}, //Ap[CDKL] += -4.0 f[IK] p[CDIL]
{"CDKL,IK,DCIL", 2.0 , 3, {20,2,19}}, //Ap[CDKL] += 2.0 f[IK] p[DCIL]
{"CDKL,IL,CDIK", 2.0 , 3, {20,2,19}}, //Ap[CDKL] += 2.0 f[IL] p[CDIK]
{"CDKL,IL,DCIK", -4.0 , 3, {20,2,19}}, //Ap[CDKL] += -4.0 f[IL] p[DCIK]
{"CDKL,JK,CDLJ", 2.0 , 3, {20,2,19}}, //Ap[CDKL] += 2.0 f[JK] p[CDLJ]
{"CDKL,JK,DCLJ", -4.0 , 3, {20,2,19}}, //Ap[CDKL] += -4.0 f[JK] p[DCLJ]
{"CDKL,JL,CDKJ", -4.0 , 3, {20,2,19}}, //Ap[CDKL] += -4.0 f[JL] p[CDKJ]
{"CDKL,JL,DCKJ", 2.0 , 3, {20,2,19}}, //Ap[CDKL] += 2.0 f[JL] p[DCKJ]
{"CDKL,AC,ADKL", 4.0 , 3, {20,4,19}}, //Ap[CDKL] += 4.0 f[AC] p[ADKL]
{"CDKL,AC,ADLK", -2.0 , 3, {20,4,19}}, //Ap[CDKL] += -2.0 f[AC] p[ADLK]
{"CDKL,AD,ACKL", -2.0 , 3, {20,4,19}}, //Ap[CDKL] += -2.0 f[AD] p[ACKL]
{"CDKL,AD,ACLK", 4.0 , 3, {20,4,19}}, //Ap[CDKL] += 4.0 f[AD] p[ACLK]
{"CDKL,BC,DBKL", -2.0 , 3, {20,4,19}}, //Ap[CDKL] += -2.0 f[BC] p[DBKL]
{"CDKL,BC,DBLK", 4.0 , 3, {20,4,19}}, //Ap[CDKL] += 4.0 f[BC] p[DBLK]
{"CDKL,BD,CBKL", 4.0 , 3, {20,4,19}}, //Ap[CDKL] += 4.0 f[BD] p[CBKL]
{"CDKL,BD,CBLK", -2.0 , 3, {20,4,19}}, //Ap[CDKL] += -2.0 f[BD] p[CBLK]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
FEqInfo Overlap[4] = {
{"CDKL,LM,CDKM", 2.0, 3, {18, 25, 24}},
{"CDKL,LM,DCKM",-1.0, 3, {18, 25, 24}},
{"CDKL,LM,CDMK",-1.0, 3, {18, 25, 24}},
{"CDKL,LM,DCMK", 2.0, 3, {18, 25, 24}},
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "NEVPT2_CCVV";
Out.perturberClass = "CCVV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 29;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 0;
Out.EqsRes = FEqSet(&EqsRes[0], 16, "NEVPT2_CCVV/Res");
Out.Overlap = FEqSet(&Overlap[0], 4, "NEVPT2_CCVV/Overlap");
};
};
<file_sep>/*
Developed by <NAME>
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MultiSlater_HEADER_H
#define MultiSlater_HEADER_H
#include <vector>
#include <set>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <Eigen/Dense>
#include "Determinants.h"
class oneInt;
class twoInt;
class twoIntHeatBathSHM;
class workingArray;
/**
* This is the wavefunction, it is a linear combination of
* slater determinants made of Hforbs
*/
class MultiSlater {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & ref
& open
& ciParity
& ciCoeffs
& numDets
& Hforbs;
}
public:
std::vector<int> ref; // reference determinant electron occupations
std::vector<int> open; // reference determinant hole occupations
std::vector<std::array<Eigen::VectorXi, 2>> ciExcitations; // ci expansion excitations
std::vector<int> ciParity; // parity factors for the ci exctiations
std::vector<double> ciCoeffs; // ci coeffs
size_t numDets; // ci expansion size
Eigen::MatrixXcd Hforbs; // mo coeffs, assuming ghf for now (TODO: crappy notation, not changing now for uniformity)
//read mo coeffs from hf.txt
void initHforbs();
//initialize the ci expansion by reading determinants generated from Dice
void initCiExpansion();
//constructor
MultiSlater();
//variables are ordered as:
//cicoeffs of the reference multidet expansion, followed by hforbs (row major): real and complex parts alternating
void getVariables(Eigen::VectorBlock<Eigen::VectorXd> &v) const;
size_t getNumVariables() const;
void updateVariables(const Eigen::VectorBlock<Eigen::VectorXd> &v);
void printVariables() const;
size_t getNumOfDets() const { return numDets; }
const Eigen::MatrixXcd& getHforbs() const { return Hforbs; }
string getfileName() const { return "MultiSlater"; }
};
#endif
<file_sep>/* Copyright (c) 2012-2020 <NAME>
*
* This file is part of the IR/WMME program
* (See https://sites.psu.edu/knizia/)
*
* IR/WMME is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* IR/WMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ir/wmme (LICENSE). If not, see http://www.gnu.org/licenses/
*/
/* IrAmrr.h v20181231 EST [storm, Gerald Knizia] */
#ifndef IR_RR_H
#define IR_RR_H
// IrAmrr -- Angular Momentum Recurrence Relations.
//
// This is generated code. Changes made here will be lost!
#include <stddef.h> // for size_t
#include "CxDefs.h" // for assert and RESTRICT
#ifndef IR_RP
#define IR_RP RESTRICT // restricted pointer
#endif
namespace ir {
unsigned const
MaxLa = 6,
MaxLc = 6;
// number of cartesian components with angular momentum <= l
inline size_t nCartX(int l) { return static_cast<size_t>((l+1)*(l+2)*(l+3)/6); }
// number of cartesians components with angular momentum == l
inline size_t nCartY(int l) { return static_cast<size_t>((l+1)*(l+2)/2); }
// number of solid harmonic components with angular momentum <= l
inline size_t nSlmX(int l) { return static_cast<size_t>((l+1)*(l+1)); }
// number of solid harmonic components with angular momentum == l
inline size_t nSlmY(int l) { return static_cast<size_t>(2*l+1); }
// index of solid harmonic component l,c (c = 0 .. 2*l+1) within 0..nSlmX(l).
inline size_t iSlcX(int l, unsigned c) { return static_cast<size_t>(l*l + c); }
typedef unsigned short
cart_vec_t,
cart_index_t;
void OsrrA(double *IR_RP pOut, double *IR_RP pGm, unsigned lab, double PmAx, double PmAy, double PmAz, double PmQx, double PmQy, double PmQz, double rho, double InvEta);
void ShTrN(double *IR_RP pOut, double const *IR_RP pIn, size_t N, unsigned l);
void OsrrB_3c_shc(double *IR_RP pOut, double const *IR_RP pIn, double *IR_RP pMem, int la, unsigned lab, unsigned lc, double fPmQx, double fPmQy, double fPmQz, double InvEtaABC, double riz);
void OsrrB_3c_cac(double *IR_RP pOut, double const *IR_RP pIn, double *IR_RP pMem, int la, unsigned lab, unsigned lc, double fPmQx, double fPmQy, double fPmQz, double InvEtaABC, double riz);
extern cart_vec_t const ix2v[680];
extern cart_index_t const iv2x[3151];
void ShTrN_Indirect(double *IR_RP pOut, size_t so, double const *IR_RP pIn, size_t si, unsigned la, cart_index_t const *ii, size_t N, size_t M);
void ShTrA_XY(double *IR_RP pOut, double const *IR_RP pIn, unsigned la, unsigned lab, size_t M);
void ShTrA_XfY(double *IR_RP pOut, double const *IR_RP pIn, unsigned la, unsigned lab, size_t M);
void ShTrA_YY(double *IR_RP pOut, double const *IR_RP pIn, unsigned la, unsigned lab, size_t M);
void OsrrC(double *IR_RP pOut, size_t sa, size_t sb, double const *IR_RP p0Z, double AmBx, double AmBy, double AmBz, unsigned lb, size_t nCount);
void ShTrN_TN(double *IR_RP pOut, double const *IR_RP pIn, size_t N, unsigned l);
void AmrrDerivA1(double *IR_RP pOut, double const *IR_RP p0Z, double const *IR_RP p2Z, unsigned lab, unsigned la, size_t nCount);
void AmrrDerivA2(double *IR_RP pOut, double const *IR_RP p0Z, double const *IR_RP p2Z, double const *IR_RP p4Z, unsigned lab, unsigned la, size_t nCount);
void AmrrDerivA0L(double *IR_RP pOut, double const *IR_RP p2Z, double const *IR_RP p4Z, unsigned lab, unsigned la, size_t nCount);
void OsrrC_dB1(double *IR_RP pOut, size_t sa, size_t sb, size_t sd, double const *IR_RP p0Z, double const *IR_RP p2Z, double AmBx, double AmBy, double AmBz, unsigned lb, size_t nCount);
void OsrrC_dB2(double *IR_RP pOut, size_t sa, size_t sb, size_t sd, double const *IR_RP p0Z, double const *IR_RP p2Z, double const *IR_RP p4Z, double AmBx, double AmBy, double AmBz, unsigned lb, size_t nCount);
void OsrrC_dB0L(double *IR_RP pOut, size_t sa, size_t sb, double const *IR_RP p2Z, double const *IR_RP p4Z, double AmBx, double AmBy, double AmBz, unsigned lb, size_t nCount);
void CaTrC(double *IR_RP pOut, double const *IR_RP pIn, size_t N, unsigned l);
void CaTrA(double *IR_RP pOut, double const *IR_RP pIn, size_t si, unsigned l);
void OsrrRx(double *IR_RP pOut, double const *IR_RP pIn, size_t si, double AmBx, double AmBy, double AmBz, unsigned lb);
void ShTrN_NN(double *IR_RP pOut, double const *IR_RP pIn, size_t N, unsigned l);
void ShellMdrr(double *IR_RP pOut, double const *IR_RP pIn, double Rx, double Ry, double Rz, unsigned lab);
void ShellLaplace(double *IR_RP pOut, double const *IR_RP pIn, unsigned LaplaceOrder, unsigned lab);
extern unsigned char iCartPow[84][3];
}
#endif // IR_RR_H
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef _CX_TYPES_H
#define _CX_TYPES_H
#ifndef _for_each
#define _for_each(it,con) for ( (it) = (con).begin(); (it) != (con).end(); ++(it) )
#endif
#define __STDC_CONSTANT_MACROS
// ^- ask stdint.h to include fixed-size literal macros (e.g., UINT64_C).
#include <boost/cstdint.hpp>
using boost::uint64_t;
using boost::uint32_t;
using boost::uint16_t;
using boost::uint8_t;
using boost::int64_t;
using boost::int32_t;
using boost::int16_t;
using boost::int8_t;
using std::size_t;
using std::ptrdiff_t;
typedef unsigned int
uint;
typedef unsigned char
uchar;
typedef unsigned int
uint;
#include "CxDefs.h"
#define RESTRICT AIC_RP
namespace ct {
struct FIntrusivePtrDest;
}
void intrusive_ptr_add_ref( ct::FIntrusivePtrDest const *pExpr );
void intrusive_ptr_release( ct::FIntrusivePtrDest const *pExpr );
namespace ct {
/// A base class for reference counted objects. Classes derived from this can
/// be used as target for boost::intrusive_ptr.
struct FIntrusivePtrDest
{
FIntrusivePtrDest() : m_RefCount(0) {};
inline virtual ~FIntrusivePtrDest() = 0;
mutable int m_RefCount;
friend void ::intrusive_ptr_add_ref( FIntrusivePtrDest const *Expr );
friend void ::intrusive_ptr_release( FIntrusivePtrDest const *Expr );
};
inline FIntrusivePtrDest::~FIntrusivePtrDest()
{
};
} // namespace ct
inline void intrusive_ptr_add_ref( ct::FIntrusivePtrDest const *pExpr ) {
pExpr->m_RefCount += 1;
}
inline void intrusive_ptr_release( ct::FIntrusivePtrDest const *pExpr ) {
assert( pExpr->m_RefCount > 0 );
pExpr->m_RefCount -= 1;
if ( pExpr->m_RefCount == 0 )
delete pExpr;
}
#include <boost/intrusive_ptr.hpp>
// ^- that's for gcc 4.7., which otherwise refuses to instantiate intrusive_ptr,
// since due to changes in two-phase name lookup, it cannot anymore instantiate *any*
// templates depending on (non-argument dependent) code which was declared only
// later in the translation unit.
// Yes, you heard right: In the case of intrusive_ptr, it means that all
// reference counting functions must be declared *BEFORE* intrusive_ptr.hpp
// is #included *ANYWHERE*. Sounds like a fun can of worms. For the
// beginning: don't include #intrusive_ptr.hpp directly, that might break
// random code.
#endif // _CX_TYPES_H
// kate: space-indent on; tab-indent on; backspace-indent on; tab-width 4; indent-width 4; mixedindent off; indent-mode normal;
<file_sep>#pragma once
#include "CxMemoryStack.h"
enum KernelID {coulombKernel, kineticKernel, overlapKernel};
struct Kernel {
virtual void getValueRSpace(double* pFmT, double T, int L, double factor, double rho, double eta, ct::FMemoryStack& Mem) =0;
virtual inline double getValueKSpace(double T, double factor, double eta)=0;
virtual int getname() = 0;
};
struct CoulombKernel : public Kernel {
int name;
CoulombKernel() {name = coulombKernel;}
void getValueRSpace(double* pFmT, double T, int L, double factor, double rho, double eta, ct::FMemoryStack& Mem);
inline double getValueKSpace(double T, double factor, double eta);
int getname() {return name;}
};
struct KineticKernel : public Kernel {
int name ;
KineticKernel() {name = kineticKernel ;}
void getValueRSpace(double* pFmT, double T, int L, double factor, double rho, double eta, ct::FMemoryStack& Mem);
inline double getValueKSpace(double T, double factor, double eta);
int getname() {return name;}
};
struct OverlapKernel : public Kernel {
int name;
OverlapKernel() {name = overlapKernel;}
void getValueRSpace(double* pFmT, double T, int L, double factor, double rho, double eta, ct::FMemoryStack& Mem);
inline double getValueKSpace(double T, double factor, double eta);
int getname() {return name;}
};
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DIIS_HEADER_H
#define DIIS_HEADER_H
#include <Eigen/Dense>
class DIIS {
Eigen::MatrixXd prevVectors;
Eigen::MatrixXd errorVectors;
Eigen::MatrixXd diisMatrix;
int maxDim;
int vectorDim;
int iter;
public:
DIIS() {};
DIIS(int pmaxDim, int pvectorDim);
void init(int pmaxDim, int pvectorDim);
void update(Eigen::VectorXd& newVector, Eigen::VectorXd& grad);
};
#endif
<file_sep>namespace NEVPT2_CCAV {
FTensorDecl TensorDecls[19] = {
/* 0*/{"R" , "ccae" , "", USAGE_Residual },
/* 1*/{"t" , "ccae" , "", USAGE_Amplitude },
/* 2*/{"T" , "ccae" , "", USAGE_Amplitude },
/* 3*/{"b" , "ccae" , "", USAGE_Amplitude },
/* 4*/{"B" , "ccae" , "", USAGE_Amplitude },
/* 5*/{"p" , "ccae" , "", USAGE_Amplitude },
/* 6*/{"Ap" , "ccae" , "", USAGE_Amplitude },
/* 7*/{"P" , "ccae" , "", USAGE_Amplitude },
/* 8*/{"AP" , "ccae" , "", USAGE_Amplitude },
/* 9*/{"W" , "ccae" , "", USAGE_Hamiltonian },
/* 10*/{"f" , "aa" , "", USAGE_Hamiltonian },
/* 11*/{"W" , "aaaa" , "", USAGE_Hamiltonian },
/* 12*/{"f" , "cc" , "", USAGE_Hamiltonian },
/* 13*/{"f" , "ee" , "", USAGE_Hamiltonian },
/* 14*/{"delta" , "aa" , "", USAGE_Density },
/* 15*/{"E1" , "aa" , "", USAGE_Density },
/* 16*/{"E2" , "aaaa" , "", USAGE_Density },
/* 17*/{"S1" , "AA" , "", USAGE_Density },
/* 18*/{"S2" , "aa" , "", USAGE_Density },
};
FEqInfo EqsRes[22] = {
{"abcd,ce,abed", 4.0, 3, { 6,10, 5}}, // 4.0 Ap[abcd] f[ce] p[abed]
{"abcd,ce,baed", -2.0, 3, { 6,10, 5}}, // -2.0 Ap[abcd] f[ce] p[baed]
{"abcd,ae,becd", 2.0, 3, { 6,12, 5}}, // 2.0 Ap[abcd] f[ae] p[becd]
{"abcd,ae,ebcd", -4.0, 3, { 6,12, 5}}, // -4.0 Ap[abcd] f[ae] p[ebcd]
{"abcd,be,aecd", -4.0, 3, { 6,12, 5}}, // -4.0 Ap[abcd] f[be] p[aecd]
{"abcd,be,eacd", 2.0, 3, { 6,12, 5}}, // 2.0 Ap[abcd] f[be] p[eacd]
{"abcd,de,abce", 4.0, 3, { 6,13, 5}}, // 4.0 Ap[abcd] f[de] p[abce]
{"abcd,de,bace", -2.0, 3, { 6,13, 5}}, // -2.0 Ap[abcd] f[de] p[bace]
{"abcd,ef,abed,fc", -2.0, 4, { 6,10, 5,15}}, // -2.0 Ap[abcd] f[ef] p[abed] E1[fc]
{"abcd,ef,baed,fc", 1.0, 4, { 6,10, 5,15}}, // 1.0 Ap[abcd] f[ef] p[baed] E1[fc]
{"abcd,cefg,abed,gf", -2.0, 4, { 6,11, 5,15}}, // -2.0 Ap[abcd] W[cefg] p[abed] E1[gf]
{"abcd,cefg,abfd,eg", 4.0, 4, { 6,11, 5,15}}, // 4.0 Ap[abcd] W[cefg] p[abfd] E1[eg]
{"abcd,cefg,baed,gf", 1.0, 4, { 6,11, 5,15}}, // 1.0 Ap[abcd] W[cefg] p[baed] E1[gf]
{"abcd,cefg,bafd,eg", -2.0, 4, { 6,11, 5,15}}, // -2.0 Ap[abcd] W[cefg] p[bafd] E1[eg]
{"abcd,ae,befd,fc", -1.0, 4, { 6,12, 5,15}}, // -1.0 Ap[abcd] f[ae] p[befd] E1[fc]
{"abcd,ae,ebfd,fc", 2.0, 4, { 6,12, 5,15}}, // 2.0 Ap[abcd] f[ae] p[ebfd] E1[fc]
{"abcd,be,aefd,fc", 2.0, 4, { 6,12, 5,15}}, // 2.0 Ap[abcd] f[be] p[aefd] E1[fc]
{"abcd,be,eafd,fc", -1.0, 4, { 6,12, 5,15}}, // -1.0 Ap[abcd] f[be] p[eafd] E1[fc]
{"abcd,de,abfe,fc", -2.0, 4, { 6,13, 5,15}}, // -2.0 Ap[abcd] f[de] p[abfe] E1[fc]
{"abcd,de,bafe,fc", 1.0, 4, { 6,13, 5,15}}, // 1.0 Ap[abcd] f[de] p[bafe] E1[fc]
{"abcd,efgh,abed,fghc", -2.0, 4, { 6,11, 5,16}}, // -2.0 Ap[abcd] W[efgh] p[abed] E2[fghc]
{"abcd,efgh,baed,fghc", 1.0, 4, { 6,11, 5,16}}, // 1.0 Ap[abcd] W[efgh] p[baed] E2[fghc]
};
FEqInfo Overlap[4] = {
{"IJPA,RP,IJRA", 4.0, 3, { 3,14, 9}}, // 4.0 b[IJPA] delta[RP] W[IJRA]
{"IJPA,RP,IJRA", -2.0, 3, { 3,15, 9}}, // -2.0 b[IJPA] E1[RP] W[IJRA]
{"IJPA,RP,JIRA", -2.0, 3, { 3,14, 9}}, // -2.0 b[IJPA] delta[RP] W[JIRA]
{"IJPA,RP,JIRA", 1.0, 3, { 3,15, 9}}, // 1.0 b[IJPA] E1[RP] W[JIRA]
};
int f(int i) {
return 2*i;
}
FDomainDecl DomainDecls[1] = {
{"A", "a", f}
};
static void GetMethodInfo(FMethodInfo &Out) {
Out = FMethodInfo();
Out.pName = "NEVPT2_CCAV";
Out.perturberClass = "CCAV";
Out.pSpinClass = "restricted";
Out.pTensorDecls = &TensorDecls[0];
Out.nTensorDecls = 19;
Out.pDomainDecls = &DomainDecls[0];
Out.nDomainDecls = 1;
Out.EqsRes = FEqSet(&EqsRes[0], 22, "NEVPT2_CCAV/Res");
Out.Overlap = FEqSet(&Overlap[0], 4, "NEVPT2_CCAV/Overlap");
};
};
<file_sep>/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#ifndef _CT8K_DIIS_H
#define _CT8K_DIIS_H
#include <cstddef>
#include "CxTypes.h"
#include "CxStorageDevice.h"
#include "CxFixedSizeArray.h"
namespace ct {
// General DIIS support. These ones are ported and extended from
// f12_shared.f90's PerformDiis function.
//
// Unfortunatelly, due to the requirement of supporting multiple
// memory blocks in DIIS, much of the simplicity of that implementation
// is lost :(.
static const uint
// maximum allowed number of iterative subspace vectors
nMaxDiisCapacity = 31;
struct
FDiisTarget;
struct FDiisOptions
{
uint
// maximum DIIS dimension allowed
nMaxDim;
double
// residual threshold for inclusion of a vector in the DIIS state.
ResidualThresh;
// note: can be implicitly constructed from an uint!
FDiisOptions( uint nMaxDim_ = 6, double ResidualThresh_ = 1e6 )
: nMaxDim( nMaxDim_ ), ResidualThresh( ResidualThresh_ )
{};
};
// FDiisState contains the properties and state of an DIIS object.
//
// The standard use of this object looks like this:
//
// double
// *T, *R;
// FStorageBlock
// DiisBlock(StorageDevice, DiisRecord);
// FDiisState
// Diis( DiisBlock, MemoryStack, nMaxDiis );
// for ( uint nIt = 0; nIt < nMaxIterations; ++nIt ){
// // calculate R(T) somehow.
// [...]
//
// Diis( T, nSizeT, R, nSizeR );
// if ( Diis.fLastResidual() < ThrVar ){
// Converged = True;
// break;
// }
// }
//
// More general usage scenarios can be realized by using the
// FDiisTarget class and explicitly giving storage records for
// the results.
class FDiisState
{
public:
typedef double FScalar;
// Memory: used for intermediates during the PerformDiis function.
// before and after, no memory is left on the stack.
// Storage: If provided, subspace data is stored here. If not,
// subspace data is stored in memory.
explicit FDiisState( FMemoryStack &Memory,
FDiisOptions const &Options = FDiisOptions(),
FStorageBlock const &Storage = FStorageBlock() );
// discards previous iteration vectors, but does not clear records.
void Reset();
void PerformDiis( FDiisTarget &TR, FScalar W1 = 1.0 );
void operator () ( FDiisTarget &TR ){ PerformDiis(TR); }
// convenience function to run DIIS on a block set in memory.
// pOth: set of amplitudes to extrapolate, but not to include in the
// DIIS system itself.
void operator () ( double *pAmp, size_t nAmpSize, double *pRes,
size_t nResSize = static_cast<size_t>(-1), double *pOth = 0, size_t nOthSize = 0 );
double fLastResidual() const { return m_LastResidualNormSq; }
double fLastCoeff() const { return m_LastAmplitudeCoeff; }
uint nLastDim() const;
uint nNextVec() const { return m_iNext; }
uint nMaxDim() const { return m_Options.nMaxDim; };
private:
FDiisOptions
m_Options;
FStorageBlock
// where we store our intermediate data
m_Storage;
FMemoryStack
// from where we get temporary space
&m_Memory;
uint
// 0xffff: no vector in this slot. Otherwise: number of iterations
// the vector in this slot has already been inside the DIIS system.
m_iVectorAge[nMaxDiisCapacity],
m_iNext; // next vector to be overwritten. nDim+1 if nDim < nMaxDim.
FStreamSize
// lengths of the amplitude and residual vectors, respectively.
m_nAmplitudeLength,
m_nResidualLength;
// find vectors which are not considered too bad for extrapolation purposes.
void FindUsefulVectors(uint *iUsedVecs, uint &nDimUsed, double &fBaseScale, uint iThis);
typedef TArrayFix<double, (nMaxDiisCapacity+1)*(nMaxDiisCapacity+1)>
FDiisMatrixBase;
struct FDiisMatrix : public FDiisMatrixBase
{
FDiisMatrix( uint nRows, uint nCols )
: m_nRows(nRows), m_nCols(nCols)
{
resize( m_nRows * m_nCols );
this->FDiisMatrixBase::operator = ( 0.0 );
}
inline uint nStride() { return m_nRows; };
inline double& operator() ( uint nRow, uint nCol ){ return (*this)[m_nRows*nCol + nRow]; }
private:
uint
m_nRows, m_nCols;
};
FDiisMatrix
// storage for a nMaxDim x nMaxDim matrix. Always stride nStride, but
// not always everything used. Keeps the resident parts of the DIIS
// system: <res[i], res[j]>. Indexed by storage slot indices.
m_ErrorMatrix;
typedef TArrayFix<double, (nMaxDiisCapacity+1)>
FDiisVector;
FDiisVector
m_Weights;
static const FStreamSize
iNotPresent = static_cast<FStreamSize>( -1 );
FStorageDevice::FRecord AmplitudeRecord( uint iVec );
FStorageDevice::FRecord ResidualRecord( uint iVec );
private:
// the following variables are kept for informative/displaying purposes
double
// dot(R,R) of last residual vector fed into this state.
m_LastResidualNormSq,
// coefficient the actual new vector got in the last DIIS step
m_LastAmplitudeCoeff;
// this one is used if the DIIS state is constructed in thin
// air (so to say).
FStorageDeviceMemoryBuf
m_StorageDeviceToUseIfNoneProvided;
private:
FDiisState( FDiisState const & ); // not implemented
void operator = ( FDiisState const & ); // not implemented
};
// Represents a pair of (vector,residual).
//
// Note that there are simple-to use default implementations for
// one-memory-block, multiple-memory-blocks and lists of associated FTensor
// objects!
//
// For all functions in here, the 'Memory' parameter just supplies an object
// from which temporary memory may be drawn if required for the given
// operation.
struct FDiisTarget
{
typedef double
FScalar;
typedef FStorageDevice::FRecord
FRecord;
// called at begin/end of diis routine. If required, may be used to
// load/store information. Default implementation does nothing.
virtual void Prepare();
virtual void Finish();
// return length of serialized residual in bytes.
virtual FStreamSize nResidualLength() = 0;
virtual FStreamSize nAmplitudeLength() = 0;
// return dot(ThisR,ThisR) for *this residual.
virtual double OwnResidualDot() = 0;
// store residual and amplitude vectors to Device at
// positions ResidualRec/AmplitudeRec.
virtual void SerializeTo( FRecord const &ResidualRec,
FRecord const &AmplitudeRec, FStorageDevice const &Device,
FMemoryStack &Memory ) = 0;
// build Out[i] = (R[i],ThisR) for other residuals stored at Device/Res[i],
// except for i == iSkip.
virtual void CalcResidualDots( FScalar Out[],
FRecord const Res[], uint nVectors, uint iSkip,
FStorageDevice const &Device, FMemoryStack &Memory ) = 0;
// build ThisX = fOwnCoeff * ThisX + \sum_i Coeffs[i] X[i]
// where X denotes amplitudes and residuals,
// except for i == iSkip.
virtual void InterpolateFrom( FScalar fOwnCoeff, FScalar const Coeffs[],
FRecord const Res[], FRecord const Amps[], uint nVectors, uint iSkip,
FStorageDevice const &Device, FMemoryStack &Memory ) = 0;
virtual ~FDiisTarget();
};
struct FMemoryBlock{
typedef FDiisTarget::FScalar
FScalar;
FScalar
*pData;
size_t
nSize;
FMemoryBlock(){};
FMemoryBlock( FScalar *p_, size_t n_ ) : pData(p_), nSize(n_) {};
};
struct FDiisTargetMemoryBlockSet : public FDiisTarget
{
public:
typedef std::size_t
size_t;
// construct an empty target: memory regions need to be added by
// AddBlock()
FDiisTargetMemoryBlockSet() {};
// construct a one-block target.
FDiisTargetMemoryBlockSet( FScalar *pAmp, size_t nAmpSize,
FScalar *pRes, size_t nResSize )
{
AddBlockPair( pAmp, nAmpSize, pRes, nResSize );
};
~FDiisTargetMemoryBlockSet(); // override
// add pAmp/pRes to controlled block set.
void AddBlockPair( FScalar *pAmp, size_t nAmpSize,
FScalar *pRes, size_t nResSize )
{
AddAmpBlock( pAmp, nAmpSize );
AddResBlock( pRes, nResSize );
};
void AddResBlock( FScalar *pBegin, size_t nSize ){
m_ResBlocks.push_back( FMemoryBlock(pBegin, nSize) );
}
void AddAmpBlock( FScalar *pBegin, size_t nSize ){
m_AmpBlocks.push_back( FMemoryBlock(pBegin, nSize) );
}
public:
FStreamSize nResidualLength(); // override
FStreamSize nAmplitudeLength(); // override
double OwnResidualDot(); // override
void SerializeTo( FRecord const &ResidualRec,
FRecord const &AmplitudeRec, FStorageDevice const &Device,
FMemoryStack &Memory ); // override
void CalcResidualDots( FScalar Out[],
FRecord const Res[], uint nVectors, uint iSkip,
FStorageDevice const &Device, FMemoryStack &Memory ); // override
void InterpolateFrom( FScalar fOwnCoeff, FScalar const Coeffs[],
FRecord const Res[], FRecord const Amps[], uint nVectors, uint iSkip,
FStorageDevice const &Device, FMemoryStack &Memory ); // override
protected:
static const uint
nMaxMemoryBlocks = 16;
//nMaxMemoryBlocks = 128;
typedef TArrayFix<FMemoryBlock, nMaxMemoryBlocks>
FMemoryBlockSet;
FMemoryBlockSet
m_AmpBlocks,
m_ResBlocks;
static void InterpolateBlockSet( FMemoryBlockSet &BlockSet,
FScalar fOwnCoeff, FScalar const Coeffs[], FRecord const Vecs[],
uint nVectors, uint iSkip, FStorageDevice const &Device, FMemoryStack &Memory );
static FStreamSize nBlockSetLength( FMemoryBlockSet const &BlockSet );
};
typedef FDiisTargetMemoryBlockSet
FDiisTarget1; // most common one, likely...
} // namespace ct
#endif // _CT8K_DIIS_H
// kate: space-indent on; tab-indent on; backspace-indent on; tab-width 4; indent-width 4; mixedindent off; indent-mode normal;
<file_sep>#include <cmath>
#include <algorithm>
#include "GeneratePolynomials.h"
double getHermiteReciprocal(int l, double* pOut,
double Gx, double Gy, double Gz,
double Tx, double Ty, double Tz,
double exponentVal,
double Scale) {
double ExpVal = exponentVal;//exp(-exponentVal)/exponentVal;
//double ExpVal = exp(-exponentVal)/exponentVal;
if (l == 0) {
pOut[0] += Scale * cos((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal;
return 1.0;
}
else if (l == 1) {
double SinVal = -sin((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
pOut[0] += (Gx) * SinVal;
pOut[1] += (Gy) * SinVal;
pOut[2] += (Gz) * SinVal;
return std::max(std::abs(Gx), std::max(std::abs(Gy), std::abs(Gz)));
}
else if (l == 2) {
double CosVal = -cos((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
pOut[0] += CosVal * Gx * Gx;
pOut[1] += CosVal * Gy * Gy;
pOut[2] += CosVal * Gz * Gz;
pOut[3] += CosVal * Gx * Gy;
pOut[4] += CosVal * Gx * Gz;
pOut[5] += CosVal * Gy * Gz;
return std::max(Gx*Gx, std::max(Gy*Gy, Gz*Gz));
}
else if (l == 3) {
double SinVal = sin((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
pOut[0] += SinVal * Gx * Gx * Gx; //3 0 0
pOut[1] += SinVal * Gy * Gy * Gy; //0 3 0
pOut[2] += SinVal * Gz * Gz * Gz; //0 0 3
pOut[3] += SinVal * Gx * Gy * Gy; //1 2 0
pOut[4] += SinVal * Gx * Gz * Gz; //1 0 2
pOut[5] += SinVal * Gx * Gx * Gy; //2 1 0
pOut[6] += SinVal * Gy * Gz * Gz; //0 1 2
pOut[7] += SinVal * Gx * Gx * Gz; //2 0 1
pOut[8] += SinVal * Gy * Gy * Gz; //0 2 1
pOut[9] += SinVal * Gx * Gy * Gz; //1 1 1
return std::max(std::abs(Gx*Gx*Gx), std::max(std::abs(Gy*Gy*Gy), std::abs(Gz*Gz*Gz)));
}
else if (l == 4) {
double Gx0=1., Gx1, Gx2, Gx3, Gx4;
double Gy0=1., Gy1, Gy2, Gy3, Gy4;
double Gz0=1., Gz1, Gz2, Gz3, Gz4;
double Cosval = cos((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3;
pOut[ 0 ]+= Cosval * Gx4 * Gy0 * Gz0;
pOut[ 1 ]+= Cosval * Gx0 * Gy4 * Gz0;
pOut[ 2 ]+= Cosval * Gx0 * Gy0 * Gz4;
pOut[ 3 ]+= Cosval * Gx3 * Gy1 * Gz0;
pOut[ 4 ]+= Cosval * Gx1 * Gy3 * Gz0;
pOut[ 5 ]+= Cosval * Gx3 * Gy0 * Gz1;
pOut[ 6 ]+= Cosval * Gx1 * Gy0 * Gz3;
pOut[ 7 ]+= Cosval * Gx0 * Gy3 * Gz1;
pOut[ 8 ]+= Cosval * Gx0 * Gy1 * Gz3;
pOut[ 9 ]+= Cosval * Gx2 * Gy2 * Gz0;
pOut[ 10 ]+= Cosval * Gx2 * Gy0 * Gz2;
pOut[ 11 ]+= Cosval * Gx0 * Gy2 * Gz2;
pOut[ 12 ]+= Cosval * Gx1 * Gy1 * Gz2;
pOut[ 13 ]+= Cosval * Gx1 * Gy2 * Gz1;
pOut[ 14 ]+= Cosval * Gx2 * Gy1 * Gz1;
return std::max(std::abs(Gx4), std::max(std::abs(Gy4), std::abs(Gz4)));
}
else if (l == 5) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5;
double Sinval = -sin((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4;
pOut[ 0 ]+= Sinval * Gx5 * Gy0 * Gz0;
pOut[ 1 ]+= Sinval * Gx0 * Gy5 * Gz0;
pOut[ 2 ]+= Sinval * Gx0 * Gy0 * Gz5;
pOut[ 3 ]+= Sinval * Gx1 * Gy4 * Gz0;
pOut[ 4 ]+= Sinval * Gx1 * Gy0 * Gz4;
pOut[ 5 ]+= Sinval * Gx4 * Gy1 * Gz0;
pOut[ 6 ]+= Sinval * Gx0 * Gy1 * Gz4;
pOut[ 7 ]+= Sinval * Gx4 * Gy0 * Gz1;
pOut[ 8 ]+= Sinval * Gx0 * Gy4 * Gz1;
pOut[ 9 ]+= Sinval * Gx3 * Gy2 * Gz0;
pOut[ 10 ]+= Sinval * Gx3 * Gy0 * Gz2;
pOut[ 11 ]+= Sinval * Gx2 * Gy3 * Gz0;
pOut[ 12 ]+= Sinval * Gx0 * Gy3 * Gz2;
pOut[ 13 ]+= Sinval * Gx2 * Gy0 * Gz3;
pOut[ 14 ]+= Sinval * Gx0 * Gy2 * Gz3;
pOut[ 15 ]+= Sinval * Gx3 * Gy1 * Gz1;
pOut[ 16 ]+= Sinval * Gx1 * Gy3 * Gz1;
pOut[ 17 ]+= Sinval * Gx1 * Gy1 * Gz3;
pOut[ 18 ]+= Sinval * Gx1 * Gy2 * Gz2;
pOut[ 19 ]+= Sinval * Gx2 * Gy1 * Gz2;
pOut[ 20 ]+= Sinval * Gx2 * Gy2 * Gz1;
return std::max(std::abs(Gx5), std::max(std::abs(Gy5), std::abs(Gz5)));
//return std::max(Gx5, std::max(Gy5, Gz5));
}
else if (l == 6) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5, Gx6;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5, Gy6;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5, Gz6;
double Cosval = -cos((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4; Gx6 = Gx * Gx5;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4; Gy6 = Gy * Gy5;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4; Gz6 = Gz * Gz5;
pOut[ 0 ]+= Cosval * Gx6 * Gy0 * Gz0;
pOut[ 1 ]+= Cosval * Gx0 * Gy6 * Gz0;
pOut[ 2 ]+= Cosval * Gx0 * Gy0 * Gz6;
pOut[ 3 ]+= Cosval * Gx5 * Gy1 * Gz0;
pOut[ 4 ]+= Cosval * Gx1 * Gy5 * Gz0;
pOut[ 5 ]+= Cosval * Gx5 * Gy0 * Gz1;
pOut[ 6 ]+= Cosval * Gx1 * Gy0 * Gz5;
pOut[ 7 ]+= Cosval * Gx0 * Gy5 * Gz1;
pOut[ 8 ]+= Cosval * Gx0 * Gy1 * Gz5;
pOut[ 9 ]+= Cosval * Gx4 * Gy2 * Gz0;
pOut[ 10 ]+= Cosval * Gx4 * Gy0 * Gz2;
pOut[ 11 ]+= Cosval * Gx2 * Gy4 * Gz0;
pOut[ 12 ]+= Cosval * Gx2 * Gy0 * Gz4;
pOut[ 13 ]+= Cosval * Gx0 * Gy4 * Gz2;
pOut[ 14 ]+= Cosval * Gx0 * Gy2 * Gz4;
pOut[ 15 ]+= Cosval * Gx3 * Gy3 * Gz0;
pOut[ 16 ]+= Cosval * Gx3 * Gy0 * Gz3;
pOut[ 17 ]+= Cosval * Gx0 * Gy3 * Gz3;
pOut[ 18 ]+= Cosval * Gx1 * Gy1 * Gz4;
pOut[ 19 ]+= Cosval * Gx1 * Gy4 * Gz1;
pOut[ 20 ]+= Cosval * Gx4 * Gy1 * Gz1;
pOut[ 21 ]+= Cosval * Gx3 * Gy1 * Gz2;
pOut[ 22 ]+= Cosval * Gx1 * Gy3 * Gz2;
pOut[ 23 ]+= Cosval * Gx3 * Gy2 * Gz1;
pOut[ 24 ]+= Cosval * Gx1 * Gy2 * Gz3;
pOut[ 25 ]+= Cosval * Gx2 * Gy3 * Gz1;
pOut[ 26 ]+= Cosval * Gx2 * Gy1 * Gz3;
pOut[ 27 ]+= Cosval * Gx2 * Gy2 * Gz2;
return std::max(std::abs(Gx6), std::max(std::abs(Gy6), std::abs(Gz6)));
//return std::max(Gx6, std::max(Gy6, Gz6));
}
else if (l == 7) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5, Gx6, Gx7;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5, Gy6, Gy7;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5, Gz6, Gz7;
double Sinval = sin((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4; Gx6 = Gx * Gx5; Gx7 = Gx * Gx6;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4; Gy6 = Gy * Gy5; Gy7 = Gy * Gy6;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4; Gz6 = Gz * Gz5; Gz7 = Gz * Gz6;
pOut[ 0 ]+= Sinval * Gx7 * Gy0 * Gz0;
pOut[ 1 ]+= Sinval * Gx0 * Gy7 * Gz0;
pOut[ 2 ]+= Sinval * Gx0 * Gy0 * Gz7;
pOut[ 3 ]+= Sinval * Gx1 * Gy6 * Gz0;
pOut[ 4 ]+= Sinval * Gx1 * Gy0 * Gz6;
pOut[ 5 ]+= Sinval * Gx6 * Gy1 * Gz0;
pOut[ 6 ]+= Sinval * Gx0 * Gy1 * Gz6;
pOut[ 7 ]+= Sinval * Gx6 * Gy0 * Gz1;
pOut[ 8 ]+= Sinval * Gx0 * Gy6 * Gz1;
pOut[ 9 ]+= Sinval * Gx5 * Gy2 * Gz0;
pOut[ 10 ]+= Sinval * Gx5 * Gy0 * Gz2;
pOut[ 11 ]+= Sinval * Gx2 * Gy5 * Gz0;
pOut[ 12 ]+= Sinval * Gx0 * Gy5 * Gz2;
pOut[ 13 ]+= Sinval * Gx2 * Gy0 * Gz5;
pOut[ 14 ]+= Sinval * Gx0 * Gy2 * Gz5;
pOut[ 15 ]+= Sinval * Gx3 * Gy4 * Gz0;
pOut[ 16 ]+= Sinval * Gx3 * Gy0 * Gz4;
pOut[ 17 ]+= Sinval * Gx4 * Gy3 * Gz0;
pOut[ 18 ]+= Sinval * Gx0 * Gy3 * Gz4;
pOut[ 19 ]+= Sinval * Gx4 * Gy0 * Gz3;
pOut[ 20 ]+= Sinval * Gx0 * Gy4 * Gz3;
pOut[ 21 ]+= Sinval * Gx5 * Gy1 * Gz1;
pOut[ 22 ]+= Sinval * Gx1 * Gy5 * Gz1;
pOut[ 23 ]+= Sinval * Gx1 * Gy1 * Gz5;
pOut[ 24 ]+= Sinval * Gx1 * Gy4 * Gz2;
pOut[ 25 ]+= Sinval * Gx1 * Gy2 * Gz4;
pOut[ 26 ]+= Sinval * Gx4 * Gy1 * Gz2;
pOut[ 27 ]+= Sinval * Gx2 * Gy1 * Gz4;
pOut[ 28 ]+= Sinval * Gx4 * Gy2 * Gz1;
pOut[ 29 ]+= Sinval * Gx2 * Gy4 * Gz1;
pOut[ 30 ]+= Sinval * Gx3 * Gy3 * Gz1;
pOut[ 31 ]+= Sinval * Gx3 * Gy1 * Gz3;
pOut[ 32 ]+= Sinval * Gx1 * Gy3 * Gz3;
pOut[ 33 ]+= Sinval * Gx3 * Gy2 * Gz2;
pOut[ 34 ]+= Sinval * Gx2 * Gy3 * Gz2;
pOut[ 35 ]+= Sinval * Gx2 * Gy2 * Gz3;
return std::max(std::abs(Gx7), std::max(std::abs(Gy7), std::abs(Gz7)));
//return std::max(Gx7, std::max(Gy7, Gz7));
}
else if (l == 8) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5, Gx6, Gx7, Gx8;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5, Gy6, Gy7, Gy8;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5, Gz6, Gz7, Gz8;
double Cosval = cos((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4; Gx6 = Gx * Gx5; Gx7 = Gx * Gx6; Gx8 = Gx * Gx7;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4; Gy6 = Gy * Gy5; Gy7 = Gy * Gy6; Gy8 = Gy * Gy7;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4; Gz6 = Gz * Gz5; Gz7 = Gz * Gz6; Gz8 = Gz * Gz7;
pOut[ 0 ]+= Cosval * Gx8 * Gy0 * Gz0;
pOut[ 1 ]+= Cosval * Gx0 * Gy8 * Gz0;
pOut[ 2 ]+= Cosval * Gx0 * Gy0 * Gz8;
pOut[ 3 ]+= Cosval * Gx7 * Gy1 * Gz0;
pOut[ 4 ]+= Cosval * Gx1 * Gy7 * Gz0;
pOut[ 5 ]+= Cosval * Gx7 * Gy0 * Gz1;
pOut[ 6 ]+= Cosval * Gx1 * Gy0 * Gz7;
pOut[ 7 ]+= Cosval * Gx0 * Gy7 * Gz1;
pOut[ 8 ]+= Cosval * Gx0 * Gy1 * Gz7;
pOut[ 9 ]+= Cosval * Gx6 * Gy2 * Gz0;
pOut[ 10 ]+= Cosval * Gx6 * Gy0 * Gz2;
pOut[ 11 ]+= Cosval * Gx2 * Gy6 * Gz0;
pOut[ 12 ]+= Cosval * Gx2 * Gy0 * Gz6;
pOut[ 13 ]+= Cosval * Gx0 * Gy6 * Gz2;
pOut[ 14 ]+= Cosval * Gx0 * Gy2 * Gz6;
pOut[ 15 ]+= Cosval * Gx5 * Gy3 * Gz0;
pOut[ 16 ]+= Cosval * Gx3 * Gy5 * Gz0;
pOut[ 17 ]+= Cosval * Gx5 * Gy0 * Gz3;
pOut[ 18 ]+= Cosval * Gx3 * Gy0 * Gz5;
pOut[ 19 ]+= Cosval * Gx0 * Gy5 * Gz3;
pOut[ 20 ]+= Cosval * Gx0 * Gy3 * Gz5;
pOut[ 21 ]+= Cosval * Gx4 * Gy4 * Gz0;
pOut[ 22 ]+= Cosval * Gx4 * Gy0 * Gz4;
pOut[ 23 ]+= Cosval * Gx0 * Gy4 * Gz4;
pOut[ 24 ]+= Cosval * Gx1 * Gy1 * Gz6;
pOut[ 25 ]+= Cosval * Gx1 * Gy6 * Gz1;
pOut[ 26 ]+= Cosval * Gx6 * Gy1 * Gz1;
pOut[ 27 ]+= Cosval * Gx5 * Gy1 * Gz2;
pOut[ 28 ]+= Cosval * Gx1 * Gy5 * Gz2;
pOut[ 29 ]+= Cosval * Gx5 * Gy2 * Gz1;
pOut[ 30 ]+= Cosval * Gx1 * Gy2 * Gz5;
pOut[ 31 ]+= Cosval * Gx2 * Gy5 * Gz1;
pOut[ 32 ]+= Cosval * Gx2 * Gy1 * Gz5;
pOut[ 33 ]+= Cosval * Gx3 * Gy1 * Gz4;
pOut[ 34 ]+= Cosval * Gx1 * Gy3 * Gz4;
pOut[ 35 ]+= Cosval * Gx3 * Gy4 * Gz1;
pOut[ 36 ]+= Cosval * Gx1 * Gy4 * Gz3;
pOut[ 37 ]+= Cosval * Gx4 * Gy3 * Gz1;
pOut[ 38 ]+= Cosval * Gx4 * Gy1 * Gz3;
pOut[ 39 ]+= Cosval * Gx4 * Gy2 * Gz2;
pOut[ 40 ]+= Cosval * Gx2 * Gy4 * Gz2;
pOut[ 41 ]+= Cosval * Gx2 * Gy2 * Gz4;
pOut[ 42 ]+= Cosval * Gx3 * Gy3 * Gz2;
pOut[ 43 ]+= Cosval * Gx3 * Gy2 * Gz3;
pOut[ 44 ]+= Cosval * Gx2 * Gy3 * Gz3;
return std::max(Gx8, std::max(Gy8, Gz8));
}
else if (l == 9) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5, Gx6, Gx7, Gx8, Gx9;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5, Gy6, Gy7, Gy8, Gy9;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5, Gz6, Gz7, Gz8, Gz9;
double Sinval = -sin((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4; Gx6 = Gx * Gx5; Gx7 = Gx * Gx6; Gx8 = Gx * Gx7; Gx9 = Gx * Gx8;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4; Gy6 = Gy * Gy5; Gy7 = Gy * Gy6; Gy8 = Gy * Gy7; Gy9 = Gy * Gy8;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4; Gz6 = Gz * Gz5; Gz7 = Gz * Gz6; Gz8 = Gz * Gz7; Gz9 = Gz * Gz8;
pOut[ 0 ]+= Sinval * Gx9 * Gy0 * Gz0;
pOut[ 1 ]+= Sinval * Gx0 * Gy9 * Gz0;
pOut[ 2 ]+= Sinval * Gx0 * Gy0 * Gz9;
pOut[ 3 ]+= Sinval * Gx1 * Gy8 * Gz0;
pOut[ 4 ]+= Sinval * Gx1 * Gy0 * Gz8;
pOut[ 5 ]+= Sinval * Gx8 * Gy1 * Gz0;
pOut[ 6 ]+= Sinval * Gx0 * Gy1 * Gz8;
pOut[ 7 ]+= Sinval * Gx8 * Gy0 * Gz1;
pOut[ 8 ]+= Sinval * Gx0 * Gy8 * Gz1;
pOut[ 9 ]+= Sinval * Gx7 * Gy2 * Gz0;
pOut[ 10 ]+= Sinval * Gx7 * Gy0 * Gz2;
pOut[ 11 ]+= Sinval * Gx2 * Gy7 * Gz0;
pOut[ 12 ]+= Sinval * Gx0 * Gy7 * Gz2;
pOut[ 13 ]+= Sinval * Gx2 * Gy0 * Gz7;
pOut[ 14 ]+= Sinval * Gx0 * Gy2 * Gz7;
pOut[ 15 ]+= Sinval * Gx3 * Gy6 * Gz0;
pOut[ 16 ]+= Sinval * Gx3 * Gy0 * Gz6;
pOut[ 17 ]+= Sinval * Gx6 * Gy3 * Gz0;
pOut[ 18 ]+= Sinval * Gx0 * Gy3 * Gz6;
pOut[ 19 ]+= Sinval * Gx6 * Gy0 * Gz3;
pOut[ 20 ]+= Sinval * Gx0 * Gy6 * Gz3;
pOut[ 21 ]+= Sinval * Gx5 * Gy4 * Gz0;
pOut[ 22 ]+= Sinval * Gx5 * Gy0 * Gz4;
pOut[ 23 ]+= Sinval * Gx4 * Gy5 * Gz0;
pOut[ 24 ]+= Sinval * Gx0 * Gy5 * Gz4;
pOut[ 25 ]+= Sinval * Gx4 * Gy0 * Gz5;
pOut[ 26 ]+= Sinval * Gx0 * Gy4 * Gz5;
pOut[ 27 ]+= Sinval * Gx7 * Gy1 * Gz1;
pOut[ 28 ]+= Sinval * Gx1 * Gy7 * Gz1;
pOut[ 29 ]+= Sinval * Gx1 * Gy1 * Gz7;
pOut[ 30 ]+= Sinval * Gx1 * Gy6 * Gz2;
pOut[ 31 ]+= Sinval * Gx1 * Gy2 * Gz6;
pOut[ 32 ]+= Sinval * Gx6 * Gy1 * Gz2;
pOut[ 33 ]+= Sinval * Gx2 * Gy1 * Gz6;
pOut[ 34 ]+= Sinval * Gx6 * Gy2 * Gz1;
pOut[ 35 ]+= Sinval * Gx2 * Gy6 * Gz1;
pOut[ 36 ]+= Sinval * Gx5 * Gy3 * Gz1;
pOut[ 37 ]+= Sinval * Gx5 * Gy1 * Gz3;
pOut[ 38 ]+= Sinval * Gx3 * Gy5 * Gz1;
pOut[ 39 ]+= Sinval * Gx3 * Gy1 * Gz5;
pOut[ 40 ]+= Sinval * Gx1 * Gy5 * Gz3;
pOut[ 41 ]+= Sinval * Gx1 * Gy3 * Gz5;
pOut[ 42 ]+= Sinval * Gx1 * Gy4 * Gz4;
pOut[ 43 ]+= Sinval * Gx4 * Gy1 * Gz4;
pOut[ 44 ]+= Sinval * Gx4 * Gy4 * Gz1;
pOut[ 45 ]+= Sinval * Gx5 * Gy2 * Gz2;
pOut[ 46 ]+= Sinval * Gx2 * Gy5 * Gz2;
pOut[ 47 ]+= Sinval * Gx2 * Gy2 * Gz5;
pOut[ 48 ]+= Sinval * Gx3 * Gy4 * Gz2;
pOut[ 49 ]+= Sinval * Gx3 * Gy2 * Gz4;
pOut[ 50 ]+= Sinval * Gx4 * Gy3 * Gz2;
pOut[ 51 ]+= Sinval * Gx2 * Gy3 * Gz4;
pOut[ 52 ]+= Sinval * Gx4 * Gy2 * Gz3;
pOut[ 53 ]+= Sinval * Gx2 * Gy4 * Gz3;
pOut[ 54 ]+= Sinval * Gx3 * Gy3 * Gz3;
return std::max(std::abs(Gx9), std::max(std::abs(Gy9), std::abs(Gz9)));
//return std::max(Gx9, std::max(Gy9, Gz9));
}
else if (l == 10) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5, Gx6, Gx7, Gx8, Gx9, Gx10;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5, Gy6, Gy7, Gy8, Gy9, Gy10;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5, Gz6, Gz7, Gz8, Gz9, Gz10;
double Cosval = -cos((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4; Gx6 = Gx * Gx5; Gx7 = Gx * Gx6; Gx8 = Gx * Gx7; Gx9 = Gx * Gx8; Gx10 = Gx * Gx9;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4; Gy6 = Gy * Gy5; Gy7 = Gy * Gy6; Gy8 = Gy * Gy7; Gy9 = Gy * Gy8; Gy10 = Gy * Gy9;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4; Gz6 = Gz * Gz5; Gz7 = Gz * Gz6; Gz8 = Gz * Gz7; Gz9 = Gz * Gz8; Gz10 = Gz * Gz9;
pOut[ 0 ]+= Cosval * Gx10 * Gy0 * Gz0;
pOut[ 1 ]+= Cosval * Gx0 * Gy10 * Gz0;
pOut[ 2 ]+= Cosval * Gx0 * Gy0 * Gz10;
pOut[ 3 ]+= Cosval * Gx9 * Gy1 * Gz0;
pOut[ 4 ]+= Cosval * Gx1 * Gy9 * Gz0;
pOut[ 5 ]+= Cosval * Gx9 * Gy0 * Gz1;
pOut[ 6 ]+= Cosval * Gx1 * Gy0 * Gz9;
pOut[ 7 ]+= Cosval * Gx0 * Gy9 * Gz1;
pOut[ 8 ]+= Cosval * Gx0 * Gy1 * Gz9;
pOut[ 9 ]+= Cosval * Gx8 * Gy2 * Gz0;
pOut[ 10 ]+= Cosval * Gx8 * Gy0 * Gz2;
pOut[ 11 ]+= Cosval * Gx2 * Gy8 * Gz0;
pOut[ 12 ]+= Cosval * Gx2 * Gy0 * Gz8;
pOut[ 13 ]+= Cosval * Gx0 * Gy8 * Gz2;
pOut[ 14 ]+= Cosval * Gx0 * Gy2 * Gz8;
pOut[ 15 ]+= Cosval * Gx7 * Gy3 * Gz0;
pOut[ 16 ]+= Cosval * Gx3 * Gy7 * Gz0;
pOut[ 17 ]+= Cosval * Gx7 * Gy0 * Gz3;
pOut[ 18 ]+= Cosval * Gx3 * Gy0 * Gz7;
pOut[ 19 ]+= Cosval * Gx0 * Gy7 * Gz3;
pOut[ 20 ]+= Cosval * Gx0 * Gy3 * Gz7;
pOut[ 21 ]+= Cosval * Gx6 * Gy4 * Gz0;
pOut[ 22 ]+= Cosval * Gx6 * Gy0 * Gz4;
pOut[ 23 ]+= Cosval * Gx4 * Gy6 * Gz0;
pOut[ 24 ]+= Cosval * Gx4 * Gy0 * Gz6;
pOut[ 25 ]+= Cosval * Gx0 * Gy6 * Gz4;
pOut[ 26 ]+= Cosval * Gx0 * Gy4 * Gz6;
pOut[ 27 ]+= Cosval * Gx5 * Gy5 * Gz0;
pOut[ 28 ]+= Cosval * Gx5 * Gy0 * Gz5;
pOut[ 29 ]+= Cosval * Gx0 * Gy5 * Gz5;
pOut[ 30 ]+= Cosval * Gx1 * Gy1 * Gz8;
pOut[ 31 ]+= Cosval * Gx1 * Gy8 * Gz1;
pOut[ 32 ]+= Cosval * Gx8 * Gy1 * Gz1;
pOut[ 33 ]+= Cosval * Gx7 * Gy1 * Gz2;
pOut[ 34 ]+= Cosval * Gx1 * Gy7 * Gz2;
pOut[ 35 ]+= Cosval * Gx7 * Gy2 * Gz1;
pOut[ 36 ]+= Cosval * Gx1 * Gy2 * Gz7;
pOut[ 37 ]+= Cosval * Gx2 * Gy7 * Gz1;
pOut[ 38 ]+= Cosval * Gx2 * Gy1 * Gz7;
pOut[ 39 ]+= Cosval * Gx3 * Gy1 * Gz6;
pOut[ 40 ]+= Cosval * Gx1 * Gy3 * Gz6;
pOut[ 41 ]+= Cosval * Gx3 * Gy6 * Gz1;
pOut[ 42 ]+= Cosval * Gx1 * Gy6 * Gz3;
pOut[ 43 ]+= Cosval * Gx6 * Gy3 * Gz1;
pOut[ 44 ]+= Cosval * Gx6 * Gy1 * Gz3;
pOut[ 45 ]+= Cosval * Gx5 * Gy1 * Gz4;
pOut[ 46 ]+= Cosval * Gx1 * Gy5 * Gz4;
pOut[ 47 ]+= Cosval * Gx5 * Gy4 * Gz1;
pOut[ 48 ]+= Cosval * Gx1 * Gy4 * Gz5;
pOut[ 49 ]+= Cosval * Gx4 * Gy5 * Gz1;
pOut[ 50 ]+= Cosval * Gx4 * Gy1 * Gz5;
pOut[ 51 ]+= Cosval * Gx6 * Gy2 * Gz2;
pOut[ 52 ]+= Cosval * Gx2 * Gy6 * Gz2;
pOut[ 53 ]+= Cosval * Gx2 * Gy2 * Gz6;
pOut[ 54 ]+= Cosval * Gx5 * Gy3 * Gz2;
pOut[ 55 ]+= Cosval * Gx3 * Gy5 * Gz2;
pOut[ 56 ]+= Cosval * Gx5 * Gy2 * Gz3;
pOut[ 57 ]+= Cosval * Gx3 * Gy2 * Gz5;
pOut[ 58 ]+= Cosval * Gx2 * Gy5 * Gz3;
pOut[ 59 ]+= Cosval * Gx2 * Gy3 * Gz5;
pOut[ 60 ]+= Cosval * Gx4 * Gy4 * Gz2;
pOut[ 61 ]+= Cosval * Gx4 * Gy2 * Gz4;
pOut[ 62 ]+= Cosval * Gx2 * Gy4 * Gz4;
pOut[ 63 ]+= Cosval * Gx3 * Gy3 * Gz4;
pOut[ 64 ]+= Cosval * Gx3 * Gy4 * Gz3;
pOut[ 65 ]+= Cosval * Gx4 * Gy3 * Gz3;
return std::max(std::abs(Gx10), std::max(std::abs(Gy10), std::abs(Gz10)));
//return std::max(Gx10, std::max(Gy10, Gz10));
}
else if (l == 11) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5, Gx6, Gx7, Gx8, Gx9, Gx10, Gx11;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5, Gy6, Gy7, Gy8, Gy9, Gy10, Gy11;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5, Gz6, Gz7, Gz8, Gz9, Gz10, Gz11;
double Sinval = sin((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4; Gx6 = Gx * Gx5; Gx7 = Gx * Gx6; Gx8 = Gx * Gx7; Gx9 = Gx * Gx8; Gx10 = Gx * Gx9; Gx11 = Gx * Gx10;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4; Gy6 = Gy * Gy5; Gy7 = Gy * Gy6; Gy8 = Gy * Gy7; Gy9 = Gy * Gy8; Gy10 = Gy * Gy9; Gy11 = Gy * Gy10;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4; Gz6 = Gz * Gz5; Gz7 = Gz * Gz6; Gz8 = Gz * Gz7; Gz9 = Gz * Gz8; Gz10 = Gz * Gz9; Gz11 = Gz * Gz10;
pOut[ 0 ]+= Sinval * Gx11 * Gy0 * Gz0;
pOut[ 1 ]+= Sinval * Gx0 * Gy11 * Gz0;
pOut[ 2 ]+= Sinval * Gx0 * Gy0 * Gz11;
pOut[ 3 ]+= Sinval * Gx1 * Gy10 * Gz0;
pOut[ 4 ]+= Sinval * Gx1 * Gy0 * Gz10;
pOut[ 5 ]+= Sinval * Gx10 * Gy1 * Gz0;
pOut[ 6 ]+= Sinval * Gx0 * Gy1 * Gz10;
pOut[ 7 ]+= Sinval * Gx10 * Gy0 * Gz1;
pOut[ 8 ]+= Sinval * Gx0 * Gy10 * Gz1;
pOut[ 9 ]+= Sinval * Gx9 * Gy2 * Gz0;
pOut[ 10 ]+= Sinval * Gx9 * Gy0 * Gz2;
pOut[ 11 ]+= Sinval * Gx2 * Gy9 * Gz0;
pOut[ 12 ]+= Sinval * Gx0 * Gy9 * Gz2;
pOut[ 13 ]+= Sinval * Gx2 * Gy0 * Gz9;
pOut[ 14 ]+= Sinval * Gx0 * Gy2 * Gz9;
pOut[ 15 ]+= Sinval * Gx3 * Gy8 * Gz0;
pOut[ 16 ]+= Sinval * Gx3 * Gy0 * Gz8;
pOut[ 17 ]+= Sinval * Gx8 * Gy3 * Gz0;
pOut[ 18 ]+= Sinval * Gx0 * Gy3 * Gz8;
pOut[ 19 ]+= Sinval * Gx8 * Gy0 * Gz3;
pOut[ 20 ]+= Sinval * Gx0 * Gy8 * Gz3;
pOut[ 21 ]+= Sinval * Gx7 * Gy4 * Gz0;
pOut[ 22 ]+= Sinval * Gx7 * Gy0 * Gz4;
pOut[ 23 ]+= Sinval * Gx4 * Gy7 * Gz0;
pOut[ 24 ]+= Sinval * Gx0 * Gy7 * Gz4;
pOut[ 25 ]+= Sinval * Gx4 * Gy0 * Gz7;
pOut[ 26 ]+= Sinval * Gx0 * Gy4 * Gz7;
pOut[ 27 ]+= Sinval * Gx5 * Gy6 * Gz0;
pOut[ 28 ]+= Sinval * Gx5 * Gy0 * Gz6;
pOut[ 29 ]+= Sinval * Gx6 * Gy5 * Gz0;
pOut[ 30 ]+= Sinval * Gx0 * Gy5 * Gz6;
pOut[ 31 ]+= Sinval * Gx6 * Gy0 * Gz5;
pOut[ 32 ]+= Sinval * Gx0 * Gy6 * Gz5;
pOut[ 33 ]+= Sinval * Gx9 * Gy1 * Gz1;
pOut[ 34 ]+= Sinval * Gx1 * Gy9 * Gz1;
pOut[ 35 ]+= Sinval * Gx1 * Gy1 * Gz9;
pOut[ 36 ]+= Sinval * Gx1 * Gy8 * Gz2;
pOut[ 37 ]+= Sinval * Gx1 * Gy2 * Gz8;
pOut[ 38 ]+= Sinval * Gx8 * Gy1 * Gz2;
pOut[ 39 ]+= Sinval * Gx2 * Gy1 * Gz8;
pOut[ 40 ]+= Sinval * Gx8 * Gy2 * Gz1;
pOut[ 41 ]+= Sinval * Gx2 * Gy8 * Gz1;
pOut[ 42 ]+= Sinval * Gx7 * Gy3 * Gz1;
pOut[ 43 ]+= Sinval * Gx7 * Gy1 * Gz3;
pOut[ 44 ]+= Sinval * Gx3 * Gy7 * Gz1;
pOut[ 45 ]+= Sinval * Gx3 * Gy1 * Gz7;
pOut[ 46 ]+= Sinval * Gx1 * Gy7 * Gz3;
pOut[ 47 ]+= Sinval * Gx1 * Gy3 * Gz7;
pOut[ 48 ]+= Sinval * Gx1 * Gy6 * Gz4;
pOut[ 49 ]+= Sinval * Gx1 * Gy4 * Gz6;
pOut[ 50 ]+= Sinval * Gx6 * Gy1 * Gz4;
pOut[ 51 ]+= Sinval * Gx4 * Gy1 * Gz6;
pOut[ 52 ]+= Sinval * Gx6 * Gy4 * Gz1;
pOut[ 53 ]+= Sinval * Gx4 * Gy6 * Gz1;
pOut[ 54 ]+= Sinval * Gx5 * Gy5 * Gz1;
pOut[ 55 ]+= Sinval * Gx5 * Gy1 * Gz5;
pOut[ 56 ]+= Sinval * Gx1 * Gy5 * Gz5;
pOut[ 57 ]+= Sinval * Gx7 * Gy2 * Gz2;
pOut[ 58 ]+= Sinval * Gx2 * Gy7 * Gz2;
pOut[ 59 ]+= Sinval * Gx2 * Gy2 * Gz7;
pOut[ 60 ]+= Sinval * Gx3 * Gy6 * Gz2;
pOut[ 61 ]+= Sinval * Gx3 * Gy2 * Gz6;
pOut[ 62 ]+= Sinval * Gx6 * Gy3 * Gz2;
pOut[ 63 ]+= Sinval * Gx2 * Gy3 * Gz6;
pOut[ 64 ]+= Sinval * Gx6 * Gy2 * Gz3;
pOut[ 65 ]+= Sinval * Gx2 * Gy6 * Gz3;
pOut[ 66 ]+= Sinval * Gx5 * Gy4 * Gz2;
pOut[ 67 ]+= Sinval * Gx5 * Gy2 * Gz4;
pOut[ 68 ]+= Sinval * Gx4 * Gy5 * Gz2;
pOut[ 69 ]+= Sinval * Gx2 * Gy5 * Gz4;
pOut[ 70 ]+= Sinval * Gx4 * Gy2 * Gz5;
pOut[ 71 ]+= Sinval * Gx2 * Gy4 * Gz5;
pOut[ 72 ]+= Sinval * Gx5 * Gy3 * Gz3;
pOut[ 73 ]+= Sinval * Gx3 * Gy5 * Gz3;
pOut[ 74 ]+= Sinval * Gx3 * Gy3 * Gz5;
pOut[ 75 ]+= Sinval * Gx3 * Gy4 * Gz4;
pOut[ 76 ]+= Sinval * Gx4 * Gy3 * Gz4;
pOut[ 77 ]+= Sinval * Gx4 * Gy4 * Gz3;
return std::max(std::abs(Gx11), std::max(std::abs(Gy11), std::abs(Gz11)));
//return std::max(Gx11, std::max(Gy11, Gz11));
}
else if (l == 12) {
double Gx0=1., Gx1, Gx2, Gx4, Gx3, Gx5, Gx6, Gx7, Gx8, Gx9, Gx10, Gx11, Gx12;
double Gy0=1., Gy1, Gy2, Gy4, Gy3, Gy5, Gy6, Gy7, Gy8, Gy9, Gy10, Gy11, Gy12;
double Gz0=1., Gz1, Gz2, Gz4, Gz3, Gz5, Gz6, Gz7, Gz8, Gz9, Gz10, Gz11, Gz12;
double Cosval = cos((Gx * Tx + Gy * Ty + Gz * Tz)) * ExpVal * Scale;
Gx1 = Gx * Gx0; Gx2 = Gx * Gx1; Gx3 = Gx * Gx2; Gx4 = Gx * Gx3; Gx5 = Gx * Gx4; Gx6 = Gx * Gx5; Gx7 = Gx * Gx6; Gx8 = Gx * Gx7; Gx9 = Gx * Gx8; Gx10 = Gx * Gx9; Gx11 = Gx * Gx10; Gx12 = Gx * Gx11;
Gy1 = Gy * Gy0; Gy2 = Gy * Gy1; Gy3 = Gy * Gy2; Gy4 = Gy * Gy3; Gy5 = Gy * Gy4; Gy6 = Gy * Gy5; Gy7 = Gy * Gy6; Gy8 = Gy * Gy7; Gy9 = Gy * Gy8; Gy10 = Gy * Gy9; Gy11 = Gy * Gy10; Gy12 = Gy * Gy11;
Gz1 = Gz * Gz0; Gz2 = Gz * Gz1; Gz3 = Gz * Gz2; Gz4 = Gz * Gz3; Gz5 = Gz * Gz4; Gz6 = Gz * Gz5; Gz7 = Gz * Gz6; Gz8 = Gz * Gz7; Gz9 = Gz * Gz8; Gz10 = Gz * Gz9; Gz11 = Gz * Gz10; Gz12 = Gz * Gz11;
pOut[ 0 ] += Cosval * Gx12 * Gy0 * Gz0;
pOut[ 1 ] += Cosval * Gx0 * Gy12 * Gz0;
pOut[ 2 ] += Cosval * Gx0 * Gy0 * Gz12;
pOut[ 3 ] += Cosval * Gx11 * Gy1 * Gz0;
pOut[ 4 ] += Cosval * Gx1 * Gy11 * Gz0;
pOut[ 5 ] += Cosval * Gx11 * Gy0 * Gz1;
pOut[ 6 ] += Cosval * Gx1 * Gy0 * Gz11;
pOut[ 7 ] += Cosval * Gx0 * Gy11 * Gz1;
pOut[ 8 ] += Cosval * Gx0 * Gy1 * Gz11;
pOut[ 9 ] += Cosval * Gx10 * Gy2 * Gz0;
pOut[ 10 ] += Cosval * Gx10 * Gy0 * Gz2;
pOut[ 11 ] += Cosval * Gx2 * Gy10 * Gz0;
pOut[ 12 ] += Cosval * Gx2 * Gy0 * Gz10;
pOut[ 13 ] += Cosval * Gx0 * Gy10 * Gz2;
pOut[ 14 ] += Cosval * Gx0 * Gy2 * Gz10;
pOut[ 15 ] += Cosval * Gx9 * Gy3 * Gz0;
pOut[ 16 ] += Cosval * Gx3 * Gy9 * Gz0;
pOut[ 17 ] += Cosval * Gx9 * Gy0 * Gz3;
pOut[ 18 ] += Cosval * Gx3 * Gy0 * Gz9;
pOut[ 19 ] += Cosval * Gx0 * Gy9 * Gz3;
pOut[ 20 ] += Cosval * Gx0 * Gy3 * Gz9;
pOut[ 21 ] += Cosval * Gx8 * Gy4 * Gz0;
pOut[ 22 ] += Cosval * Gx8 * Gy0 * Gz4;
pOut[ 23 ] += Cosval * Gx4 * Gy8 * Gz0;
pOut[ 24 ] += Cosval * Gx4 * Gy0 * Gz8;
pOut[ 25 ] += Cosval * Gx0 * Gy8 * Gz4;
pOut[ 26 ] += Cosval * Gx0 * Gy4 * Gz8;
pOut[ 27 ] += Cosval * Gx7 * Gy5 * Gz0;
pOut[ 28 ] += Cosval * Gx5 * Gy7 * Gz0;
pOut[ 29 ] += Cosval * Gx7 * Gy0 * Gz5;
pOut[ 30 ] += Cosval * Gx5 * Gy0 * Gz7;
pOut[ 31 ] += Cosval * Gx0 * Gy7 * Gz5;
pOut[ 32 ] += Cosval * Gx0 * Gy5 * Gz7;
pOut[ 33 ] += Cosval * Gx6 * Gy6 * Gz0;
pOut[ 34 ] += Cosval * Gx6 * Gy0 * Gz6;
pOut[ 35 ] += Cosval * Gx0 * Gy6 * Gz6;
pOut[ 36 ] += Cosval * Gx1 * Gy1 * Gz10;
pOut[ 37 ] += Cosval * Gx1 * Gy10 * Gz1;
pOut[ 38 ] += Cosval * Gx10 * Gy1 * Gz1;
pOut[ 39 ] += Cosval * Gx9 * Gy1 * Gz2;
pOut[ 40 ] += Cosval * Gx1 * Gy9 * Gz2;
pOut[ 41 ] += Cosval * Gx9 * Gy2 * Gz1;
pOut[ 42 ] += Cosval * Gx1 * Gy2 * Gz9;
pOut[ 43 ] += Cosval * Gx2 * Gy9 * Gz1;
pOut[ 44 ] += Cosval * Gx2 * Gy1 * Gz9;
pOut[ 45 ] += Cosval * Gx3 * Gy1 * Gz8;
pOut[ 46 ] += Cosval * Gx1 * Gy3 * Gz8;
pOut[ 47 ] += Cosval * Gx3 * Gy8 * Gz1;
pOut[ 48 ] += Cosval * Gx1 * Gy8 * Gz3;
pOut[ 49 ] += Cosval * Gx8 * Gy3 * Gz1;
pOut[ 50 ] += Cosval * Gx8 * Gy1 * Gz3;
pOut[ 51 ] += Cosval * Gx7 * Gy1 * Gz4;
pOut[ 52 ] += Cosval * Gx1 * Gy7 * Gz4;
pOut[ 53 ] += Cosval * Gx7 * Gy4 * Gz1;
pOut[ 54 ] += Cosval * Gx1 * Gy4 * Gz7;
pOut[ 55 ] += Cosval * Gx4 * Gy7 * Gz1;
pOut[ 56 ] += Cosval * Gx4 * Gy1 * Gz7;
pOut[ 57 ] += Cosval * Gx5 * Gy1 * Gz6;
pOut[ 58 ] += Cosval * Gx1 * Gy5 * Gz6;
pOut[ 59 ] += Cosval * Gx5 * Gy6 * Gz1;
pOut[ 60 ] += Cosval * Gx1 * Gy6 * Gz5;
pOut[ 61 ] += Cosval * Gx6 * Gy5 * Gz1;
pOut[ 62 ] += Cosval * Gx6 * Gy1 * Gz5;
pOut[ 63 ] += Cosval * Gx8 * Gy2 * Gz2;
pOut[ 64 ] += Cosval * Gx2 * Gy8 * Gz2;
pOut[ 65 ] += Cosval * Gx2 * Gy2 * Gz8;
pOut[ 66 ] += Cosval * Gx7 * Gy3 * Gz2;
pOut[ 67 ] += Cosval * Gx3 * Gy7 * Gz2;
pOut[ 68 ] += Cosval * Gx7 * Gy2 * Gz3;
pOut[ 69 ] += Cosval * Gx3 * Gy2 * Gz7;
pOut[ 70 ] += Cosval * Gx2 * Gy7 * Gz3;
pOut[ 71 ] += Cosval * Gx2 * Gy3 * Gz7;
pOut[ 72 ] += Cosval * Gx6 * Gy4 * Gz2;
pOut[ 73 ] += Cosval * Gx6 * Gy2 * Gz4;
pOut[ 74 ] += Cosval * Gx4 * Gy6 * Gz2;
pOut[ 75 ] += Cosval * Gx4 * Gy2 * Gz6;
pOut[ 76 ] += Cosval * Gx2 * Gy6 * Gz4;
pOut[ 77 ] += Cosval * Gx2 * Gy4 * Gz6;
pOut[ 78 ] += Cosval * Gx5 * Gy5 * Gz2;
pOut[ 79 ] += Cosval * Gx5 * Gy2 * Gz5;
pOut[ 80 ] += Cosval * Gx2 * Gy5 * Gz5;
pOut[ 81 ] += Cosval * Gx3 * Gy3 * Gz6;
pOut[ 82 ] += Cosval * Gx3 * Gy6 * Gz3;
pOut[ 83 ] += Cosval * Gx6 * Gy3 * Gz3;
pOut[ 84 ] += Cosval * Gx5 * Gy3 * Gz4;
pOut[ 85 ] += Cosval * Gx3 * Gy5 * Gz4;
pOut[ 86 ] += Cosval * Gx5 * Gy4 * Gz3;
pOut[ 87 ] += Cosval * Gx3 * Gy4 * Gz5;
pOut[ 88 ] += Cosval * Gx4 * Gy5 * Gz3;
pOut[ 89 ] += Cosval * Gx4 * Gy3 * Gz5;
pOut[ 90 ] += Cosval * Gx4 * Gy4 * Gz4;
return std::max(Gx12, std::max(Gy12, Gz12));
}
return -1.;
}
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
#include <stdexcept>
#include <string.h> // for memset
#include "BlockContract.h"
#include "CxAlgebra.h"
#include "TensorTranspose.h"
#include <iostream>
#include <boost/format.hpp>
#ifdef _DEBUG
#include <iostream>
#include <boost/format.hpp>
// some printing stuff which may be helpful in debug mode.
// Not included in default mode because it induces unnecessary dependencies, and
// the host programs probably have own means of printing this kind of stuff anyway.
template<class T>
void IrPrintRow(std::ostream &xout, T const *pData, int iColSt, unsigned nCols, std::string const &FmtF, char const *pEndLn="\n")
{
for (unsigned iCol = 0; iCol < nCols; ++ iCol)
if ( FmtF != "" )
xout << boost::format("%14.6f") % pData[iColSt * iCol];
else
xout << boost::format(FmtF) % pData[iColSt * iCol];
xout << pEndLn;
};
void IrPrintMatrixGen(std::ostream &xout, double *pData, unsigned nRows, unsigned iRowSt, unsigned nCols, unsigned iColSt, std::string const &Caption)
{
using boost::format;
xout << format(" Matrix %s, %i x %i.\n") % Caption % nRows % nCols;
std::string
FmtS = "%14s",
FmtI = "%11i ",
FmtF = "%14.6f";
xout << format(FmtS) % "";
for (unsigned i = 0; i < nCols; ++ i)
xout << " " << format(FmtI) % i;
xout << std::endl;
for (unsigned iRow = 0; iRow < nRows; ++ iRow) {
xout << format(FmtI) % iRow;
IrPrintRow(xout, &pData[iRow*iRowSt], iColSt, nCols, FmtF);
}
xout << std::endl;
};
#endif // _DEBUG
// sanity check: assert that slots A[A0..An] have the same sizes as B[B0..Bn].
static void AssertSlotsCompatible(FNdArrayView const &A, uint A0, uint An,
FNdArrayView const &B, uint B0, uint Bn)
{
assert(An <= A.Rank());
assert(Bn <= B.Rank());
assert(An - A0 == Bn - B0);
for (uint i = 0; i < Bn - B0; ++ i ) {
assert(A.Sizes[A0+i] == B.Sizes[B0+i]);
}
}
static void AssertCompatible(FNdArrayView const &A, FNdArrayView const &B)
{
assert(A.Rank() == B.Rank());
AssertSlotsCompatible(A, 0, A.Rank(), B, 0, B.Rank());
}
static FArrayOffset iStrideCostFn(FArrayOffset iStA, FArrayOffset iStB)
{
if (iStA == 1 || iStB == 1)
return 0;
return iStA + iStB + std::max(iStA,iStB);
}
// ^- this doesn't make sure that we actually get the 1 stride as fastest
// dimension, does it?
static void PermuteSlotPairs(FNdArrayView &A, uint A0, uint An,
FNdArrayView &B, uint B0, uint Bn)
{
assert(An - A0 == Bn - B0);
uint n = An - A0;
for (uint i = 0; i < n; ++ i)
for (uint j = i+1; j < n; ++ j)
if (iStrideCostFn(A.Strides[A0+j], B.Strides[B0+j]) <
iStrideCostFn(A.Strides[A0+i], B.Strides[B0+i]))
{
A.SwapSlots(A0+i, A0+j);
B.SwapSlots(B0+i, B0+j);
}
};
static void MakeLinearStrides0(FArraySizes &Strides, FArraySizes const &Sizes)
{
Strides.push_back(1);
for (uint i = 0; i != Sizes.size(); ++ i)
Strides.push_back(Strides.back() * Sizes[i]);
};
// static void MakeLinearStrides1(FArraySizes &Out, FNdArrayView const &A, uint A0, uint An)
// {
// for (uint i = A0; i != An; ++ i)
// Out.push_back(Out.back() * A.Sizes[i]);
// };
//
//
// static void MakeLinearStrides2(FArraySizes &Out, FNdArrayView const &A,
// bool Trans, uint nSlots0)
// {
// Out.push_back(1);
// if (!Trans) {
// MakeLinearStrides1(Out, A, 0, nSlots0);
// MakeLinearStrides1(Out, A, nSlots0, A.Rank());
// } else {
// MakeLinearStrides1(Out, A, nSlots0, A.Rank());
// MakeLinearStrides1(Out, A, 0, nSlots0);
// }
// }
static void PermuteSlotsAb(FNdArrayView &A, uint nSlots0)
{
FArraySizes
OldSizes = A.Sizes,
OldStrides = A.Strides;
A.Sizes.clear();
A.Strides.clear();
for (uint i = nSlots0; i != OldSizes.size(); ++ i){
A.Sizes.push_back(OldSizes[i]);
A.Strides.push_back(OldStrides[i]);
}
for (uint i = 0; i != nSlots0; ++ i){
A.Sizes.push_back(OldSizes[i]);
A.Strides.push_back(OldStrides[i]);
}
};
static char TrCh(bool Trans) {
return Trans? 'T' : 'N';
}
void ContractFirst(FNdArrayView D, FNdArrayView S, FNdArrayView T,
FScalar Factor, bool Add, ct::FMemoryStack &Mem)
{
// return ContractFirst_Naive(D,S,T,Factor,Add,Mem);
uint
nSlotsL = (S.Rank() + T.Rank() - D.Rank())/2,
nSlotsA = S.Rank() - nSlotsL,
nSlotsB = T.Rank() - nSlotsL;
assert(2*nSlotsL + D.Rank() == S.Rank() + T.Rank());
AssertSlotsCompatible(D,0,nSlotsA, S,nSlotsL,S.Rank());
AssertSlotsCompatible(D,nSlotsA,D.Rank(), T,nSlotsL,T.Rank());
AssertSlotsCompatible(S,0,nSlotsL, T,0,nSlotsL);
// count the dimensions and transpositions.
FArrayOffset
nA = D.nValues(0, nSlotsA),
nB = D.nValues(nSlotsA, nSlotsA+nSlotsB),
nL = S.nValues(0, nSlotsL);
if (nA == 0 || nB == 0 || nL == 0)
// nothing to do here. And if we keep going on, MKL complains
// about zero strides.
return;
// check out which matrix storage format conversion requires the
// least jumping in memory. Effectively we need to decide on the
// 'N'/'T' property of D/S/T, and on the simultaneous permutation
// of A, B, and L indices.
//
// a good thing would be to do as little as possible to whatever
// is the largest tensor. And in particular: if it is possible to
// just let it stand, without actually copying it in memory (by
// transposing the other tensors), this should be attempted.
// This is always possible if the two index subsets are
// non-interleaving.
// But here we only do a simple greedy heuristic for a start [*]
// - Whatever subset of D/S/T has the Strides[i] == 1 slot becomes
// the fast dimension. This decides on the Trans properties:
bool
TransD = true, // 'N': D[A,B], 'T': D[B,A]
TransS = true, // 'N': S[L,A], 'T': S[A,L]
TransT = true; // 'N': T[L,B], 'T': T[B,L]
for (uint i = 0; i < nSlotsL; ++ i)
if (S.Strides[i] == 1) TransS = false;
for (uint i = 0; i < nSlotsL; ++ i)
if (T.Strides[i] == 1) TransT = false;
for (uint i = 0; i < nSlotsA; ++ i)
if (D.Strides[i] == 1) TransD = false;
// - Then the permutations on A/B/L are decided by ordering,
// fn(D.Strides[A], S.Strides[A]),
// fn(D.Strides[B], T.Strides[B]),
// fn(S.Strides[L], T.Strides[L]),
// where fn is some simple function of the two sub-arrays, still
// to be decided ('+', 'min' and 'max' all do the right thing in some
// simple cases. Needs to be tested experimentally I guess)
//
// [*] (in small cases full iteration through all the permutations
// and 8 TransX combinations would also be possible):
// [**] I could also check for the largest directly MxM-able
// subset of the block contraction on the largest tensor (there
// always is one!) and never copy any data unless it is small
// (loop through the rest of the large tensor). Hard to say
// if that would help, though.
PermuteSlotPairs(S,0,nSlotsL, T,0,nSlotsL);
PermuteSlotPairs(S, nSlotsL, S.Rank(), D, 0, nSlotsA);
PermuteSlotPairs(T, nSlotsL, T.Rank(), D, nSlotsA, D.Rank());
// optionally switch A/B, L/A, L/B dimensions of D/S/T
FArraySizes
StridesMxmD, StridesMxmS, StridesMxmT;
if (TransD) PermuteSlotsAb(D, nSlotsA);
if (TransS) PermuteSlotsAb(S, nSlotsL);
if (TransT) PermuteSlotsAb(T, nSlotsL);
// make strides for matrix form of the contraction.
MakeLinearStrides0(StridesMxmD, D.Sizes);
MakeLinearStrides0(StridesMxmS, S.Sizes);
MakeLinearStrides0(StridesMxmT, T.Sizes);
// (copy required? Should check. Note, for example, that for
// actual matrices (2d data) a copy is *never* required.)
// note: I think that if the input data is continuous, a copy is
// not required iff the mxm strides are ascending or descending.
// They are certainly not requred if in ReorderData1A the
// input strides and the output strides are identical.
void
*pBaseOfMemory = Mem.Alloc(0);
FScalar
scalar,
*pMatS = Mem.AllocN(nL * nA, scalar),
*pMatT = Mem.AllocN(nL * nB, scalar),
*pMatD = Mem.AllocN(nA * nB, scalar);
FArrayOffset
ldS = (!TransS)? nL : nA,
ldT = (!TransT)? nL : nB,
ldD = (!TransD)? nA : nB;
// IrPrintMatrixGen(std::cout, S.pData, nL, 1, nA, nL, "ORIG DATA: S");
ReorderData1A(pMatS, S.pData, StridesMxmS, S.Sizes, 1., false, true, &S.Strides);
// IrPrintMatrixGen(std::cout, pMatS, nL, 1, nA, nL, "AFTER TRANSPOSE: S");
// IrPrintMatrixGen(std::cout, T.pData, nL, 1, nB, nL, "ORIG DATA: T");
ReorderData1A(pMatT, T.pData, StridesMxmT, T.Sizes, 1., false, true, &T.Strides);
// IrPrintMatrixGen(std::cout, pMatT, nL, 1, nB, nL, "AFTER TRANSPOSE: T");
if (!TransD) {
FScalar scale1 = 1.0, scale0=0.0;
#ifdef _SINGLE_PRECISION
sgemm_(TrCh(!TransS), TrCh(TransT), nA, nB, nL,
scale1, pMatS, ldS, pMatT, ldT, scale0, pMatD, ldD);
#else
dgemm_(TrCh(!TransS), TrCh(TransT), nA, nB, nL,
scale1, pMatS, ldS, pMatT, ldT, scale0, pMatD, ldD);
#endif
} else {
// cannot directly feed that into dgemm, but note that
// if D^T = A*B, then D = (A*B)^T = B^T * A^T, and this we can.
FScalar scale1 = 1.0, scale0=0.0;
#ifdef _SINGLE_PRECISION
sgemm_(TrCh(!TransT), TrCh(TransS), nB, nA, nL,
scale1, pMatT, ldT, pMatS, ldS, scale0, pMatD, ldD);
#else
dgemm_(TrCh(!TransT), TrCh(TransS), nB, nA, nL,
scale1, pMatT, ldT, pMatS, ldS, scale0, pMatD, ldD);
#endif
}
// IrPrintMatrixGen(std::cout, pMatD, nA, 1, nB, nA, "AFTER MXM: D");
ReorderData1A(D.pData, pMatD, D.Strides, D.Sizes, Factor, Add, true, &StridesMxmD);
// ReorderData1A(pMatD, D.pData, StridesMxmD, D.Sizes, Factor, Add, false, &D.Strides);
// IrPrintMatrixGen(std::cout, D.pData, nA, 1, nB, nA, "AFTER TRANSPOSE: D");
Mem.Free(pBaseOfMemory);
}
// convert logical total array offset (linear strides, no holes) into
// physical total array offset (actual strides)
static size_t i2o(FNdArrayView const &A, FArrayOffset iLogical)
{
FArrayOffset
iOut = 0;
for (uint iSlot = 0; iSlot < A.Rank(); ++ iSlot){
iOut += A.Strides[iSlot] * (iLogical % A.Sizes[iSlot]);
iLogical /= A.Sizes[iSlot];
}
return iOut;
};
void ContractFirst_Naive(FNdArrayView D, FNdArrayView S, FNdArrayView T,
FScalar Factor, bool Add, ct::FMemoryStack &Mem)
{
uint
nSlotsL = (S.Rank() + T.Rank() - D.Rank())/2,
nSlotsA = S.Rank() - nSlotsL,
nSlotsB = T.Rank() - nSlotsL;
FArrayOffset
nA = D.nValues(0, nSlotsA),
nB = D.nValues(nSlotsA, nSlotsA+nSlotsB),
nL = S.nValues(0, nSlotsL);
for (FArrayOffset iA = 0; iA < nA; ++ iA)
for (FArrayOffset iB = 0; iB < nB; ++ iB)
{
FArrayOffset
iOffD = i2o(D, iA + nA * iB);
FScalar
v = 0;
if (Add)
v = D.pData[iOffD];
for (FArrayOffset iL = 0; iL < nL; ++ iL)
{
FArrayOffset
iOffS = i2o(S, iL + nL * iA),
iOffT = i2o(T, iL + nL * iB);
v += Factor * S.pData[iOffS] * T.pData[iOffT];
};
D.pData[iOffD] = v;
}
};
typedef TArrayFix<unsigned char, nMaxRank, unsigned char>
FSlotIndices;
static void Append(FSlotIndices &Out, FSlotIndices const &A)
{
for (uint i = 0; i < A.size(); ++ i)
Out.push_back(A[i]);
};
static void FindCommonIndices(FSlotIndices &IA, FSlotIndices &IB,
char const *pBegA, char const *pEndA, char const *pBegB, char const *pEndB)
{
for (char const *pA = pBegA; pA != pEndA; ++ pA)
for (char const *pB = pBegB; pB != pEndB; ++ pB)
if (*pA == *pB) {
IA.push_back(pA - pBegA);
IB.push_back(pB - pBegB);
break;
}
};
static void PermuteSlots(FNdArrayView &D, FSlotIndices const &PermIn)
{
FArraySizes
OldSizes = D.Sizes,
OldStrides = D.Strides;
for (uint i = 0; i < PermIn.size(); ++ i) {
D.Sizes[i] = OldSizes[PermIn[i]];
D.Strides[i] = OldStrides[PermIn[i]];
}
};
// static void PermuteSlotsDest(FNdArrayView &D, FSlotIndices const &PermIn)
// {
// FArraySizes
// OldSizes = D.Sizes,
// OldStrides = D.Strides;
// for (uint i = 0; i < PermIn.size(); ++ i) {
// D.Sizes[PermIn[i]] = OldSizes[i];
// D.Strides[PermIn[i]] = OldStrides[i];
// }
// };
void ContractBinary(FNdArrayView D, char const *pDecl, FNdArrayView S, FNdArrayView T,
FScalar Factor, bool Add, ct::FMemoryStack &Mem)
{
// indices of A/B/L indices in D/S/T in input. Read from decl.
FSlotIndices
DA,DB, SL,SA, TL,TB;
// find substrings corresponding to the D/S/T parts of the declaration.
char const
*pBegD, *pEndD, *pBegS, *pEndS, *pBegT, *pEndT,
*p = pDecl;
if (false) {
// format: S,T->D
pBegS = p;
for(; *p != 0; ++p)
if (*p == ',') break;
if (*p == 0) throw std::runtime_error("expected ',' in contraction declaration.");
pEndS = p;
++ p;
pBegT = p;
for(; *p != 0; ++p)
if (*p == '-') break;
if (*p == 0 || *(p+1) != '>') throw std::runtime_error("expected '->' in contraction declaration.");
pEndT = p;
p += 2;
pBegD = p;
for(; *p != 0; ++p) {
}
pEndD = p;
} else {
// format: D,S,T
pBegD = p;
for(; *p != 0; ++p)
if (*p == ',') break;
if (*p == 0) throw std::runtime_error("expected ',' in contraction declaration.");
pEndD = p;
++ p;
pBegS = p;
for(; *p != 0; ++p)
if (*p == ',') break;
if (*p == 0) throw std::runtime_error("expected ',' in contraction declaration.");
pEndS = p;
++ p;
pBegT = p;
for(; *p != 0; ++p) {
}
pEndT = p;
}
if (D.Rank() != pEndD - pBegD ||
S.Rank() != pEndS - pBegS ||
T.Rank() != pEndT - pBegT) {
std::cout << boost::format("co-decl: '%s' D: '%s' S: '%s' T: '%s'") % pDecl % std::string(pBegD, pEndD) % std::string(pBegS, pEndS) % std::string(pBegT, pEndT) << std::endl;
throw std::runtime_error("ranks derived from contraction declaration differ from ranks of input tensors.");
}
// match up indices with all their counterparts
FindCommonIndices(DA,SA, pBegD,pEndD, pBegS,pEndS);
FindCommonIndices(DB,TB, pBegD,pEndD, pBegT,pEndT);
FindCommonIndices(SL,TL, pBegS,pEndS, pBegT,pEndT);
if (DA.size() + DB.size() != pEndD - pBegD ||
SL.size() + SA.size() != pEndS - pBegS ||
TL.size() + TB.size() != pEndT - pBegT)
throw std::runtime_error(boost::str(boost::format("unsound index pattern in contraction declaration. Not a binary contraction: %s") % pDecl));
// throw std::runtime_error("unsound index pattern in contraction declaration. Not a binary contraction");
// re-order the tensors into D[A,B] += S[L,A] * T[L,B] form.
FSlotIndices
DAB, SLA, TLB;
Append(DAB, DA); Append(DAB, DB); PermuteSlots(D, DAB);
Append(SLA, SL); Append(SLA, SA); PermuteSlots(S, SLA);
Append(TLB, TL); Append(TLB, TB); PermuteSlots(T, TLB);
// relay to ContractFirst for the actual work.
return ContractFirst(D, S, T, Factor, Add, Mem);
};
static int FindChr(char what, char const *pDecl){
char const *p = pDecl;
for ( ; *p != 0 && *p != ','; ++ p)
if (*p == what) return p - pDecl;
return -1;
}
std::string g_dbgPrefix = ""; // FIXME: REMOVE THIS
// note: (1) Declarations here come as 'dest,s0,s1,s2'. There is no '->', and dest comes first.
void ContractN(FNdArrayView **Ts, char const *pDecl, FScalar Factor, bool Add, ct::FMemoryStack &Mem)
{
void *pBaseOfMemory = Mem.Alloc(0);
bool Print = false;
// find number of terms and boundaries between terms.
uint const nMaxTerms = 32;
uint nTerms = 1;
uint iTerm[nMaxTerms];
iTerm[0] = 0;
{
char const *p;
for (p = pDecl; *p != 0; ++ p){
if (*p == ',') {
iTerm[nTerms] = p - pDecl + 1;
nTerms += 1;
}
}
iTerm[nTerms] = p - pDecl + 1;
}
if (Print) {
std::cout << g_dbgPrefix << boost::format("co-decl: '%s'") % pDecl;
for (uint i = 0; i < nTerms; ++ i)
std::cout << boost::format(" %s[%i]: '%s'") % (i==0?'D':'S') % (i) % std::string(&pDecl[iTerm[i]], &pDecl[iTerm[i+1]]);
std::cout << boost::format(" F: %.5f Add: %i ") % Factor % Add << std::endl;
}
for (uint i = 0; i < nTerms; ++ i)
if ( iTerm[i+1] - iTerm[i] - 1 != Ts[i]->Rank() )
throw std::runtime_error("contraction decl/actual tensor dimension mismatch.");
if (nTerms < 3)
throw std::runtime_error("contractions with less than three terms not supported.");
if (nTerms == 3) {
return ContractBinary(*Ts[0], pDecl, *Ts[1], *Ts[2], Factor, Add, Mem);
}
// count number of distinct and common indices for all tensor pairs.
// Find tensor pair with the smallest number of distinct indices
// and the largest number of common indices.
uint
iBest = 0xffff, jBest = 0xffff;
size_t
DiMin = 0,
CoMax = 0;
for (uint i0 = 0; i0 < nTerms; ++ i0)
for (uint i1 = i0+1; i1 < nTerms; ++ i1) {
size_t
Di = 1,
Co = 1;
for (uint s0 = 0; s0 != Ts[i0]->Rank(); ++ s0)
if (-1 != FindChr(pDecl[iTerm[i0]+s0], &pDecl[iTerm[i1]])) {
// common
Co *= Ts[i0]->Sizes[s0];
// if (Ts[i0]->Sizes[s0] != Ts[i1]->Sizes[s1])
// throw std::runtime_error(boost::format("tensor sizes not consistent: %s") % pDecl);
} else {
// distinct: On T[i0], but not on T[i1]
Di *= Ts[i0]->Sizes[s0];
}
for (uint s1 = 0; s1 != Ts[i1]->Rank(); ++ s1)
if (-1 == FindChr(pDecl[iTerm[i1]+s1], &pDecl[iTerm[i0]]))
// distinct: On T[i1], but not on T[i0]
Di *= Ts[i1]->Sizes[s1];
if (iBest == 0xffff || Di < DiMin || (Di == DiMin && Co > CoMax)) {
// if (iBest == 0) continue; // FIXME: REMOVE THIS.
iBest = i0;
jBest = i1;
DiMin = Di;
CoMax = Co;
}
}
// make new declaration string: remove i0 and i1, and replace by its
// distinct indices.
char
*pDecl1,
*pDecl2,
*pDistinct;
FNdArrayView **Ts1, **Ts2;
uint nTs1 = 0, nDistinct = 0;
Mem.Alloc(pDecl1, iTerm[nTerms]+1);
Mem.Alloc(pDecl2, iTerm[nTerms]+1);
Mem.Alloc(pDistinct, iTerm[nTerms]+1);
Mem.Align(32);
Mem.Alloc(Ts1, nTerms);
Mem.Alloc(Ts2, nTerms);
FNdArrayView
Tmp;
char *q = pDecl2, *p = pDecl1;
for (uint i = 0; i < nTerms; ++ i) {
if (i == iBest) {
// put in the distinct indices between iBest and jBest.
uint i0 = iBest, i1 = jBest;
for (uint s0 = 0; s0 != Ts[i0]->Rank(); ++ s0)
if (-1 == FindChr(pDecl[iTerm[i0]+s0], &pDecl[iTerm[i1]])) {
pDistinct[nDistinct] = pDecl[iTerm[i0]+s0];
*p++ = pDistinct[nDistinct];
++ nDistinct;
Tmp.Sizes.push_back(Ts[i0]->Sizes[s0]);
}
for (uint s1 = 0; s1 != Ts[i1]->Rank(); ++ s1)
if (-1 == FindChr(pDecl[iTerm[i1]+s1], &pDecl[iTerm[i0]])) {
// *p++ = pDecl[iTerm[i1]][s1];
pDistinct[nDistinct] = pDecl[iTerm[i1]+s1];
*p++ = pDistinct[nDistinct];
++ nDistinct;
Tmp.Sizes.push_back(Ts[i1]->Sizes[s1]);
}
Ts1[nTs1] = &Tmp;
nTs1 += 1;
} else if (i == jBest) {
continue;
} else {
// nothing special: replicate original indices.
for (uint s0 = 0; s0 != Ts[i]->Rank(); ++ s0)
*p++ = pDecl[iTerm[i]+s0];
Ts1[nTs1] = Ts[i];
nTs1 += 1;
}
p[0] = ',';
++p;
}
-- p;
p[0] = 0; // remove the trailing ','.
if (Print) {
std::cout << g_dbgPrefix << boost::format("co-pair: i = %i j = %i distinct: '%s' Co = %i Di = %i")
% iBest % jBest % std::string(pDistinct,pDistinct+nDistinct) % CoMax % DiMin << std::endl;
}
// allocate intermediate contraction result.
// Tmp.Strides.push_back(1);
Tmp.Strides.resize(Tmp.Sizes.size()+1);
Tmp.Strides[0] = 1;
// for (uint i = 1; i < Tmp.Rank(); ++ i)
// Tmp.Strides[i] = Tmp.Strides[i-1] * Tmp.Sizes[i-1];
// Mem.Alloc(Tmp.pData, Tmp.nValues());
for (uint i = 0; i < Tmp.Rank(); ++ i)
Tmp.Strides[i+1] = Tmp.Strides[i] * Tmp.Sizes[i];
Mem.Alloc(Tmp.pData, Tmp.Strides[Tmp.Rank()]);
assert(Tmp.Strides[Tmp.Rank()] == Tmp.nValues());
if (iBest == 0) {
// factorization involves output tensor. need to make other stuff
// first (Tmp) and then contract current result to final output.
assert(Ts1[0] == &Tmp);
// std::string s0 = g_dbgPrefix;
// g_dbgPrefix = s0 + "RHS ";
ContractN(Ts1, pDecl1, 1., false, Mem);
Ts2[0] = Ts[iBest];
Ts2[1] = Ts[jBest];
Ts2[2] = &Tmp;
for (uint s0 = 0; s0 < Ts2[0]->Rank(); ++ s0) *q++ = pDecl[iTerm[iBest]+s0]; *q++ = ',';
for (uint s0 = 0; s0 < Ts2[1]->Rank(); ++ s0) *q++ = pDecl[iTerm[jBest]+s0]; *q++ = ',';
for (uint s0 = 0; s0 < Ts2[2]->Rank(); ++ s0) *q++ = pDistinct[s0];
q[0] = 0; // null-terminate.
// g_dbgPrefix = s0 + "TMP ";
ContractN(Ts2, pDecl2, Factor, Add, Mem);
// g_dbgPrefix = s0;
} else {
// factorization on rhs only.
assert(Ts1[0] != &Tmp);
Ts2[0] = &Tmp;
Ts2[1] = Ts[iBest];
Ts2[2] = Ts[jBest];
for (uint s0 = 0; s0 < Ts2[0]->Rank(); ++ s0) *q++ = pDistinct[s0]; *q++ = ',';
for (uint s0 = 0; s0 < Ts2[1]->Rank(); ++ s0) *q++ = pDecl[iTerm[iBest]+s0]; *q++ = ',';
for (uint s0 = 0; s0 < Ts2[2]->Rank(); ++ s0) *q++ = pDecl[iTerm[jBest]+s0];
q[0] = 0; // null-terminate.
std::string s0 = g_dbgPrefix;
// g_dbgPrefix = s0 + "TMP ";
ContractN(Ts2, pDecl2, 1., false, Mem);
// g_dbgPrefix = s0 + "RST ";
ContractN(Ts1, pDecl1, Factor, Add, Mem);
// g_dbgPrefix = s0;
}
Mem.Free(pBaseOfMemory);
}
void ContractN(FNdArrayView Out, char const *pDecl, FScalar Factor, bool Add, ct::FMemoryStack &Mem,
FNdArrayView *pT1, FNdArrayView *pT2, FNdArrayView *pT3, FNdArrayView *pT4, FNdArrayView *pT5,
FNdArrayView *pT6, FNdArrayView *pT7, FNdArrayView *pT8)
{
FNdArrayView *pTs[9] = {&Out, pT1, pT2, pT3, pT4, pT5, pT6, pT7, pT8};
ContractN(pTs, pDecl, Factor, Add, Mem);
}
void ContractN(FNdArrayView Out, char const *pDecl, FScalar Factor, bool Add, ct::FMemoryStack &Mem,
FNdArrayView const &T1, FNdArrayView const &T2, FNdArrayView const &T3, FNdArrayView const &T4,
FNdArrayView const &T5, FNdArrayView const &T6, FNdArrayView const &T7, FNdArrayView const &T8)
{
#define XCONV(TN) const_cast<FNdArrayView*>(&TN)
FNdArrayView *pTs[9] = {&Out, XCONV(T1), XCONV(T2), XCONV(T3), XCONV(T4), XCONV(T5), XCONV(T6), XCONV(T7), XCONV(T8)};
ContractN(pTs, pDecl, Factor, Add, Mem);
#undef XCONV
}
void Copy(FNdArrayView &Out, FNdArrayView const &In)
{
// NOTE: if this becomes a problem, do it in a slightly less insanely
// stupid manner. i2o was not actually intended to be used in real code.
//AssertCompatible(Out, In);
FArrayOffset
N = Out.nValues();
for (size_t i = 0; i != N; ++ i)
Out.pData[i2o(Out,i)] = In.pData[i2o(In,i)];
};
void FNdArrayView::ClearData()
{
// FIXME: will do the wrong thing (tm) if used on a non-continuous tensor.
FArrayOffset
TrialStride = 1;
for (uint i = 0; i < Rank(); ++ i){
// check for each stride which would occur in linear addressing if
// it occurs somewhere in the actual set of strides.
// (nah.. that's not really right, is it? but will work for direct
// linear storage pattern, so I leave it for the moment)
bool Found = false;
for (uint j = 0; j < Rank(); ++ j)
if (Strides[i] == TrialStride)
Found = true;
if (!Found)
throw std::runtime_error("ClearData() not implemented for non-continuous tensors.");
TrialStride *= Sizes[i];
}
memset(pData, 0, nValues() * sizeof(pData[0]));
};
<file_sep>#pragma once
double getHermiteReciprocal(int l, double* pout,
double Gx, double Gy, double Gz,
double Tx, double Ty, double Tz,
double exponentVal,
double Scale) ;
<file_sep>/*
Developed by <NAME> and <NAME>, 2016
Copyright (c) 2016, <NAME>
*/
/* This program is not yet in a release condition and should not be distributed.
* Author: <NAME>, Aug. 2013.
*/
#define INDENTSTREAM_IMPL
#include "CxIndentStream.h"
namespace fmt {
char const
*const g_pSpaces = " ";
int
g_IndentIndex = 0,
g_PreIndentIndex = 0;
bool
g_IndentIndexInitialized = false;
void InitIndentStreamBuf()
{
static int s_IndentIndex = std::ios_base::xalloc();
g_IndentIndex = s_IndentIndex;
// ^- explicit initizalization routine to avoid static initialization hell problems.
}
template<class FChar>
int TIndentStreamBuf<FChar>::sync() throw()
{
long
IndentLevel = 1;
std::basic_string<FChar>
*pPreIndentStr=NULL;
if ( 0 != m_pParentStream ) {
IndentLevel = m_pParentStream->iword(g_IndentIndex);
void *p = m_pParentStream->pword(g_PreIndentIndex);
pPreIndentStr = reinterpret_cast<std::basic_string<FChar>*>(p);
}
FBase::sync();
/* FChar
*pFirst = this->pbase(),
*pLast = pFirst,
*pEnd = this->pptr();*/
std::string const
&_str = this->str();
// ^- this makes a copy. not good. Here because pgcc bypasses the
// output buffer and directly constructs the output string under
// certain circumstances (it is allowed to do that).
FChar const
*pFirst = &_str[0],
*pLast = pFirst,
*pEnd = pFirst + _str.size();
for ( ; pLast != pEnd; pFirst = pLast ){
// emit indentation characters, unless line is empty.
if ( *pFirst != '\n' ) {
if ( pPreIndentStr )
m_Target.sputn(&*pPreIndentStr->begin(), pPreIndentStr->size());
for ( uint i = 0; i < static_cast<uint>(IndentLevel); ++ i )
m_Target.sputn(m_pIndentStr, m_IndentLength);
}
while ( (pLast != pEnd) && (*pLast != '\n') )
++pLast;
if ( pLast != pEnd )
++pLast;
m_Target.sputn(pFirst, pLast-pFirst);
}
m_Target.pubsync();
FBase::sync();
// clear the line buffer. Current input is not required anymore.
this->str(m_EmptyString);
return 0;
}
template<class FChar>
TIndentStreamBuf<FChar>::~TIndentStreamBuf() throw()
{
}
template class TIndentStream1<char>;
} // namespace fmt
// kate: space-indent on; indent-width 3; indent-mode normal;
<file_sep>#include "sr.h"
#include <Eigen/Dense>
#include "global.h"
#ifndef SERIAL
#include "mpi.h"
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>
#endif
using namespace Eigen;
using namespace boost;
void ConjGrad(DirectMetric &A, VectorXd &b, int n, VectorXd &x)
{
double tol = 1.e-10;
VectorXd Ap = VectorXd::Zero(x.rows());
A.multiply(x, Ap);
VectorXd r = b - Ap;
VectorXd p = r;
double rsold = r.adjoint() * r;
if (fabs(rsold) < tol) return;
for (int i = 0; i < n; i++)
{
A.multiply(p, Ap);
double pAp = p.adjoint() * Ap;
double alpha = rsold / pAp;
x = x + alpha * p;
r = r - alpha * Ap;
double rsnew = r.adjoint() * r;
double beta = rsnew / rsold;
rsold = rsnew;
p = r + beta*p;
}
}
void PInv(MatrixXd &A, MatrixXd &Ainv)
{
SelfAdjointEigenSolver<MatrixXd> es;
es.compute(A);
std::vector<int> cols;
for (int m = 0; m < A.cols(); m++)
{
if (fabs(es.eigenvalues()(m)) > 1.e-10)
{
cols.push_back(m);
}
}
MatrixXd U = MatrixXd::Zero(A.rows(), cols.size());
MatrixXd eig_inv = MatrixXd::Zero(cols.size(),cols.size());
for (int m = 0; m < cols.size(); m++)
{
int index = cols[m];
U.col(m) = es.eigenvectors().col(index);
double eigval = es.eigenvalues()(index);
eig_inv(m,m) = 1.0 / eigval;
}
Ainv = U * eig_inv * U.adjoint();
}
<file_sep>/*
Developed by <NAME> with contributions from <NAME> and <NAME>, 2017
Copyright (c) 2017, <NAME>
This file is part of DICE.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef WalkerHelper_HEADER_H
#define WalkerHelper_HEADER_H
#include <unordered_set>
#include "Determinants.h"
#include "igl/slice.h"
#include "igl/slice_into.h"
#include "ShermanMorrisonWoodbury.h"
#include "Slater.h"
#include "MultiSlater.h"
#include "AGP.h"
#include "Pfaffian.h"
#include "CPS.h"
#include "Jastrow.h"
#include "Gutzwiller.h"
#include "RBM.h"
#include "JRBM.h"
template<typename Reference>
class WalkerHelper {
};
template<>
class WalkerHelper<Slater>
{
public:
HartreeFock hftype; //hftype same as that in slater
std::array<MatrixXcd, 2> thetaInv; //inverse of the theta matrix
std::vector<std::array<complex<double>, 2>> thetaDet; //determinant of the theta matrix, vector for multidet
std::array<vector<int>, 2> openOrbs; //set of open orbitals in the walker
std::array<vector<int>, 2> closedOrbs; //set of closed orbitals in the walker
std::array<vector<int>, 2> closedOrbsRef; //set of closed orbitals in the reference (zeroth det)
std::vector<std::array<MatrixXcd, 2>> rTable; //table used for efficiently, vector for multidet
WalkerHelper() {};
WalkerHelper(const Slater &w, const Determinant &d)
{
hftype = w.hftype;
//fill the spin strings for the walker and the zeroth reference det
fillOpenClosedOrbs(d);
closedOrbsRef[0].clear();
closedOrbsRef[1].clear();
w.getDeterminants()[0].getClosedAlphaBeta(closedOrbsRef[0], closedOrbsRef[1]);
rTable.resize(w.getNumOfDets());
thetaDet.resize(w.getNumOfDets());
if (hftype == Generalized) {
initInvDetsTablesGhf(w);
}
else {
initInvDetsTables(w);
}
}
void fillOpenClosedOrbs(const Determinant &d)
{
openOrbs[0].clear();
openOrbs[1].clear();
closedOrbs[0].clear();
closedOrbs[1].clear();
d.getOpenClosedAlphaBeta(openOrbs[0], closedOrbs[0], openOrbs[1], closedOrbs[1]);
}
void makeTable(const Slater &w, const MatrixXcd& inv, const Eigen::Map<VectorXi>& colClosed, int detIndex, bool sz)
{
Map<VectorXi> rowOpen(&openOrbs[sz][0], openOrbs[sz].size());
rTable[detIndex][sz] = MatrixXcd::Zero(openOrbs[sz].size(), closedOrbs[sz].size());
MatrixXcd HfopenTheta;
igl::slice(w.getHforbs(sz), rowOpen, colClosed, HfopenTheta);
rTable[detIndex][sz] = HfopenTheta * inv;
}
//void calcOtherDetsTables(const Slater& w, bool sz)
//{
// Eigen::Map<VectorXi> rowClosed(&closedOrbs[sz][0], closedOrbs[sz].size());
// vector<int> cre(closedOrbs[sz].size(), -1), des(closedOrbs[sz].size(), -1);
// for (int x = 1; x < w.getNumOfDets(); x++) {
// MatrixXcd invCurrent;
// vector<int> ref;
// w.getDeterminants()[x].getClosed(sz, ref);
// Eigen::Map<VectorXi> colClosed(&ref[0], ref.size());
// getDifferenceInOccupation(w.getDeterminants()[x], w.getDeterminants()[0], cre, des, sz);
// double parity = w.getDeterminants()[0].parity(cre, des, sz);
// calculateInverseDeterminantWithColumnChange(thetaInv[sz], thetaDet[0][sz], invCurrent, thetaDet[x][sz], cre, des, rowClosed, closedOrbsRef[sz], w.getHforbs(sz));
// thetaDet[x][sz] *= parity;
// makeTable(w, invCurrent, colClosed, x, sz);
// }
//}
//commenting out calcotherdetstables, uncomment for multidet
void initInvDetsTables(const Slater &w)
{
int norbs = Determinant::norbs;
for (int sz = 0; sz < 2; sz++) {
Eigen::Map<VectorXi> rowClosed(&closedOrbs[sz][0], closedOrbs[sz].size());
Eigen::Map<VectorXi> colClosed(&closedOrbsRef[sz][0], closedOrbsRef[sz].size());
MatrixXcd theta;
igl::slice(w.getHforbs(sz), rowClosed, colClosed, theta);
Eigen::FullPivLU<MatrixXcd> lua(theta);
if (lua.isInvertible()) {
thetaInv[sz] = lua.inverse();
thetaDet[0][sz] = lua.determinant();
}
else {
cout << sz << " overlap with determinant not invertible" << endl;
exit(0);
}
rTable[0][sz] = MatrixXcd::Zero(norbs, closedOrbs[sz].size());
rTable[0][sz] = w.getHforbs(sz).block(0, 0, norbs, closedOrbs[sz].size()) * thetaInv[sz];
//makeTable(w, thetaInv[sz], colClosed, 0, sz);
//calcOtherDetsTables(w, sz);
}
}
void concatenateGhf(const vector<int>& v1, const vector<int>& v2, vector<int>& result) const
{
int norbs = Determinant::norbs;
result.clear();
result = v1;
result.insert(result.end(), v2.begin(), v2.end());
for (int j = v1.size(); j < v1.size() + v2.size(); j++)
result[j] += norbs;
}
void makeTableGhf(const Slater &w, const Eigen::Map<VectorXi>& colTheta)
{
rTable[0][0] = MatrixXcd::Zero(openOrbs[0].size() + openOrbs[1].size(), closedOrbs[0].size() + closedOrbs[1].size());
MatrixXcd ghfOpen;
vector<int> rowVec;
concatenateGhf(openOrbs[0], openOrbs[1], rowVec);
Eigen::Map<VectorXi> rowOpen(&rowVec[0], rowVec.size());
igl::slice(w.getHforbs(), rowOpen, colTheta, ghfOpen);
rTable[0][0] = ghfOpen * thetaInv[0];
rTable[0][1] = rTable[0][0];
}
void initInvDetsTablesGhf(const Slater &w)
{
int norbs = Determinant::norbs;
vector<int> workingVec0, workingVec1;
concatenateGhf(closedOrbs[0], closedOrbs[1], workingVec0);
Eigen::Map<VectorXi> rowTheta(&workingVec0[0], workingVec0.size());
concatenateGhf(closedOrbsRef[0], closedOrbsRef[1], workingVec1);
Eigen::Map<VectorXi> colTheta(&workingVec1[0], workingVec1.size());
MatrixXcd theta;
igl::slice(w.getHforbs(), rowTheta, colTheta, theta);
Eigen::FullPivLU<MatrixXcd> lua(theta);
if (lua.isInvertible()) {
thetaInv[0] = lua.inverse();
thetaDet[0][0] = lua.determinant();
}
else {
Eigen::Map<VectorXi> v1(&closedOrbs[0][0], closedOrbs[0].size());
Eigen::Map<VectorXi> v2(&closedOrbs[1][0], closedOrbs[1].size());
cout << "alphaClosed\n" << v1 << endl << endl;
cout << "betaClosed\n" << v2 << endl << endl;
cout << "col\n" << colTheta << endl << endl;
cout << theta << endl << endl;
cout << "overlap with theta determinant not invertible" << endl;
exit(0);
}
thetaDet[0][1] = 1.;
rTable[0][0] = MatrixXcd::Zero(2*norbs, closedOrbs[0].size() + closedOrbs[1].size());
rTable[0][0] = w.getHforbs().block(0, 0, 2*norbs, closedOrbs[0].size() + closedOrbs[1].size()) * thetaInv[0];
rTable[0][1] = rTable[0][0];
//makeTableGhf(w, colTheta);
}
//commenting out calcotherdetstables, uncomment for multidet
void excitationUpdate(const Slater &w, vector<int>& cre, vector<int>& des, bool sz, double parity, const Determinant& excitedDet)
{
MatrixXcd invOld = thetaInv[sz];
std::complex<double> detOld = thetaDet[0][sz];
MatrixXcd tableOld = rTable[0][sz];
Eigen::Map<Eigen::VectorXi> colClosed(&closedOrbsRef[sz][0], closedOrbsRef[sz].size());
calculateInverseDeterminantWithRowChange(invOld, detOld, tableOld, thetaInv[sz], thetaDet[0][sz], rTable[0][sz], cre, des, colClosed, closedOrbs[sz], w.getHforbs(sz), 1);
thetaDet[0][sz] *= parity;
fillOpenClosedOrbs(excitedDet);
//makeTable(w, thetaInv[sz], colClosed, 0, sz);
//calcOtherDetsTables(w, sz);
}
void excitationUpdateGhf(const Slater &w, vector<int>& cre, vector<int>& des, bool sz, double parity, const Determinant& excitedDet)
{
vector<int> colVec;
concatenateGhf(closedOrbsRef[0], closedOrbsRef[1], colVec);
Eigen::Map<VectorXi> colTheta(&colVec[0], colVec.size());
vector<int> rowIn;
concatenateGhf(closedOrbs[0], closedOrbs[1], rowIn);
MatrixXcd invOld = thetaInv[0];
std::complex<double> detOld = thetaDet[0][0];
MatrixXcd tableOld = rTable[0][0];
calculateInverseDeterminantWithRowChange(invOld, detOld, tableOld, thetaInv[0], thetaDet[0][0], rTable[0][0], cre, des, colTheta, rowIn, w.getHforbs(), 1);
rTable[0][1] = rTable[0][0];
thetaDet[0][0] *= parity;
fillOpenClosedOrbs(excitedDet);
//makeTableGhf(w, colTheta);
}
void getRelIndices(int i, int &relI, int a, int &relA, bool sz) const
{
//relI = std::lower_bound(closedOrbs[sz].begin(), closedOrbs[sz].end(), i) - closedOrbs[sz].begin();
//relA = std::lower_bound(openOrbs[sz].begin(), openOrbs[sz].end(), a) - openOrbs[sz].begin();
int factor = 0;
if (hftype == 2 && sz != 0) factor = 1;
relI = std::search_n(closedOrbs[sz].begin(), closedOrbs[sz].end(), 1, i) - closedOrbs[sz].begin() + factor * closedOrbs[0].size();
//relA = std::search_n(openOrbs[sz].begin(), openOrbs[sz].end(), 1, a) - openOrbs[sz].begin() + factor * openOrbs[0].size();
relA = a + factor * Determinant::norbs;
}
};
template<>
class WalkerHelper<MultiSlater>
{
public:
MatrixXcd t; // A^{-1}
complex<double> refOverlap; // < n | phi_0 >
std::vector<double> ciOverlaps; // Re (< n | phi_i >), include parity
double totalOverlap; // Re (< n | psi >)
std::vector<complex<double>> ciOverlapRatios; // < n | phi_i > / < n | phi_0 >, include parity, for orb gradient
complex<double> totalComplexOverlap; // < n | psi >, for orb gradient
std::vector<int> closedOrbs, openOrbs; // set of closed and open orbitals in the walker
MatrixXcd r, c, b, rt, tc, rtc_b; // intermediate tables
vector<Matrix4cd> tcSlice; // intermediate tables
WalkerHelper() {};
WalkerHelper(const MultiSlater &w, const Determinant &d)
{
//fill the closed orbs for the walker
closedOrbs.clear();
openOrbs.clear();
vector<int> closedBeta, openBeta;
d.getOpenClosedAlphaBeta(openOrbs, closedOrbs, openBeta, closedBeta);
for (int& c_i : closedBeta) c_i += Determinant::norbs;
for (int& o_i : openBeta) o_i += Determinant::norbs;
closedOrbs.insert(closedOrbs.end(), closedBeta.begin(), closedBeta.end());
openOrbs.insert(openOrbs.end(), openBeta.begin(), openBeta.end());
initInvDetsTables(w);
if (commrank == 0) {
if (refOverlap.real() == 0 || totalOverlap == 0) {
cout << "refOverlap = " << refOverlap << ", totalOverlap = " << totalOverlap << endl;
cout << "walker det: " << d << endl;
cout << "ciOverlaps\n";
for (double ci: ciOverlaps) cout << ci << endl;
}
}
}
void initInvDetsTables(const MultiSlater &w)
{
int norbs = Determinant::norbs;
// inverse and refDet
MatrixXcd a;
Eigen::Map<VectorXi> occRows(&closedOrbs[0], closedOrbs.size());
auto refCopy = w.ref;
Eigen::Map<VectorXi> occColumns(&refCopy[0], refCopy.size());
igl::slice(w.getHforbs(), occRows, occColumns, a);
Eigen::FullPivLU<MatrixXcd> lua(a);
if (lua.isInvertible()) {
t = lua.inverse();
refOverlap = lua.determinant();
}
else {
if (commrank == 0) {
cout << "overlap with zeroth determinant not invertible" << endl;
cout << "occRows\n" << occRows.transpose() << endl;
cout << "occColumns\n" << occColumns.transpose() << endl;
cout << "a\n" << a << endl;
cout << "w.Hforbs\n" << w.Hforbs << endl;
}
#ifndef SERIAL
MPI_Barrier(MPI_COMM_WORLD);
#endif
exit(0);
}
// tables
// TODO: change table structure so that only unoccupied orbitals are present in r and c,
// this is not done currently because table updates are easier with all orbitals, but leads to bigger tables
//VectorXi all = VectorXi::LinSpaced(2*norbs, 0, 2*norbs - 1);
auto openCopy = w.open;
Eigen::Map<VectorXi> openColumns(&openCopy[0], openCopy.size());
Eigen::Map<VectorXi> openRows(&openOrbs[0], openOrbs.size());
//igl::slice(w.getHforbs(), all, occColumns, r);
//igl::slice(w.getHforbs(), occRows, all, c);
igl::slice(w.getHforbs(), openRows, occColumns, r);
igl::slice(w.getHforbs(), occRows, openColumns, c);
igl::slice(w.getHforbs(), openRows, openColumns, b);
rt = r * t;
tc = t * c;
rtc_b = rt * c - b;
//rtc_b = rt * c - w.getHforbs();
// overlaps with phi_i
ciOverlaps.clear();
ciOverlapRatios.clear();
ciOverlaps.push_back(refOverlap.real());
ciOverlapRatios.push_back(1.);
totalOverlap = w.ciCoeffs[0] * ciOverlaps[0];
totalComplexOverlap = w.ciCoeffs[0] * refOverlap;
for (int i = 1; i < w.numDets; i++) {
if (w.ciExcitations[i][0].size() == 4) {
Matrix4cd sliceMat;
igl::slice(tc, w.ciExcitations[i][0], w.ciExcitations[i][1], sliceMat);
tcSlice.push_back(sliceMat);
complex<double> ratio = sliceMat.determinant() * complex<double>(w.ciParity[i]);
ciOverlapRatios.push_back(ratio);
ciOverlaps.push_back((ratio * refOverlap).real());
totalOverlap += w.ciCoeffs[i] * ciOverlaps[i];
totalComplexOverlap += w.ciCoeffs[i] * ratio * refOverlap;
}
else {
MatrixXcd sliceMat;
igl::slice(tc, w.ciExcitations[i][0], w.ciExcitations[i][1], sliceMat);
complex<double> ratio = calcDet(sliceMat) * complex<double>(w.ciParity[i]);
ciOverlapRatios.push_back(ratio);
ciOverlaps.push_back((ratio * refOverlap).real());
totalOverlap += w.ciCoeffs[i] * ciOverlaps[i];
totalComplexOverlap += w.ciCoeffs[i] * ratio * refOverlap;
}
}
}
void excitationUpdate(const MultiSlater &w, vector<int>& cre, vector<int>& des, bool sz, double parity, const Determinant& excitedDet)
{
// <NAME> to update inverse
// right now only table rt is updated efficiently
auto refCopy = w.ref;
Eigen::Map<VectorXi> occColumns(&refCopy[0], refCopy.size());
MatrixXcd tOld = t;
complex<double> overlapOld = refOverlap;
MatrixXcd rtOld = rt;
calculateInverseDeterminantWithRowChange(tOld, overlapOld, rtOld, t, refOverlap, rt, cre, des, occColumns, closedOrbs, w.getHforbs(), 0);
refOverlap *= parity;
int norbs = Determinant::norbs;
closedOrbs.clear();
openOrbs.clear();
vector<int> closedBeta, openBeta;
excitedDet.getOpenClosedAlphaBeta(openOrbs, closedOrbs, openBeta, closedBeta);
for (int& c_i : closedBeta) c_i += norbs;
for (int& o_i : openBeta) o_i += norbs;
closedOrbs.insert(closedOrbs.end(), closedBeta.begin(), closedBeta.end());
openOrbs.insert(openOrbs.end(), openBeta.begin(), openBeta.end());
// TODO: these tables also need efficient updates
auto openCopy = w.open;
Eigen::Map<VectorXi> openColumns(&openCopy[0], openCopy.size());
Eigen::Map<VectorXi> occRows(&closedOrbs[0], closedOrbs.size());
Eigen::Map<VectorXi> openRows(&openOrbs[0], openOrbs.size());
//VectorXi all = VectorXi::LinSpaced(2*norbs, 0, 2*norbs - 1);
igl::slice(w.getHforbs(), openRows, occColumns, r);
igl::slice(w.getHforbs(), occRows, openColumns, c);
igl::slice(w.getHforbs(), openRows, openColumns, b);
rt = r * t;
tc = t * c;
rtc_b = rt * c - b;
//rtc_b = rt * c - w.getHforbs();
// overlaps with phi_i
ciOverlaps.clear();
ciOverlapRatios.clear();
ciOverlaps.push_back(refOverlap.real());
ciOverlapRatios.push_back(1.);
totalOverlap = w.ciCoeffs[0] * ciOverlaps[0];
totalComplexOverlap = w.ciCoeffs[0] * refOverlap;
size_t count4 = 0;
for (int j = 1; j < w.numDets; j++) {
int rank = w.ciExcitations[j][0].size();
complex<double> sliceDet;
if (rank == 1) sliceDet = tc(w.ciExcitations[j][0][0], w.ciExcitations[j][1][0]);
else if (rank == 2) sliceDet = tc(w.ciExcitations[j][0][0], w.ciExcitations[j][1][0]) * tc(w.ciExcitations[j][0][1], w.ciExcitations[j][1][1])
- tc(w.ciExcitations[j][0][0], w.ciExcitations[j][1][1]) * tc(w.ciExcitations[j][0][1], w.ciExcitations[j][1][0]);
else if (rank == 3) {
//igl::slice(tc, w.ciExcitations[j][0], w.ciExcitations[j][1], sliceMat);
Matrix3cd tcSlice;
for (int mu = 0; mu < 3; mu++)
for (int nu = 0; nu < 3; nu++)
tcSlice(mu, nu) = tc(w.ciExcitations[j][0][mu], w.ciExcitations[j][1][nu]);
//sliceDet = calcDet(sliceMat);
sliceDet = tcSlice.determinant();
}
else if (rank == 4) {
//igl::slice(tc, w.ciExcitations[j][0], w.ciExcitations[j][1], sliceMat);
for (int mu = 0; mu < 4; mu++)
for (int nu = 0; nu < 4; nu++)
tcSlice[count4](mu, nu) = tc(w.ciExcitations[j][0][mu], w.ciExcitations[j][1][nu]);
//sliceDet = calcDet(sliceMat);
sliceDet = tcSlice[count4].determinant();
count4++;
}
else {
MatrixXcd sliceMat = MatrixXcd::Zero(rank, rank);
//igl::slice(tc, w.ciExcitations[j][0], w.ciExcitations[j][1], sliceMat);
for (int mu = 0; mu < rank; mu++)
for (int nu = 0; nu < rank; nu++)
sliceMat(mu, nu) = tc(w.ciExcitations[j][0][mu], w.ciExcitations[j][1][nu]);
sliceDet = sliceMat.determinant();
}
ciOverlaps.push_back((sliceDet * refOverlap).real() * w.ciParity[j]);
ciOverlapRatios.push_back(sliceDet * complex<double>(w.ciParity[j]));
totalOverlap += w.ciCoeffs[j] * ciOverlaps[j];
totalComplexOverlap += w.ciCoeffs[j] * ciOverlapRatios[j] * refOverlap;
}
if (commrank == 0) {
if (refOverlap.real() == 0 || totalOverlap == 0) {
cout << "refOverlap = " << refOverlap << ", totalOverlap = " << totalOverlap << endl;
cout << "walker det: " << excitedDet << endl;
cout << "ciOverlaps\n";
for (double ci: ciOverlaps) cout << ci << endl;
}
}
}
void getRelIndices(int i, int &relI, int a, int &relA, bool sz) const
{
//relI = std::lower_bound(closedOrbs[sz].begin(), closedOrbs[sz].end(), i) - closedOrbs[sz].begin();
relI = std::search_n(closedOrbs.begin(), closedOrbs.end(), 1, i + sz * Determinant::norbs) - closedOrbs.begin();
relA = std::search_n(openOrbs.begin(), openOrbs.end(), 1, a + sz * Determinant::norbs) - openOrbs.begin();
//relA = a + sz * Determinant::norbs;
}
};
//template<>
//class WalkerHelper<BFSlater>
//{
//
// public:
// HartreeFock hftype; //hftype same as that in slater
// std::array<MatrixXcd, 2> theta;
// std::array<MatrixXcd, 2> thetaInv; //inverse of the theta matrix
// std::array<complex<double>, 2> thetaDet; //determinant of the theta matrix
// std::array<vector<int>, 2> openOrbs; //set of open orbitals in the walker
// std::array<vector<int>, 2> closedOrbs; //set of closed orbitals in the walker
// std::vector<int> doublons, holons; //doubly occupied and empty spatial orbs
// std::array<vector<int>, 2> closedOrbsRef; //set of closed orbitals in the reference
// std::array<MatrixXcd, 2> rTable; //table used for efficiently
//
// WalkerHelper() {};
//
// WalkerHelper(const BFSlater &w, const Determinant &d)
// {
// hftype = w.hftype;
//
// fillOccupancyHelpers(d);
// closedOrbsRef[0].clear();
// closedOrbsRef[1].clear();
// w.det.getClosedAlphaBeta(closedOrbsRef[0], closedOrbsRef[1]);
//
// if (hftype == Generalized) {
// initInvDetsTablesGhf(w);
// }
// else {
// initInvDetsTables(w);
// }
// }
//
// void fillOccupancyHelpers(const Determinant &d)
// {
// //fill the spin strings for the walker
// openOrbs[0].clear();
// openOrbs[1].clear();
// closedOrbs[0].clear();
// closedOrbs[1].clear();
// d.getOpenClosedAlphaBeta(openOrbs[0], closedOrbs[0], openOrbs[1], closedOrbs[1]);
//
// //fill holons and doublons
// doublons.clear();
// holons.clear();
// set_intersection(closedOrbs[0].begin(), closedOrbs[0].end(), closedOrbs[1].begin(), closedOrbs[1].end(), back_inserter(doublons));
// set_intersection(openOrbs[0].begin(), openOrbs[0].end(), openOrbs[1].begin(), openOrbs[1].end(), back_inserter(holons));
// }
//
// void initInvDetsTables(const BFSlater &w)
// {
// int norbs = Determinant::norbs;
// for (int sz = 0; sz < 2; sz++) {
// Eigen::Map<VectorXi> rowClosed(&closedOrbs[sz][0], closedOrbs[sz].size());
// Eigen::Map<VectorXi> colClosed(&closedOrbsRef[sz][0], closedOrbsRef[sz].size());
// MatrixXcd hforbs = w.getHforbs(sz);
// igl::slice(hforbs, rowClosed, colClosed, theta[sz]);
// for (int i = 0; i < doublons.size(); i++) {
// int relIndex = std::search_n(closedOrbs[sz].begin(), closedOrbs[sz].end(), 1, doublons[i]) - closedOrbs[sz].begin();
// for (int j = 0; j < holons.size(); j++) {
// theta[sz].row(relIndex) += w.bf(i, j) * hforbs.row(holons(j));
// }
// }
//
// Eigen::FullPivLU<MatrixXcd> lua(theta[sz]);
// if (lua.isInvertible()) {
// thetaInv[sz] = lua.inverse();
// thetaDet[sz] = lua.determinant();
// }
// else {
// cout << sz << " overlap with determinant not invertible" << endl;
// exit(0);
// }
//
// rTable[sz] = MatrixXcd::Zero(norbs, closedOrbs[sz].size());
// rTable[sz] = hforbs.block(0, 0, norbs, closedOrbs[sz].size()) * thetaInv[sz];
// }
// }
//
// void concatenateGhf(const vector<int>& v1, const vector<int>& v2, vector<int>& result) const
// {
// int norbs = Determinant::norbs;
// result.clear();
// result = v1;
// result.insert(result.end(), v2.begin(), v2.end());
// for (int j = v1.size(); j < v1.size() + v2.size(); j++)
// result[j] += norbs;
// }
//
// void initInvDetsTablesGhf(const BFSlater &w)
// {
// int norbs = Determinant::norbs;
// vector<int> workingVec0, workingVec1;
// concatenateGhf(closedOrbs[0], closedOrbs[1], workingVec0);
// Eigen::Map<VectorXi> rowTheta(&workingVec0[0], workingVec0.size());
// concatenateGhf(closedOrbsRef[0], closedOrbsRef[1], workingVec1);
// Eigen::Map<VectorXi> colTheta(&workingVec1[0], workingVec1.size());
//
// MatrixXcd hforbs = w.getHforbs();
// igl::slice(hforbs, rowTheta, colTheta, theta[0]);
// for (int i = 0; i < doublons.size(); i++) {
// int relIndexA = std::search_n(closedOrbs[0].begin(), closedOrbs[0].end(), 1, doublons[i]) - closedOrbs[0].begin();
// int relIndexB = std::search_n(closedOrbs[1].begin(), closedOrbs[1].end(), 1, doublons[i]) - closedOrbs[1].begin();
// for (int j = 0; j < holons.size(); j++) {
// theta[0].row(relIndexA) += w.bf(i, j) * hforbs.row(holons(j));
// theta[0].row(closedOrbs[0].size() + relIndexB) += w.bf(i, j) * hforbs.row(norbs + holons(j));
// }
// }
// Eigen::FullPivLU<MatrixXcd> lua(theta[0]);
// if (lua.isInvertible()) {
// thetaInv[0] = lua.inverse();
// thetaDet[0] = lua.determinant();
// }
// else {
// Eigen::Map<VectorXi> v1(&closedOrbs[0][0], closedOrbs[0].size());
// Eigen::Map<VectorXi> v2(&closedOrbs[1][0], closedOrbs[1].size());
// cout << "alphaClosed\n" << v1 << endl << endl;
// cout << "betaClosed\n" << v2 << endl << endl;
// cout << "col\n" << colTheta << endl << endl;
// cout << theta << endl << endl;
// cout << "overlap with theta determinant not invertible" << endl;
// exit(0);
// }
// thetaDet[1] = 1.;
// rTable[0] = MatrixXcd::Zero(2*norbs, closedOrbs[0].size() + closedOrbs[1].size());
// rTable[0] = w.getHforbs().block(0, 0, 2*norbs, closedOrbs[0].size() + closedOrbs[1].size()) * thetaInv[0];
// rTable[1] = rTable[0];
// //makeTableGhf(w, colTheta);
// }
//
// void excitationUpdate(const BFSlater &w, const Determinant& excitedDet)
// {
// fillOccupancyHelpers(excitedDet);
// initInvDetsTables(w);
// //makeTable(w, thetaInv[sz], colClosed, 0, sz);
// //calcOtherDetsTables(w, sz);
// }
//
// void excitationUpdateGhf(const BFSlater &w, const Determinant& excitedDet)
// {
// fillOccupancyHelpers(excitedDet);
// initInvDetsTablesGhf(w);
// //makeTableGhf(w, colTheta);
// }
//
// void getRelIndices(int i, int &relI, int a, int &relA, bool sz) const
// {
// //relI = std::lower_bound(closedOrbs[sz].begin(), closedOrbs[sz].end(), i) - closedOrbs[sz].begin();
// //relA = std::lower_bound(openOrbs[sz].begin(), openOrbs[sz].end(), a) - openOrbs[sz].begin();
// int factor = 0;
// if (hftype == 2 && sz != 0) factor = 1;
// relI = std::search_n(closedOrbs[sz].begin(), closedOrbs[sz].end(), 1, i) - closedOrbs[sz].begin() + factor * closedOrbs[0].size();
// //relA = std::search_n(openOrbs[sz].begin(), openOrbs[sz].end(), 1, a) - openOrbs[sz].begin() + factor * openOrbs[0].size();
// relA = a + factor * Determinant::norbs;
// }
//
//};
template<>
class WalkerHelper<AGP>
{
public:
MatrixXcd thetaInv; //inverse of the theta matrix
std::complex<double> thetaDet; //determinant of the theta matrix
std::array<vector<int>, 2> openOrbs; //set of open orbitals in the walker
std::array<vector<int>, 2> closedOrbs; //set of closed orbitals in the walker
std::array<MatrixXcd, 3> rTable; //table used for efficiently
WalkerHelper() {};
WalkerHelper(const AGP &w, const Determinant &d)
{
//fill the spin strings for the walker and the zeroth reference det
fillOpenClosedOrbs(d);
initInvDetsTables(w);
}
void fillOpenClosedOrbs(const Determinant &d)
{
openOrbs[0].clear();
openOrbs[1].clear();
closedOrbs[0].clear();
closedOrbs[1].clear();
d.getOpenClosedAlphaBeta(openOrbs[0], closedOrbs[0], openOrbs[1], closedOrbs[1]);
}
void makeTables(const AGP &w)
{
Map<VectorXi> rowOpen(&openOrbs[0][0], openOrbs[0].size());
Map<VectorXi> colClosed(&closedOrbs[1][0], closedOrbs[1].size());
MatrixXcd openThetaAlpha;
igl::slice(w.getPairMat(), rowOpen, colClosed, openThetaAlpha);
rTable[0] = openThetaAlpha * thetaInv;
Map<VectorXi> rowClosed(&closedOrbs[0][0], closedOrbs[0].size());
Map<VectorXi> colOpen(&openOrbs[1][0], openOrbs[1].size());
MatrixXcd openThetaBeta;
igl::slice(w.getPairMat(), rowClosed, colOpen, openThetaBeta);
MatrixXcd betaTableTranspose = thetaInv * openThetaBeta;
rTable[1] = betaTableTranspose.transpose();
MatrixXcd openTheta;
igl::slice(w.getPairMat(), rowOpen, colOpen, openTheta);
MatrixXcd rtc = rTable[0] * openThetaBeta;
rTable[2] = openTheta - rtc;
}
void initInvDetsTables(const AGP &w)
{
Eigen::Map<VectorXi> rowClosed(&closedOrbs[0][0], closedOrbs[0].size());
Eigen::Map<VectorXi> colClosed(&closedOrbs[1][0], closedOrbs[1].size());
MatrixXcd theta;
igl::slice(w.getPairMat(), rowClosed, colClosed, theta);
Eigen::FullPivLU<MatrixXcd> lua(theta);
if (lua.isInvertible()) {
thetaInv = lua.inverse();
thetaDet = lua.determinant();
}
else {
cout << "pairMat\n" << w.getPairMat() << endl << endl;
cout << "theta\n" << theta << endl << endl;
cout << "rowClosed\n" << rowClosed << endl << endl;
cout << "colClosed\n" << colClosed << endl << endl;
cout << " overlap with determinant not invertible" << endl;
exit(0);
}
makeTables(w);
}
void excitationUpdate(const AGP &w, vector<int>& cre, vector<int>& des, bool sz, double parity, const Determinant& excitedDet)
{
MatrixXcd invOld = thetaInv;
std::complex<double> detOld = thetaDet;
MatrixXcd test1, test2;
if (sz == 0) {
Eigen::Map<Eigen::VectorXi> colClosed(&closedOrbs[1][0], closedOrbs[1].size());
calculateInverseDeterminantWithRowChange(invOld, detOld, test1, thetaInv, thetaDet, test2, cre, des, colClosed, closedOrbs[0], w.getPairMat(), 0);
}
if (sz == 1) {
Eigen::Map<Eigen::VectorXi> rowClosed(&closedOrbs[0][0], closedOrbs[0].size());
calculateInverseDeterminantWithColumnChange(invOld, detOld, test1, thetaInv, thetaDet, test2, cre, des, rowClosed, closedOrbs[1], w.getPairMat());
}
thetaDet *= parity;
fillOpenClosedOrbs(excitedDet);
makeTables(w);
}
void getRelIndices(int i, int &relI, int a, int &relA, bool sz) const
{
relI = std::search_n(closedOrbs[sz].begin(), closedOrbs[sz].end(), 1, i) - closedOrbs[sz].begin();
relA = std::search_n(openOrbs[sz].begin(), openOrbs[sz].end(), 1, a) - openOrbs[sz].begin();
}
};
template<>
class WalkerHelper<Pfaffian>
{
public:
MatrixXcd thetaInv; //inverse of the theta matrix
complex<double> thetaPfaff; //determinant of the theta matrix
std::array<vector<int>, 2> openOrbs; //set of open orbitals in the walker
std::array<vector<int>, 2> closedOrbs; //set of closed orbitals in the walker
std::array<MatrixXcd, 2> rTable;
MatrixXcd fMat;
WalkerHelper() {};
WalkerHelper(const Pfaffian &w, const Determinant &d)
{
fillOpenClosedOrbs(d);
int nopen = openOrbs[0].size() + openOrbs[1].size();
int nclosed = closedOrbs[0].size() + closedOrbs[1].size();
fMat = MatrixXcd::Zero(nopen * nclosed, nclosed);
initInvDetsTables(w);
}
void fillOpenClosedOrbs(const Determinant &d)
{
openOrbs[0].clear();
openOrbs[1].clear();
closedOrbs[0].clear();
closedOrbs[1].clear();
d.getOpenClosedAlphaBeta(openOrbs[0], closedOrbs[0], openOrbs[1], closedOrbs[1]);
}
void makeTables(const Pfaffian &w)
{
int norbs = Determinant::norbs;
int nopen = openOrbs[0].size() + openOrbs[1].size();
int nclosed = closedOrbs[0].size() + closedOrbs[1].size();
Map<VectorXi> openAlpha(&openOrbs[0][0], openOrbs[0].size());
Map<VectorXi> openBeta(&openOrbs[1][0], openOrbs[1].size());
VectorXi open(nopen);
open << openAlpha, (openBeta.array() + norbs).matrix();
Map<VectorXi> closedAlpha(&closedOrbs[0][0], closedOrbs[0].size());
Map<VectorXi> closedBeta(&closedOrbs[1][0], closedOrbs[1].size());
VectorXi closed(nclosed);
closed << closedAlpha, (closedBeta.array() + norbs).matrix();
igl::slice(w.getPairMat(), open, closed, fMat);
rTable[0] = fMat * thetaInv;
rTable[1] = - rTable[0] * fMat.transpose();
//MatrixXcd fRow;
//VectorXi rowSlice(1), colSlice(nclosed);
//for (int i = 0; i < closed.size(); i++) {
// for (int a = 0; a < open.size(); a++) {
// colSlice = closed;
// rowSlice[0] = open[a];
// colSlice[i] = open[a];
// igl::slice(w.getPairMat(), rowSlice, colSlice, fRow);
// fMat.block(i * open.size() + a, 0, 1, closed.size()) = fRow;
// }
//}
//rTable[0] = fMat * thetaInv;
//rTable[1] = - rTable[0] * fMat.transpose();
}
void initInvDetsTables(const Pfaffian &w)
{
int norbs = Determinant::norbs;
int nclosed = closedOrbs[0].size() + closedOrbs[1].size();
Map<VectorXi> closedAlpha(&closedOrbs[0][0], closedOrbs[0].size());
Map<VectorXi> closedBeta(&closedOrbs[1][0], closedOrbs[1].size());
VectorXi closed(nclosed);
closed << closedAlpha, (closedBeta.array() + norbs).matrix();
MatrixXcd theta;
igl::slice(w.getPairMat(), closed, closed, theta);
Eigen::FullPivLU<MatrixXcd> lua(theta);
if (lua.isInvertible()) {
thetaInv = lua.inverse();
thetaPfaff = calcPfaffian(theta);
}
else {
cout << "pairMat\n" << w.getPairMat() << endl << endl;
cout << "theta\n" << theta << endl << endl;
cout << "colClosed\n" << closed << endl << endl;
cout << " overlap with determinant not invertible" << endl;
exit(0);
}
makeTables(w);
}
void excitationUpdate(const Pfaffian &w, int i, int a, bool sz, double parity, const Determinant& excitedDet)
{
int tableIndexi, tableIndexa;
getRelIndices(i, tableIndexi, a, tableIndexa, sz);
int norbs = Determinant::norbs;
int nopen = openOrbs[0].size() + openOrbs[1].size();
int nclosed = closedOrbs[0].size() + closedOrbs[1].size();
Map<VectorXi> closedAlpha(&closedOrbs[0][0], closedOrbs[0].size());
Map<VectorXi> closedBeta(&closedOrbs[1][0], closedOrbs[1].size());
VectorXi closed(nclosed);
closed << closedAlpha, (closedBeta.array() + norbs).matrix();
MatrixXcd cInv(2,2);
cInv << 0, -1,
1, 0;
MatrixXcd bMat = MatrixXcd::Zero(nclosed, 2);
bMat(tableIndexi, 1) = 1;
VectorXi colSlice(1);
colSlice[0] = i + sz * norbs;
MatrixXcd thetaSlice;
igl::slice(w.getPairMat(), closed, colSlice, thetaSlice);
//bMat.block(0, 0, nclosed, 1) = - fMat.transpose().block(0, tableIndexi * nopen + tableIndexa, nclosed, 1) - thetaSlice;
bMat.block(0, 0, nclosed, 1) = - fMat.transpose().block(0, tableIndexa, nclosed, 1) - thetaSlice;
MatrixXcd invOld = thetaInv;
MatrixXcd intermediate = (cInv + bMat.transpose() * invOld * bMat).inverse();
MatrixXcd shuffledThetaInv = invOld - invOld * bMat * intermediate * bMat.transpose() * invOld;
closed[tableIndexi] = a + sz * norbs;
std::vector<int> order(closed.size());
auto rcopy = closed;
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&rcopy](size_t i1, size_t i2) { return rcopy[i1] < rcopy[i2]; });
Eigen::Map<Eigen::VectorXi> orderVec(&order[0], order.size());
igl::slice(shuffledThetaInv, orderVec, orderVec, thetaInv);
//thetaPfaff = thetaPfaff * rTable[0](tableIndexi * nopen + tableIndexa, tableIndexi);
complex<double> pfaffRatio = fMat.row(tableIndexa) * invOld.col(tableIndexi);
thetaPfaff = thetaPfaff * pfaffRatio;
thetaPfaff *= parity;
fillOpenClosedOrbs(excitedDet);
makeTables(w);
}
void getRelIndices(int i, int &relI, int a, int &relA, bool sz) const
{
int factor = 0;
if (sz != 0) factor = 1;
relI = std::search_n(closedOrbs[sz].begin(), closedOrbs[sz].end(), 1, i) - closedOrbs[sz].begin() + factor * closedOrbs[0].size();
relA = std::search_n(openOrbs[sz].begin(), openOrbs[sz].end(), 1, a) - openOrbs[sz].begin() + factor * openOrbs[0].size();
}
};
template<>
class WalkerHelper<CPS>
{
public:
std::vector<double> intermediateForEachSpinOrb;
std::vector<int> commonCorrelators;
std::vector<std::vector<int> > twoSitesToCorrelator;
WalkerHelper() {};
WalkerHelper(CPS& cps, const Determinant& d) {
int norbs = Determinant::norbs;
intermediateForEachSpinOrb.resize(norbs*2);
updateHelper(cps, d, 0, 0, 0);
if (cps.twoSiteOrSmaller) {
vector<int> initial(norbs, -1);
twoSitesToCorrelator.resize(norbs, initial);
int corrIndex = 0;
for (const auto& corr : cps.cpsArray) {
if (corr.asites.size() == 2) {
int site1 = corr.asites[0], site2 = corr.asites[1];
twoSitesToCorrelator[site1][site2] = corrIndex;
twoSitesToCorrelator[site2][site1] = corrIndex;
}
corrIndex++;
}
}
}
//these update functions are really init functions
void updateHelper(CPS& cps, const Determinant& d, int l, int a, bool sz) {
int norbs = Determinant::norbs;
for (int i=0; i<2*norbs; i++) {
intermediateForEachSpinOrb[i] = 1.0;
Determinant dcopy1 = d, dcopy2 = d;
dcopy1.setocc(i, true); //make sure this is occupied
dcopy2.setocc(i, false); //make sure this is unoccupied
const vector<int>& cpsContainingi = cps.mapFromOrbitalToCorrelator[i/2];
for (const auto& j : cpsContainingi) {
intermediateForEachSpinOrb[i] *= cps.cpsArray[j].OverlapRatio(dcopy1, dcopy2);
}
}
}
void updateHelper(CPS& cps, const Determinant& d, int l, int m, int a, int b, bool sz) {
int norbs = Determinant::norbs;
for (int i=0; i<2*norbs; i++) {
intermediateForEachSpinOrb[i] = 1.0;
Determinant dcopy1 = d, dcopy2 = d;
dcopy1.setocc(i, true); //make sure this is occupied
dcopy2.setocc(i, false); //make sure this is unoccupied
const vector<int>& cpsContainingi = cps.mapFromOrbitalToCorrelator[i/2];
for (const auto& j : cpsContainingi) {
intermediateForEachSpinOrb[i] *= cps.cpsArray[j].OverlapRatio(dcopy1, dcopy2);
}
}
}
double OverlapRatio(int i, int a, const CPS& cps, const Determinant &dcopy, const Determinant &d) const
{
vector<int>& common = const_cast<vector<int>&>(commonCorrelators);
common.resize(0);
if (cps.twoSiteOrSmaller) {
common.push_back(twoSitesToCorrelator[i/2][a/2]);
if (common[0] == -1) common.resize(0);
}
else {
set_intersection(cps.mapFromOrbitalToCorrelator[i/2].begin(),
cps.mapFromOrbitalToCorrelator[i/2].end(),
cps.mapFromOrbitalToCorrelator[a/2].begin(),
cps.mapFromOrbitalToCorrelator[a/2].end(),
back_inserter(common));
sort(common.begin(), common.end() );
}
double ovlp = intermediateForEachSpinOrb[a]/intermediateForEachSpinOrb[i];
Determinant dcopy1 = d, dcopy2 = d;
dcopy1.setocc(i, false); dcopy2.setocc(a, true);
int previ = -1;
for (const auto& j : common) {
ovlp *= cps.cpsArray[j].OverlapRatio(dcopy,d);
ovlp *= cps.cpsArray[j].OverlapRatio(d, dcopy2);
ovlp *= cps.cpsArray[j].OverlapRatio(d, dcopy1);
}
return ovlp;
}
double OverlapRatio(int i, int j, int a, int b, const CPS& cps, const Determinant &dcopy, const Determinant &d) const
{
if (!(cps.twoSiteOrSmaller && i/2!=j/2 && i/2!=a/2 && i/2!= b/2 && j/2 != a/2 && j/2 != b/2 && a/2!=b/2))
return cps.OverlapRatio(i/2, j/2, a/2, b/2, dcopy, d);
vector<int>& common = const_cast<vector<int>&>(commonCorrelators);
common.resize(0);
double ovlp = intermediateForEachSpinOrb[a]*intermediateForEachSpinOrb[b]
/intermediateForEachSpinOrb[i]/intermediateForEachSpinOrb[j];
Determinant dcopy1 = d, dcopy2 = d;
{//i j
dcopy1.setocc(i, false); dcopy2.setocc(j, false);
int index = twoSitesToCorrelator[i/2][j/2];
if (index != -1) {
ovlp *= cps.cpsArray[index].OverlapRatio(dcopy, d);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy2);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy1);
}
dcopy1.setocc(i, true); dcopy2.setocc(j, true);
}
{//i a
dcopy1.setocc(i, false); dcopy2.setocc(a, true);
int index = twoSitesToCorrelator[i/2][a/2];
if (index != -1) {
ovlp *= cps.cpsArray[index].OverlapRatio(dcopy, d);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy2);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy1);
}
dcopy1.setocc(i, true); dcopy2.setocc(a, false);
}
{//i b
dcopy1.setocc(i, false); dcopy2.setocc(b, true);
int index = twoSitesToCorrelator[i/2][b/2];
if (index != -1) {
ovlp *= cps.cpsArray[index].OverlapRatio(dcopy, d);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy2);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy1);
}
dcopy1.setocc(i, true); dcopy2.setocc(b, false);
}
{//j a
dcopy1.setocc(j, false); dcopy2.setocc(a, true);
int index = twoSitesToCorrelator[j/2][a/2];
if (index != -1) {
ovlp *= cps.cpsArray[index].OverlapRatio(dcopy, d);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy2);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy1);
}
dcopy1.setocc(j, true); dcopy2.setocc(a, false);
}
{//j b
dcopy1.setocc(j, false); dcopy2.setocc(b, true);
int index = twoSitesToCorrelator[j/2][b/2];
if (index != -1) {
ovlp *= cps.cpsArray[index].OverlapRatio(dcopy, d);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy2);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy1);
}
dcopy1.setocc(j, true); dcopy2.setocc(b, false);
}
{//a b
dcopy1.setocc(a, true); dcopy2.setocc(b, true);
int index = twoSitesToCorrelator[a/2][b/2];
if (index != -1) {
ovlp *= cps.cpsArray[index].OverlapRatio(dcopy, d);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy2);
ovlp *= cps.cpsArray[index].OverlapRatio(d, dcopy1);
}
dcopy1.setocc(a, false); dcopy2.setocc(b, false);
}
return ovlp;
}
double OverlapRatio(const std::array<unordered_set<int> , 2> &from, const std::array<unordered_set<int> , 2> &to, const CPS& cps) const
{
return 0.;
}
};
template<>
class WalkerHelper<Jastrow>
{
public:
std::vector<double> intermediateForEachSpinOrb;
WalkerHelper() {};
WalkerHelper(Jastrow& cps, const Determinant& d) {
int norbs = Determinant::norbs;
intermediateForEachSpinOrb.resize(norbs*2);
initHelper(cps, d);
}
void initHelper(Jastrow& cps, const Determinant& d) {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
for (int i=0; i<2*norbs; i++) {
intermediateForEachSpinOrb[i] = cps(i,i);
for (int j=0; j<closed.size(); j++)
if (closed[j] != i)
intermediateForEachSpinOrb[i] *= cps(i, closed[j]);
}
}
void updateHelper(Jastrow& cps, const Determinant& d, int i, int a, bool sz) {
i = 2 * i + sz; a = 2 * a + sz;
int norbs = Determinant::norbs;
for (int l = 0; l < 2 * norbs; l++)
intermediateForEachSpinOrb[l] *= cps(l, a) / cps(l, i);
intermediateForEachSpinOrb[i] *= cps(i, i);
intermediateForEachSpinOrb[a] /= cps(a, a);
//initHelper(cps, d);
}
void updateHelper(Jastrow& cps, const Determinant& d, int i, int j, int a, int b, bool sz) {
i = 2 * i + sz; a = 2 * a + sz;
j = 2 * j + sz; b = 2 * b + sz;
int norbs = Determinant::norbs;
for (int l = 0; l < 2 * norbs; l++)
intermediateForEachSpinOrb[l] *= cps(l, a) * cps(l, b) / cps(l, i) / cps(l, j);
intermediateForEachSpinOrb[i] *= cps(i, i);
intermediateForEachSpinOrb[a] /= cps(a, a);
intermediateForEachSpinOrb[j] *= cps(j, j);
intermediateForEachSpinOrb[b] /= cps(b, b);
//initHelper(cps, d);
}
double OverlapRatio(int i, int a, const Jastrow& cps,
const Determinant &dcopy, const Determinant &d) const
{
return intermediateForEachSpinOrb[a]/intermediateForEachSpinOrb[i]/cps(i,a);
}
double OverlapRatio(int i, int j, int a, int b, const Jastrow& cps,
const Determinant &dcopy, const Determinant &d) const
{
return intermediateForEachSpinOrb[a]*intermediateForEachSpinOrb[b]*cps(a,b)*cps(i,j)
/intermediateForEachSpinOrb[i]/intermediateForEachSpinOrb[j]/
cps(i,a)/cps(j,a)/cps(i,b)/cps(j,b);
}
double OverlapRatio(const std::array<unordered_set<int> , 2> &from, const std::array<unordered_set<int> , 2> &to, const Jastrow& cps) const
{
vector<int> fromSpin, toSpin;
fromSpin.clear(); toSpin.clear();
double ratio = 1.;
for (int sz = 0; sz < 2; sz++) {//iterate over spins
auto itFrom = from[sz].begin();
auto itTo = to[sz].begin();
for (int n = 0; n < from[sz].size(); n++) {//iterate over excitations
int i = 2 * (*itFrom) + sz, a = 2 * (*itTo) + sz;
itFrom = std::next(itFrom); itTo = std::next(itTo);
ratio *= intermediateForEachSpinOrb[a] / intermediateForEachSpinOrb[i] / cps(i, a);
for (int p = 0; p < fromSpin.size(); p++) {
ratio *= cps(i, fromSpin[p]) * cps(a, toSpin[p]) / cps(i, toSpin[p]) / cps(fromSpin[p], a);
}
fromSpin.push_back(i);
toSpin.push_back(a);
}
}
return ratio;
}
};
template<>
class WalkerHelper<Gutzwiller>
{
public:
WalkerHelper() {};
WalkerHelper(Gutzwiller& gutz, const Determinant& d) {}
void updateHelper(Gutzwiller& gutz, const Determinant& d, int i, int a, bool sz) {}
void updateHelper(Gutzwiller& gutz, const Determinant& d, int i, int j, int a, int b, bool sz) {}
double OverlapRatio(int i, int a, const Gutzwiller& gutz,
const Determinant &dcopy, const Determinant &d) const
{
double ratio = 1;
if (i % 2 == 0) {
if (d.getoccB(i/2)) ratio /= gutz.g(i/2);
if (d.getoccB(a/2)) ratio *= gutz.g(a/2);
}
else {
if (d.getoccA(i/2)) ratio /= gutz.g(i/2);
if (d.getoccA(a/2)) ratio *= gutz.g(a/2);
}
return ratio;
//return gutz.OverlapRatio(dcopy, d);
}
double OverlapRatio(int i, int j, int a, int b, const Gutzwiller& gutz,
const Determinant &dcopy, const Determinant &d) const
{
double ratio = 1;
if (i % 2 == 0) {
if (d.getoccB(i/2)) ratio /= gutz.g(i/2);
if (d.getoccB(a/2)) ratio *= gutz.g(a/2);
}
else {
if (d.getoccA(i/2)) ratio /= gutz.g(i/2);
if (d.getoccA(a/2)) ratio *= gutz.g(a/2);
}
Determinant dExc = d;
dExc.setocc(i, false); dExc.setocc(a, true);
if (j % 2 == 0) {
if (dExc.getoccB(j/2)) ratio /= gutz.g(j/2);
if (dExc.getoccB(b/2)) ratio *= gutz.g(b/2);
}
else {
if (dExc.getoccA(j/2)) ratio /= gutz.g(j/2);
if (dExc.getoccA(b/2)) ratio *= gutz.g(b/2);
}
return ratio;
//return gutz.OverlapRatio(dcopy, d);
}
double OverlapRatio(const std::array<unordered_set<int> , 2> &from, const std::array<unordered_set<int> , 2> &to, const Gutzwiller& gutz) const
{
return 0.;
}
};
template<>
class WalkerHelper<RBM>
{
public:
//the intermediate data is stored in the wfn, this class initializes and updates it
WalkerHelper() {};
WalkerHelper(RBM& cps, const Determinant& d) {
int norbs = Determinant::norbs;
//cps.bwn = ArrayXd::Zero(cps.numHidden);
cps.bwn = VectorXd::Zero(cps.numHidden);
//cps.intermediates[0] = ArrayXXd::Zero(norbs, norbs);
//cps.intermediates[1] = ArrayXXd::Zero(norbs, norbs);
initHelper(cps, d);
}
void initHelper(RBM& cps, const Determinant& d) {
int norbs = Determinant::norbs;
vector<int> closed;
vector<int> open;
d.getOpenClosed(open, closed);
//bwn
cps.bwn = cps.bVec;
for (int j = 0; j < closed.size(); j++) {
cps.bwn += cps.wMat.col(closed[j]);
}
cps.coshbwn = cosh(cps.bwn.array()).prod();
//intermediates
//ArrayXd tanhbwn = tanh(cps.bwn);
//for (int i = commrank; i < (norbs * (norbs-1)) / 2; i += commsize) {
// //calc row (occupied) and column (unoccupied) up spatial orb indices
// int occ = floor(0.5 + sqrt(1 + 8*i) / 2), unocc = i % occ;//bottom half
// ArrayXd wDiff = cps.wMat.col(2 * unocc) - cps.wMat.col(2 * occ);
// ArrayXd coshWDiff = cosh(wDiff), sinhWDiff = sinh(wDiff);
// cps.intermediates[0](occ, unocc) = (coshWDiff + tanhbwn * sinhWDiff).prod();
// cps.intermediates[0](unocc, occ) = (coshWDiff - tanhbwn * sinhWDiff).prod();//bottom half
// wDiff = cps.wMat.col(2 * unocc + 1) - cps.wMat.col(2 * occ + 1);
// coshWDiff = cosh(wDiff); sinhWDiff = sinh(wDiff);
// cps.intermediates[1](occ, unocc) = (coshWDiff + tanhbwn * sinhWDiff).prod();
// cps.intermediates[1](unocc, occ) = (coshWDiff - tanhbwn * sinhWDiff).prod();
//}
//#ifndef SERIAL
// MPI_Allreduce(MPI_IN_PLACE, cps.intermediates[0].data(), norbs*norbs, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
// MPI_Allreduce(MPI_IN_PLACE, cps.intermediates[1].data(), norbs*norbs, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
//#endif
}
void updateHelper(RBM& cps, const Determinant& d, int i, int a, bool sz) {
i = 2 * i + sz; a = 2 * a + sz;
cps.bwn += cps.wMat.col(a) - cps.wMat.col(i);
cps.coshbwn = cosh(cps.bwn.array()).prod();
}
void updateHelper(RBM& cps, const Determinant& d, int i, int j, int a, int b, bool sz) {
i = 2 * i + sz; a = 2 * a + sz;
j = 2 * j + sz; b = 2 * b + sz;
cps.bwn += cps.wMat.col(a) - cps.wMat.col(i) + cps.wMat.col(b) - cps.wMat.col(j);
cps.coshbwn = cosh(cps.bwn.array()).prod();
}
double OverlapRatio(int i, int a, const RBM& cps,
const Determinant &dcopy, const Determinant &d) const
{
double aFac = exp(cps.aVec(a) - cps.aVec(i));
VectorXd bwnp = cps.bwn + cps.wMat.col(a) - cps.wMat.col(i);
return aFac * cosh(bwnp.array()).prod() / cps.coshbwn;
}
double OverlapRatio(int i, int j, int a, int b, const RBM& cps,
const Determinant &dcopy, const Determinant &d) const
{
double aFac = exp(cps.aVec(a) - cps.aVec(i) + cps.aVec(b) - cps.aVec(j));
VectorXd bwnp = cps.bwn + cps.wMat.col(a) - cps.wMat.col(i) + cps.wMat.col(b) - cps.wMat.col(j);
return aFac * cosh(bwnp.array()).prod() / cps.coshbwn;
}
double OverlapRatio(const std::array<unordered_set<int> , 2> &from, const std::array<unordered_set<int> , 2> &to, const RBM& cps) const
{
return 0.;
}
};
template<>
class WalkerHelper<JRBM>
{
public:
WalkerHelper<Jastrow> jastrowHelper;
WalkerHelper<RBM> RBMHelper;
WalkerHelper() {};
WalkerHelper(JRBM& cps, const Determinant& d) {
jastrowHelper = WalkerHelper<Jastrow>(cps.jastrow, d);
RBMHelper = WalkerHelper<RBM>(cps.rbm, d);
}
void initHelper(JRBM& cps, const Determinant& d) {
jastrowHelper.initHelper(cps.jastrow, d);
RBMHelper.initHelper(cps.rbm, d);
}
void updateHelper(JRBM& cps, const Determinant& d, int i, int a, bool sz) {
jastrowHelper.updateHelper(cps.jastrow, d, i, a, sz);
RBMHelper.updateHelper(cps.rbm, d, i, a, sz);
}
void updateHelper(JRBM& cps, const Determinant& d, int i, int j, int a, int b, bool sz) {
jastrowHelper.updateHelper(cps.jastrow, d, i, j, a, b, sz);
RBMHelper.updateHelper(cps.rbm, d, i, j, a, b, sz);
}
double OverlapRatio(int i, int a, const JRBM& cps,
const Determinant &dcopy, const Determinant &d) const
{
return jastrowHelper.OverlapRatio(i, a, cps.jastrow, dcopy, d) * RBMHelper.OverlapRatio(i, a, cps.rbm, dcopy, d);
}
double OverlapRatio(int i, int j, int a, int b, const JRBM& cps,
const Determinant &dcopy, const Determinant &d) const
{
return jastrowHelper.OverlapRatio(i, j, a, b, cps.jastrow, dcopy, d) * RBMHelper.OverlapRatio(i, j, a, b, cps.rbm, dcopy, d);
}
double OverlapRatio(const std::array<unordered_set<int> , 2> &from, const std::array<unordered_set<int> , 2> &to, const JRBM& cps) const
{
return 0.;
}
};
#endif
|
54f9bdc20470f85e0645ca996533317854738265
|
[
"Makefile",
"Python",
"C",
"C++",
"Shell"
] | 206 |
C++
|
mixianxian/VMC
|
4def47ed37c07df3f28a6e80bd006347fbff8675
|
13b2f69862061a1f8bb72fe4768275ebf17d0ab3
|
refs/heads/main
|
<file_sep>namespace Kapitelaufgabe3Script {
function getSubpage(): string {
return window.location.pathname.substring(window.location.pathname.lastIndexOf("/") + 1);
}
if (getSubpage() == "index.html") { // script for registration-Page
let buttonSubmit: HTMLElement = document.getElementById("submit");
let buttonSignIn: HTMLElement = document.getElementById("tosignin");
let buttonShow: HTMLElement = document.getElementById("toshow");
let responseDiv: HTMLElement = document.getElementById("div");
buttonSubmit.addEventListener("click", handleSubmit);
async function handleSubmit(_event: Event): Promise<void> {
let formData: FormData = new FormData(document.forms[0]); //create and fill formData
let url: string = "https://hfugis2020.herokuapp.com";
formData.append("task", "register");
let query: URLSearchParams = new URLSearchParams(<any>formData);
url = url + "?" + query.toString(); //create GET-Url
console.log(url);
await fetch(url).then(async function (response: Response): Promise<void> {
let responseText: string = await response.text();
console.log(responseText);
let answer: HTMLElement = document.createElement("p");
answer.innerText = responseText;
responseDiv.appendChild(answer);
}
);
}
//Buttons to linked Sub-Pages
buttonShow.addEventListener("click", handleToShow);
function handleToShow(_event: Event): void {
window.open("showusers.html", "_self");
}
buttonSignIn.addEventListener("click", handleToSignin);
function handleToSignin(_event: Event): void {
window.open("signin.html", "_self");
}
}
if (getSubpage() == "showusers.html") { //Script for Users-Page
let buttonShow: HTMLElement = document.getElementById("show");
let buttonSignIn: HTMLElement = document.getElementById("tosignin");
let buttonRegister: HTMLElement = document.getElementById("toregister");
let responseUsersDiv: HTMLElement = document.getElementById("users");
buttonShow.addEventListener("click", handleShow);
async function handleShow(_event: Event): Promise<void> {
let formData: FormData = new FormData(); //create and fill formData
let url: string = "https://hfugis2020.herokuapp.com";
formData.append("task", "showusers");
let query: URLSearchParams = new URLSearchParams(<any>formData);
url = url + "?" + query.toString(); //create GET-Url
console.log(url);
await fetch(url).then(async function (response: Response): Promise<void> {
let responseText: string = await response.text();
responseUsersDiv.innerHTML = responseText;
}
);
}
//Buttons to linked Sub-Pages
buttonRegister.addEventListener("click", handleToRegister);
function handleToRegister(_event: Event): void {
window.open("index.html", "_self");
}
buttonSignIn.addEventListener("click", handleToSignin);
function handleToSignin(_event: Event): void {
window.open("signin.html", "_self");
}
}
if (getSubpage() == "signin.html") { //Script for log in Page
let buttonSignin: HTMLElement = document.getElementById("signin");
let buttonShow: HTMLElement = document.getElementById("toshow");
let buttonRegister: HTMLElement = document.getElementById("toregister");
let responseSignDiv: HTMLElement = document.getElementById("signdiv");
buttonSignin.addEventListener("click", handleSignin);
async function handleSignin(_event: Event): Promise<void> {
let formData: FormData = new FormData(document.forms[0]);
let url: string = "https://hfugis2020.herokuapp.com";
formData.append("task", "signin");
let query: URLSearchParams = new URLSearchParams(<any>formData);
url = url + "?" + query.toString(); //create GET-Url
console.log(url);
await fetch(url).then(async function (response: Response): Promise<void> {
let responseText: string = await response.text();
responseSignDiv.innerText = responseText;
}
);
}
//Buttons to linked Sub-Pages
buttonRegister.addEventListener("click", handleToRegister);
function handleToRegister(_event: Event): void {
window.open("index.html", "_self");
}
buttonShow.addEventListener("click", handleToShow);
function handleToShow(_event: Event): void {
window.open("showusers.html", "_self");
}
}
}<file_sep>import * as Http from "http";
import * as Url from "url";
import * as Mongo from "mongodb";
export namespace P_3_1Server {
console.log("Starting server");
interface MyInput { //every possible input
Name: string;
Nachname: string;
email: string;
Adresse: string;
Passwort: string;
task: string;
}
interface User { //user input from registration-Page
Name: string;
Nachname: string;
email: string;
Adresse: string;
Passwort: string;
}
function inputUser(_input: MyInput): User { //converting Input to Registration-Input
let myUser: User = { "Name": "", "Nachname": "", "Adresse": "", "email": "", "Passwort": "" };
myUser.Name = _input.Name;
myUser.Nachname = _input.Nachname;
myUser.email = _input.email;
myUser.Adresse = _input.Adresse;
myUser.Passwort = _input.Passwort;
return myUser;
}
let users: Mongo.Collection;
let port: number = Number(process.env.PORT);
if (!port)
port = 8100;
let databaseUrl: string = "mongodb+srv://Fabian:<EMAIL>@specific<EMAIL>/Test?retryWrites=true&w=majority";
startServer(port);
connectToDatabase(databaseUrl);
function startServer(_port: number | string): void {
let server: Http.Server = Http.createServer();
server.addListener("request", handleRequest);
server.addListener("listening", handleListen);
server.listen(_port);
}
async function connectToDatabase(_url: string): Promise<void> {
let options: Mongo.MongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };
let mongoClient: Mongo.MongoClient = new Mongo.MongoClient(_url, options);
await mongoClient.connect();
users = mongoClient.db("Test").collection("users");
console.log("Database connected: " + users != undefined);
}
function storeUser(_user: User): void {
users.insertOne(_user);
}
function handleListen(): void {
console.log("Listening");
}
async function checkUser(_user: User): Promise<boolean> { //is email already used in Database?
let newUser: User = JSON.parse(JSON.stringify(await users.findOne({ "email": _user.email })));
return _user.email == newUser.email;
}
async function checkPassword(_user: MyInput): Promise<boolean> { //is user / password correct
let newUser: User = JSON.parse(JSON.stringify(await users.findOne({ "Passwort": _<PASSWORD>, "email": _user.email })));
return newUser != undefined;
}
async function getUsers(): Promise<string> { // return every user in Database
let returnString: string = "";
let userCurser: Mongo.Cursor = users.find();
let jsonUsers: string = JSON.stringify(await userCurser.toArray());
let myUsers: User[] = JSON.parse(jsonUsers);
for (let i: number = 0; i < myUsers.length; i++) {
returnString = returnString + "<p>" + myUsers[i].Name + " " + myUsers[i].Nachname + "</p></br>";
}
return returnString;
}
async function handleRequest(_request: Http.IncomingMessage, _response: Http.ServerResponse): Promise<void> {
console.log("I hear voices!");
_response.setHeader("content-type", "text/html; charset=utf-8");
_response.setHeader("Access-Control-Allow-Origin", "*");
let q: Url.UrlWithParsedQuery = Url.parse(_request.url, true);
console.log(q.search);
let jsonString: string = JSON.stringify(q.query); //convert GET-Url to Input-Object
let input: MyInput = JSON.parse(jsonString);
if (input.task == "register") { // for requested registration
let user: User = inputUser(input);
if (!(await checkUser(user).catch(() => {
console.log("Check failed!");
}))) {
storeUser(user);
_response.write("user created!");
_response.end();
} else {
_response.write("user already exists!");
_response.end();
}
} else if (input.task == "showusers") { // for requested users
let responseString: string | void;
responseString = await getUsers().catch(() => {
console.log("failed!");
});
_response.write("" + responseString)
_response.end();
} else if (input.task == "signin") { // for requested sign in
if ((await checkPassword(input).catch(() => {
console.log("Sign in failed!");
}))) {
_response.write("Sign in sucessful!");
_response.end();
} else {
_response.write("Sign in unsucessful!");
_response.end();
}
} else {
_response.write("something went wrong!");
_response.end();
}
}
}
|
51edad2f5f28ff46bf92675d8c99f62e8a64b9f1
|
[
"TypeScript"
] | 2 |
TypeScript
|
SpeziFisch-DE/GIS2020
|
fa794439e05988aa11abf90e9f9aafb8480524d8
|
01aa3968e9c8d43ae36ffe93df3c4093be320c85
|
refs/heads/master
|
<file_sep>
import com.fuzzylite.Engine;
import com.fuzzylite.FuzzyLite;
import com.fuzzylite.defuzzifier.Centroid;
import com.fuzzylite.imex.FldExporter;
import com.fuzzylite.imex.FllImporter;
import com.fuzzylite.norm.s.Maximum;
import com.fuzzylite.norm.t.Minimum;
import com.fuzzylite.rule.Rule;
import com.fuzzylite.rule.RuleBlock;
import com.fuzzylite.term.Cosine;
import com.fuzzylite.term.Triangle;
import com.fuzzylite.variable.InputVariable;
import com.fuzzylite.variable.OutputVariable;
import java.io.File;
import java.net.URL;
import java.util.logging.Level;
public class SimpleDimmer {
public SimpleDimmer() {
}
//Method 1: Set up the engine manually.
public void method1() {
Engine engine = new Engine();
engine.setName("simple-dimmer");
InputVariable inputVariable = new InputVariable();
inputVariable.setEnabled(true);
inputVariable.setName("Ambient");
inputVariable.setRange(0.000, 1.000);
inputVariable.addTerm(new Triangle("DARK", 0.000, 0.250, 0.500));
inputVariable.addTerm(new Triangle("MEDIUM", 0.250, 0.500, 0.750));
inputVariable.addTerm(new Triangle("BRIGHT", 0.500, 0.750, 1.000));
engine.addInputVariable(inputVariable);
OutputVariable outputVariable = new OutputVariable();
outputVariable.setEnabled(true);
outputVariable.setName("Power");
outputVariable.setRange(0.000, 1.000);
outputVariable.fuzzyOutput().setAccumulation(new Maximum());
outputVariable.setDefuzzifier(new Centroid(200));
outputVariable.setDefaultValue(Double.NaN);
outputVariable.setLockPreviousOutputValue(false);
outputVariable.setLockOutputValueInRange(false);
outputVariable.addTerm(new Triangle("LOW", 0.000, 0.250, 0.500));
outputVariable.addTerm(new Triangle("MEDIUM", 0.250, 0.500, 0.750));
outputVariable.addTerm(new Triangle("HIGH", 0.500, 0.750, 1.000));
engine.addOutputVariable(outputVariable);
RuleBlock ruleBlock = new RuleBlock();
ruleBlock.setEnabled(true);
ruleBlock.setName("");
ruleBlock.setConjunction(null);
ruleBlock.setDisjunction(null);
ruleBlock.setActivation(new Minimum());
ruleBlock.addRule(Rule.parse("if Ambient is DARK then Power is HIGH", engine));
ruleBlock.addRule(Rule.parse("if Ambient is MEDIUM then Power is MEDIUM", engine));
ruleBlock.addRule(Rule.parse("if Ambient is BRIGHT then Power is LOW", engine));
engine.addRuleBlock(ruleBlock);
FuzzyLite.logger().info(new FldExporter().toString(engine));
}
//Method 2: Load from a file
public void method2() {
Engine engine = null;
String configurationFile = "SimpleDimmer.fll";
URL url = SimpleDimmer.class.getResource(configurationFile);
try {
engine = new FllImporter().fromFile(new File(url.toURI()));
} catch (Exception ex) {
FuzzyLite.logger().log(Level.SEVERE, ex.toString(), ex);
}
FuzzyLite.logger().info(new FldExporter().toString(engine));
}
public void anotherTest(){
Engine engine = new Engine();
engine.setName("simple-dimmer");
InputVariable inputVariable = new InputVariable();
inputVariable.setEnabled(true);
inputVariable.setName("Ambient");
inputVariable.setRange(0.000, 1.000);
inputVariable.addTerm(new Triangle("DARK", 0.000, 0.250, 0.500));
inputVariable.addTerm(new Triangle("MEDIUM", 0.250, 0.500, 0.750));
inputVariable.addTerm(new Triangle("BRIGHT", 0.500, 0.750, 1.000));
engine.addInputVariable(inputVariable);
OutputVariable outputVariable1 = new OutputVariable();
outputVariable1.setEnabled(true);
outputVariable1.setName("Power");
outputVariable1.setRange(0.000, 1.000);
outputVariable1.fuzzyOutput().setAccumulation(new Maximum());
outputVariable1.setDefuzzifier(new Centroid(200));
outputVariable1.setDefaultValue(Double.NaN);
outputVariable1.setLockPreviousOutputValue(false);
outputVariable1.setLockOutputValueInRange(false);
outputVariable1.addTerm(new Triangle("LOW", 0.000, 0.250, 0.500));
outputVariable1.addTerm(new Triangle("MEDIUM", 0.250, 0.500, 0.750));
outputVariable1.addTerm(new Triangle("HIGH", 0.500, 0.750, 1.000));
engine.addOutputVariable(outputVariable1);
OutputVariable outputVariable2 = new OutputVariable();
outputVariable2.setEnabled(true);
outputVariable2.setName("InversePower");
outputVariable2.setRange(0.000, 1.000);
outputVariable2.fuzzyOutput().setAccumulation(new Maximum());
outputVariable2.setDefuzzifier(new Centroid(500));
outputVariable2.setDefaultValue(Double.NaN);
outputVariable2.setLockPreviousOutputValue(false);
outputVariable2.setLockOutputValueInRange(false);
outputVariable2.addTerm(new Cosine("LOW", 0.200, 0.500));
outputVariable2.addTerm(new Cosine("MEDIUM", 0.500, 0.500));
outputVariable2.addTerm(new Cosine("HIGH", 0.800, 0.500));
engine.addOutputVariable(outputVariable2);
RuleBlock ruleBlock = new RuleBlock();
ruleBlock.setEnabled(true);
ruleBlock.setName("");
ruleBlock.setConjunction(null);
ruleBlock.setDisjunction(null);
ruleBlock.setActivation(new Minimum());
ruleBlock.addRule(Rule.parse("if Ambient is DARK then Power is HIGH", engine));
ruleBlock.addRule(Rule.parse("if Ambient is MEDIUM then Power is MEDIUM", engine));
ruleBlock.addRule(Rule.parse("if Ambient is BRIGHT then Power is LOW", engine));
ruleBlock.addRule(Rule.parse("if Power is LOW then InversePower is HIGH", engine));
ruleBlock.addRule(Rule.parse("if Power is MEDIUM then InversePower is MEDIUM", engine));
ruleBlock.addRule(Rule.parse("if Power is HIGH then InversePower is LOW", engine));
engine.addRuleBlock(ruleBlock);
FuzzyLite.logger().info(new FldExporter().toString(engine));
}
public void run() {
method1();
method2();
anotherTest();
}
public static void main(String[] args) {
new SimpleDimmer().run();
}
}
|
84f8bd9706f062433f8a8b96799b4b5d0d295d97
|
[
"Java"
] | 1 |
Java
|
aicroe/proyia_simpledinner
|
97bc9e6a4dad0108c83cf6e265dedc2eefdc9201
|
ff6ab0c7d87948fa24863fe6a928dca986ff6551
|
refs/heads/master
|
<file_sep>package me.trinopoty.protobufRpc.server;
import com.google.protobuf.AbstractMessage;
import io.netty.channel.Channel;
import me.trinopoty.protobufRpc.codec.WirePacketFormat;
import me.trinopoty.protobufRpc.util.RpcServiceCollector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
@SuppressWarnings("unused")
public final class ProtobufRpcServerChannel {
private final class OobInvocationHandler implements InvocationHandler {
private final RpcServiceCollector.RpcServiceInfo mRpcServiceInfo;
OobInvocationHandler(RpcServiceCollector.RpcServiceInfo serviceInfo) {
mRpcServiceInfo = serviceInfo;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
RpcServiceCollector.RpcMethodInfo methodInfo = mRpcServiceInfo.getMethodMap().get(method);
assert methodInfo != null;
WirePacketFormat.ServiceIdentifier serviceIdentifier = WirePacketFormat.ServiceIdentifier.newBuilder()
.setServiceIdentifier(mRpcServiceInfo.getServiceIdentifier())
.setMethodIdentifier(methodInfo.getMethodIdentifier())
.build();
WirePacketFormat.WirePacket.Builder requestWirePacketBuilder = WirePacketFormat.WirePacket.newBuilder();
requestWirePacketBuilder.setMessageIdentifier(0);
requestWirePacketBuilder.setMessageType(WirePacketFormat.MessageType.MESSAGE_TYPE_OOB);
requestWirePacketBuilder.setServiceIdentifier(serviceIdentifier);
AbstractMessage requestMessage = (AbstractMessage) args[0];
requestWirePacketBuilder.setPayload(requestMessage.toByteString());
mChannel.writeAndFlush(requestWirePacketBuilder.build());
return null;
}
}
private final ProtobufRpcServer mProtobufRpcServer;
private final Channel mChannel;
ProtobufRpcServerChannel(ProtobufRpcServer protobufRpcServer, Channel channel) {
mProtobufRpcServer = protobufRpcServer;
mChannel = channel;
}
@SuppressWarnings("unchecked")
public <T> T getOobService(Class<T> classOfService) {
RpcServiceCollector.RpcServiceInfo serviceInfo = mProtobufRpcServer.getRpcServiceCollector().getServiceInfo(classOfService);
if(serviceInfo != null) {
return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { classOfService }, new OobInvocationHandler(serviceInfo));
} else {
throw new IllegalArgumentException(String.format("Class<%s> not registered for OOB handling.", classOfService.getName()));
}
}
public InetSocketAddress getRemoteAddress() {
return (InetSocketAddress) mChannel.remoteAddress();
}
}<file_sep># Protobuf RPC
[](https://jitpack.io/#trinopoty/protobuf-rpc)
Protobuf and Netty based client-server RPC library.<file_sep>package me.trinopoty.protobufRpc.exception;
public final class DuplicateRpcServiceIdentifierException extends Exception {
public DuplicateRpcServiceIdentifierException() {
super();
}
public DuplicateRpcServiceIdentifierException(String message) {
super(message);
}
public DuplicateRpcServiceIdentifierException(String message, Throwable cause) {
super(message, cause);
}
public DuplicateRpcServiceIdentifierException(Throwable cause) {
super(cause);
}
protected DuplicateRpcServiceIdentifierException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}<file_sep>package me.trinopoty.protobufRpc.test;
import com.google.protobuf.Empty;
import me.trinopoty.protobufRpc.annotation.RpcIdentifier;
import me.trinopoty.protobufRpc.client.ProtobufRpcClient;
import me.trinopoty.protobufRpc.exception.DuplicateRpcMethodIdentifierException;
import me.trinopoty.protobufRpc.exception.DuplicateRpcServiceIdentifierException;
import me.trinopoty.protobufRpc.exception.IllegalMethodSignatureException;
import me.trinopoty.protobufRpc.exception.MissingRpcIdentifierException;
import org.junit.Test;
@SuppressWarnings("unused")
public final class RpcInterfaceTest {
@RpcIdentifier(1)
public interface DuplicateService01 {
@RpcIdentifier(1)
Empty empty(Empty empty);
}
@RpcIdentifier(1)
public interface DuplicateService02 {
@RpcIdentifier(1)
Empty empty(Empty empty);
}
@RpcIdentifier(1)
public interface DuplicateMethod01 {
@RpcIdentifier(1)
Empty empty(Empty empty);
@RpcIdentifier(1)
Empty empty2(Empty empty);
}
public interface MissingIdentifierService {
@RpcIdentifier(1)
Empty empty(Empty empty);
}
@RpcIdentifier(1)
public interface MissingIdentifierMethod {
Empty empty(Empty empty);
}
@RpcIdentifier(1)
public interface RpcMethodSignature {
@RpcIdentifier(1)
void method1();
@RpcIdentifier(2)
void method2();
@RpcIdentifier(3)
void method3(Empty empty);
@RpcIdentifier(4)
Empty method4();
@RpcIdentifier(5)
Empty method5(Empty empty);
}
@Test(expected = DuplicateRpcServiceIdentifierException.class)
public void duplicateServiceIdentifierTest() throws DuplicateRpcMethodIdentifierException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException {
ProtobufRpcClient.Builder builder = new ProtobufRpcClient.Builder();
builder.registerService(DuplicateService01.class, DuplicateService02.class);
}
@Test(expected = DuplicateRpcMethodIdentifierException.class)
public void duplicateMethodIdentifierTest() throws DuplicateRpcMethodIdentifierException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException {
ProtobufRpcClient.Builder builder = new ProtobufRpcClient.Builder();
builder.registerService(DuplicateMethod01.class);
}
@Test(expected = MissingRpcIdentifierException.class)
public void missingIdentifierServiceTest() throws DuplicateRpcMethodIdentifierException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException {
ProtobufRpcClient.Builder builder = new ProtobufRpcClient.Builder();
builder.registerService(MissingIdentifierService.class);
}
@Test(expected = MissingRpcIdentifierException.class)
public void missingIdentifierMethodTest() throws DuplicateRpcMethodIdentifierException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException {
ProtobufRpcClient.Builder builder = new ProtobufRpcClient.Builder();
builder.registerService(MissingIdentifierMethod.class);
}
@Test
public void rpcMethodSignatureTest() throws DuplicateRpcMethodIdentifierException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException {
ProtobufRpcClient.Builder builder = new ProtobufRpcClient.Builder();
builder.registerService(RpcMethodSignature.class);
}
}<file_sep>package me.trinopoty.protobufRpc.exception;
public final class RpcCallException extends RuntimeException {
public RpcCallException() {
super();
}
public RpcCallException(String message) {
super(message);
}
public RpcCallException(String message, Throwable cause) {
super(message, cause);
}
public RpcCallException(Throwable cause) {
super(cause);
}
protected RpcCallException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}<file_sep>package me.trinopoty.protobufRpc.client;
import java.net.InetSocketAddress;
public interface ProtobufRpcClientChannel extends AutoCloseable {
/**
* Get an instance of service class that can be used to communicate with Rpc server.
*
* @param classOfService The class of the interface defining the service.
* @param <T> The type of the interface defining the service.
* @return An object of the service instance that can be used to communicate with Rpc server.
*/
<T> T getService(Class<T> classOfService);
/**
* Add a OOB message handler.
*
* @param classOfOob The class of the OOB interface.
* @param objectOfOob The instance of the OOB instance.
* @param <T>
*
* @throws IllegalArgumentException If provided OOB interface class is not registered.
*/
<T> void addOobHandler(Class<T> classOfOob, T objectOfOob);
/**
* Retrieves boolean value indicating if the connection is active.
*
* @return boolean value indicating whether the connection is active.
*/
boolean isActive();
/**
* Adds a listener for channel disconnect events.
*
* @param channelDisconnectListener The channel disconnect listener.
*/
void setChannelDisconnectListener(ProtobufRpcClientChannelDisconnectListener channelDisconnectListener);
/**
* Close the connection with the server.
*/
void close();
/**
* Gets the remote address of this connection.
*
* @return The remote address of this connection.
*/
InetSocketAddress getRemoteAddress();
}<file_sep>package me.trinopoty.protobufRpc.client;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.IdleStateHandler;
import me.trinopoty.protobufRpc.codec.RpcMessageCodec;
import java.util.concurrent.TimeUnit;
final class RpcClientChannelInitializer extends ChannelInitializer<SocketChannel> {
private static final int MAX_PACKET_LENGTH = 8 * 1024;
private final int mMaxReceivePacketLength;
private final SslContext mSslContext;
private final boolean mKeepAlive;
private final String mLoggingName;
private final boolean mEnableRpcLogging;
private final boolean mEnableTrafficLogging;
RpcClientChannelInitializer(
Integer maxReceivePacketLength,
SslContext sslContext,
boolean keepAlive,
String loggingName,
boolean enableRpcLogging,
boolean enableTrafficLogging) {
mMaxReceivePacketLength = (maxReceivePacketLength != null)? maxReceivePacketLength : MAX_PACKET_LENGTH;
mSslContext = sslContext;
mKeepAlive = keepAlive;
mLoggingName = loggingName;
mEnableRpcLogging = enableRpcLogging;
mEnableTrafficLogging = enableTrafficLogging;
}
@Override
protected void initChannel(SocketChannel socketChannel) {
ChannelPipeline pipeline = socketChannel.pipeline();
if(mSslContext != null) {
pipeline.addLast("ssl", mSslContext.newHandler(socketChannel.alloc()));
}
pipeline.addLast("protobuf-codec", new RpcMessageCodec(
mMaxReceivePacketLength,
true,
mLoggingName,
mEnableTrafficLogging,
mEnableTrafficLogging
));
if(mKeepAlive) {
pipeline.addLast("keep-alive", new IdleStateHandler(
true,
3000,
1500,
0,
TimeUnit.MILLISECONDS));
}
pipeline.addLast("handler", new RpcClientChannelHandler(
mLoggingName,
mEnableRpcLogging
));
}
}<file_sep>package me.trinopoty.protobufRpc.exception;
public final class ServiceConstructorNotFoundException extends Exception {
public ServiceConstructorNotFoundException() {
super();
}
public ServiceConstructorNotFoundException(String message) {
super(message);
}
public ServiceConstructorNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public ServiceConstructorNotFoundException(Throwable cause) {
super(cause);
}
protected ServiceConstructorNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}<file_sep>package me.trinopoty.protobufRpc.test;
import me.trinopoty.protobufRpc.annotation.RpcIdentifier;
import me.trinopoty.protobufRpc.client.ProtobufRpcClient;
import me.trinopoty.protobufRpc.client.ProtobufRpcClientChannel;
import me.trinopoty.protobufRpc.exception.*;
import me.trinopoty.protobufRpc.server.ProtobufRpcServer;
import me.trinopoty.protobufRpc.server.ProtobufRpcServerChannel;
import me.trinopoty.protobufRpc.test.proto.EchoOuterClass;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import static org.junit.Assert.assertNotNull;
public final class OobEchoTest {
@RpcIdentifier(1)
public interface EchoService {
@RpcIdentifier(1)
EchoOuterClass.Echo echo(EchoOuterClass.Echo request);
}
@RpcIdentifier(2)
public interface OobService {
@RpcIdentifier(1)
void oob1(EchoOuterClass.Echo message);
}
public static final class EchoServiceImpl implements EchoService {
private final ProtobufRpcServerChannel mRpcServerChannel;
public EchoServiceImpl(ProtobufRpcServerChannel rpcServerChannel) {
mRpcServerChannel = rpcServerChannel;
}
@Override
public EchoOuterClass.Echo echo(EchoOuterClass.Echo request) {
mRpcServerChannel.getOobService(OobService.class).oob1(request);
return request;
}
}
private static ProtobufRpcServer sProtobufRpcServer;
@SuppressWarnings("Duplicates")
@BeforeClass
public static void setup() throws DuplicateRpcMethodIdentifierException, ServiceConstructorNotFoundException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException, UnknownHostException {
ProtobufRpcServer.Builder builder = new ProtobufRpcServer.Builder();
builder.setLocalAddress(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0));
builder.addServiceImplementation(EchoService.class, EchoServiceImpl.class);
builder.registerOob(OobService.class);
ProtobufRpcServer server = builder.build();
server.startServer();
sProtobufRpcServer = server;
}
@AfterClass
public static void cleanup() {
sProtobufRpcServer.stopServer();
}
@Test
public void oobEchoTest01() throws DuplicateRpcMethodIdentifierException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException {
ProtobufRpcClient client = (new ProtobufRpcClient.Builder()).registerService(EchoService.class).registerOob(OobService.class).build();
ProtobufRpcClientChannel clientChannel = client.getClientChannel(sProtobufRpcServer.getActualLocalAddress());
EchoService echoService = clientChannel.getService(EchoService.class);
clientChannel.addOobHandler(OobService.class, new OobService() {
@Override
public void oob1(EchoOuterClass.Echo message) {
assertNotNull(message);
System.out.println("OOB: " + message.getMessage());
}
});
EchoOuterClass.Echo echo = echoService.echo(EchoOuterClass.Echo.newBuilder().setMessage("Hello World").build());
assertNotNull(echo);
clientChannel.close();
client.close();
}
}<file_sep>package me.trinopoty.protobufRpc;
public enum DisconnectReason {
CLIENT_CLOSE,
SERVER_CLOSE,
NETWORK_ERROR
}<file_sep>package me.trinopoty.protobufRpc.util;
import com.google.protobuf.AbstractMessage;
import me.trinopoty.protobufRpc.annotation.RpcIdentifier;
import me.trinopoty.protobufRpc.exception.DuplicateRpcMethodIdentifierException;
import me.trinopoty.protobufRpc.exception.DuplicateRpcServiceIdentifierException;
import me.trinopoty.protobufRpc.exception.IllegalMethodSignatureException;
import me.trinopoty.protobufRpc.exception.MissingRpcIdentifierException;
import me.trinopoty.protobufRpc.server.ProtobufRpcServerChannel;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public final class RpcServiceCollector {
public static final class RpcMethodInfo {
private Method mMethod;
private int mMethodIdentifier;
private Method mRequestMessageParser;
private Method mResponseMessageParser;
public Method getMethod() {
return mMethod;
}
public int getMethodIdentifier() {
return mMethodIdentifier;
}
public Method getRequestMessageParser() {
return mRequestMessageParser;
}
public Method getResponseMessageParser() {
return mResponseMessageParser;
}
}
public static final class RpcServiceInfo {
public enum ConstructorType {
DEFAULT,
PARAMETERIZED
}
private Class mServiceClass;
private int mServiceIdentifier;
private Map<Method, RpcMethodInfo> mMethodMap;
private Map<Integer, RpcMethodInfo> mMethodIdentifierMap;
private boolean mIsOob;
private Class mImplClass;
private Pair<ConstructorType, Constructor> mImplClassConstructor;
public Class getServiceClass() {
return mServiceClass;
}
public int getServiceIdentifier() {
return mServiceIdentifier;
}
public Map<Method, RpcMethodInfo> getMethodMap() {
return mMethodMap;
}
public Map<Integer, RpcMethodInfo> getMethodIdentifierMap() {
return mMethodIdentifierMap;
}
public boolean isOob() {
return mIsOob;
}
public Class getImplClass() {
return mImplClass;
}
public void setImplClass(Class implClass) {
mImplClass = implClass;
}
public void setImplClassConstructor(Pair<ConstructorType, Constructor> implClassConstructor) {
mImplClassConstructor = implClassConstructor;
}
public Object createImplClassObject(ProtobufRpcServerChannel rpcServerChannel) {
if(mImplClassConstructor != null) {
Object implObject = null;
try {
switch (mImplClassConstructor.getFirst()) {
case DEFAULT:
implObject = mImplClassConstructor.getSecond().newInstance();
break;
case PARAMETERIZED:
implObject = mImplClassConstructor.getSecond().newInstance(rpcServerChannel);
break;
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
throw new RuntimeException("Unable to create service implementation object.", ex);
}
return implObject;
} else {
throw new IllegalStateException("Implementation class is not set for service interface " + mServiceClass.getName());
}
}
}
private HashSet<Integer> mServiceIdentifierList = new HashSet<>();
private HashMap<Integer, Class> mServiceIdentifierClassMap = new HashMap<>();
private HashMap<Class, RpcServiceInfo> mServiceInfoMap = new HashMap<>();
public void parseServiceInterface(Class classOfService, boolean isOob) throws DuplicateRpcMethodIdentifierException, MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, IllegalMethodSignatureException {
if(!mServiceInfoMap.containsKey(classOfService)) {
RpcServiceInfo rpcServiceInfo = parseServiceClass(classOfService, isOob);
mServiceIdentifierList.add(rpcServiceInfo.getServiceIdentifier());
mServiceIdentifierClassMap.put(rpcServiceInfo.getServiceIdentifier(), rpcServiceInfo.getServiceClass());
mServiceInfoMap.put(classOfService, rpcServiceInfo);
}
}
public RpcServiceInfo getServiceInfo(Class classOfService) {
return mServiceInfoMap.get(classOfService);
}
public RpcServiceInfo getServiceInfo(int serviceIdentifier) {
if(mServiceIdentifierList.contains(serviceIdentifier)) {
return mServiceInfoMap.get(mServiceIdentifierClassMap.get(serviceIdentifier));
}
return null;
}
private synchronized RpcServiceInfo parseServiceClass(Class classOfService, boolean isOob) throws MissingRpcIdentifierException, DuplicateRpcServiceIdentifierException, DuplicateRpcMethodIdentifierException, IllegalMethodSignatureException {
RpcServiceInfo rpcServiceInfo = new RpcServiceInfo();
if(!classOfService.isInterface()) {
throw new IllegalArgumentException(String.format("Class<%s> is not an interface.", classOfService.getName()));
}
rpcServiceInfo.mServiceClass = classOfService;
Annotation rpcIdentifierAnnotation;
rpcIdentifierAnnotation = classOfService.getAnnotation(RpcIdentifier.class);
if(rpcIdentifierAnnotation == null) {
throw new MissingRpcIdentifierException(String.format("Class<%s> does not contain @RpcIdentifier annotation.", classOfService.getName()));
}
rpcServiceInfo.mIsOob = isOob;
rpcServiceInfo.mServiceIdentifier = ((RpcIdentifier) rpcIdentifierAnnotation).value();
if(mServiceIdentifierList.contains(rpcServiceInfo.mServiceIdentifier)) {
throw new DuplicateRpcServiceIdentifierException(String.format("Class<%s> contains duplicate @RpcIdentifier value. Duplicate class: %s", classOfService.getName(), mServiceIdentifierClassMap.get(rpcServiceInfo.mServiceIdentifier).getName()));
}
HashSet<Integer> methodIdentifierList = new HashSet<>();
HashMap<Method, RpcMethodInfo> rpcMethodInfoMap = new HashMap<>();
HashMap<Integer, RpcMethodInfo> rpcMethodInfoIdentifierMap = new HashMap<>();
for(Method method : classOfService.getDeclaredMethods()) {
RpcMethodInfo rpcMethodInfo = new RpcMethodInfo();
rpcMethodInfo.mMethod = method;
rpcIdentifierAnnotation = method.getAnnotation(RpcIdentifier.class);
if(rpcIdentifierAnnotation == null) {
throw new MissingRpcIdentifierException(String.format("Class<%s>.%s does not contain @RpcIdentifier annotation.", classOfService.getName(), method.getName()));
}
rpcMethodInfo.mMethodIdentifier = ((RpcIdentifier) rpcIdentifierAnnotation).value();
if(methodIdentifierList.contains(rpcMethodInfo.mMethodIdentifier)) {
throw new DuplicateRpcMethodIdentifierException(String.format("Class<%s>.%s contains duplicate @RpcIdentifier value.", classOfService.getName(), method.getName()));
} else {
methodIdentifierList.add(rpcMethodInfo.mMethodIdentifier);
}
if(method.getParameterTypes().length == 1) {
Class requestType = method.getParameterTypes()[0];
if(!AbstractMessage.class.isAssignableFrom(requestType)) {
throw new IllegalMethodSignatureException(String.format("Class<%s>.%s does not accept a protobuf message.", classOfService.getName(), method.getName()));
}
//noinspection unchecked
rpcMethodInfo.mRequestMessageParser = getProtobufParserMethod(requestType);
assert rpcMethodInfo.mRequestMessageParser != null;
} else if(method.getParameterTypes().length != 0) {
throw new IllegalMethodSignatureException(String.format("Class<%s>.%s has invalid method signature.", classOfService.getName(), method.getName()));
}
Class responseType = method.getReturnType();
if(!isOob) {
if(!responseType.equals(void.class)) {
if(!AbstractMessage.class.isAssignableFrom(responseType)) {
throw new IllegalMethodSignatureException(String.format("Class<%s>.%s does not return a protobuf message.", classOfService.getName(), method.getName()));
}
//noinspection unchecked
rpcMethodInfo.mResponseMessageParser = getProtobufParserMethod(responseType);
assert rpcMethodInfo.mResponseMessageParser != null;
}
} else {
if(!responseType.equals(void.class)) {
throw new IllegalMethodSignatureException(String.format("Class<%s>.%s does not return void.", classOfService.getName(), method.getName()));
}
}
rpcMethodInfoMap.put(method, rpcMethodInfo);
rpcMethodInfoIdentifierMap.put(rpcMethodInfo.mMethodIdentifier, rpcMethodInfo);
}
rpcServiceInfo.mMethodMap = Collections.unmodifiableMap(rpcMethodInfoMap);
rpcServiceInfo.mMethodIdentifierMap = Collections.unmodifiableMap(rpcMethodInfoIdentifierMap);
return rpcServiceInfo;
}
@SuppressWarnings("JavaReflectionMemberAccess")
private Method getProtobufParserMethod(Class<? extends AbstractMessage> messageClass) {
Method parserMethod = null;
try {
parserMethod = messageClass.getMethod("parseFrom", byte[].class);
} catch (NoSuchMethodException ignore) {
}
return parserMethod;
}
}
|
f593d3aaaa502262938963ab1121d0ec1da5f918
|
[
"Markdown",
"Java"
] | 11 |
Java
|
Crasader/protobuf-rpc
|
ae1c450619f8c8ada9c3238f26c054dd2a36cd41
|
25fe3f9abc2cd8ff8afe257708509ec594ca78f8
|
refs/heads/main
|
<repo_name>sh960440/GAME2014-F2020-Midterm-101212629<file_sep>/Assets/_Scripts/IApplyDamage.cs
/*******************
File name: IApplyDamage.cs
Author: <NAME>
Student Number: 101212629
Date last Modified: 2020/10/22
Program description: An interface applies the bullet damage.
Revision History:
2020/10/22
- Added internal documentation
Interface:
IApplyDamage
*******************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IApplyDamage
{
int ApplyDamage();
}
<file_sep>/Assets/_Scripts/BulletController.cs
/*******************
File name: BulletController.cs
Author: <NAME>
Student Number: 101212629
Date last Modified: 2020/10/22
Program description: A public class handles the bullet movement and collision.
Revision History:
2020/10/22
- Added internal documentation
- Modified _Move function.
- Modified _CheckBounds function.
Class:
BulletController
Functions:
Start
Update
_Move
_Checkbounds
OnTriggerEnter2D
ApplyDamage
*******************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour, IApplyDamage
{
public float verticalSpeed;
public float verticalBoundary;
public BulletManager bulletManager;
public int damage;
// Start is called before the first frame update
void Start()
{
bulletManager = FindObjectOfType<BulletManager>();
}
// Update is called once per frame
void Update()
{
_Move();
_CheckBounds();
}
private void _Move()
{
transform.position += new Vector3(verticalSpeed, 0.0f, 0.0f) * Time.deltaTime;
}
private void _CheckBounds()
{
if (transform.position.x > verticalBoundary)
{
bulletManager.ReturnBullet(gameObject);
}
}
public void OnTriggerEnter2D(Collider2D other)
{
//Debug.Log(other.gameObject.name);
bulletManager.ReturnBullet(gameObject);
}
public int ApplyDamage()
{
return damage;
}
}
<file_sep>/Assets/_Scripts/BackgroundController.cs
/*******************
File name: BackgroundController.cs
Author: <NAME>
Student Number: 101212629
Date last Modified: 2020/10/22
Program description: A pubilc class for the scrolling background.
Revision History:
2020/10/22
- Added internal documentation
- Modified the _CheckBounds function.
Class:
BackgroundController
Functions:
Update
_Reset
_Move
_Checkbounds
*******************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackgroundController : MonoBehaviour
{
public float verticalSpeed;
public float verticalBoundary;
// Update is called once per frame
void Update()
{
_Move();
_CheckBounds();
}
private void _Reset()
{
transform.position = new Vector3(verticalBoundary, 0.0f);
}
private void _Move()
{
transform.position -= new Vector3(verticalSpeed, 0.0f) * Time.deltaTime;
}
private void _CheckBounds()
{
// if the background is lower than the bottom of the screen then reset
if (transform.position.x <= -verticalBoundary)
{
_Reset();
}
}
}
<file_sep>/Assets/_Scripts/EnemyController.cs
/*******************
File name: EnemyController.cs
Author: <NAME>
Student Number: 101212629
Date last Modified: 2020/10/22
Program description: A public class controls the enemy's movement.
Revision History:
2020/10/22
- Added internal documentation
- Modified _Move function.
- Modified _CheckBounds function.
Class:
EnemyController
Functions:
Update
_Move
_CheckBounds
*******************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public float verticalSpeed;
public float verticalBoundary;
public float direction;
// Update is called once per frame
void Update()
{
_Move();
_CheckBounds();
}
private void _Move()
{
transform.position += new Vector3(0.0f, verticalSpeed * direction * Time.deltaTime, 0.0f);
}
private void _CheckBounds()
{
// check right boundary
if (transform.position.y >= verticalBoundary)
{
direction = -1.0f;
}
// check left boundary
if (transform.position.y <= -verticalBoundary)
{
direction = 1.0f;
}
}
}
<file_sep>/Assets/_Scripts/BulletType.cs
/*******************
File name: BulletType.cs
Author: <NAME>
Student Number: 101212629
Date last Modified: 2020/10/22
Program description: An enumeration includes different bullet types.
Revision History:
2020/10/22
- Added internal documentation
Enumeration:
BulletType
*******************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public enum BulletType
{
REGULAR,
FAT,
PULSING,
RANDOM
}
|
49920861ea5d1ae39a7d9ac3918156ed08d7dcd4
|
[
"C#"
] | 5 |
C#
|
sh960440/GAME2014-F2020-Midterm-101212629
|
9ba6679b25c44c37652f0aa6799eaccf6c7f1221
|
243720154b1951816f2fada1654b788e0a535883
|
refs/heads/master
|
<file_sep>#include <SFML/Graphics.hpp>
#include "State\stateManager.h"
#include "State\mainMenuState.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(1920, 1080), "SFML works!");
stateManager sManager;
sManager.requestChangeState(new mainMenuState(sManager));
sManager.changeState();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
sManager.update();
window.clear();
sManager.draw(window);
window.display();
sManager.changeState();
}
return 0;
}<file_sep>#include "stateManager.h"
stateManager::stateManager()
: currentState(NULL)
, requestedState (NULL)
{
}
stateManager::~stateManager()
{
if (currentState != NULL)
{
delete currentState;
}
}
void stateManager::draw(sf::RenderWindow &window)
{
if (currentState != NULL)
{
currentState->draw(window);
}
}
void stateManager::update()
{
if (currentState != NULL)
{
currentState->update();
}
}
void stateManager::requestChangeState(istate *newState)
{
requestedState = newState;
}
void stateManager::changeState()
{
if (requestedState == NULL)
return;
if (currentState != NULL)
{
delete currentState;
}
currentState = requestedState;
requestedState = NULL;
}<file_sep>#ifndef ISTATE_H
#define ISTATE_H
#include <SFML/Graphics.hpp>
class stateManager;
class istate
{
public:
istate() = delete;
istate(stateManager &manager) : sManager (manager) { }
virtual ~istate() { };
virtual void draw(sf::RenderWindow &window)=0;
virtual void update()=0;
protected:
stateManager &sManager;
};
#endif // !ISTATE_H
<file_sep>#ifndef STATEMANAGER_H
#define STATEMANAGER_H
#include "State\istate.h"
#include <SFML/Graphics.hpp>
class stateManager
{
public:
stateManager();
~stateManager();
void draw(sf::RenderWindow &window);
void update();
void requestChangeState(istate *newState);
//do not call this from a state, plz
void changeState();
private :
istate *currentState;
istate *requestedState;
};
#endif //statemanager<file_sep>#include "mainMenuState.h"
#include <SFML\Window\Keyboard.hpp>
#include "State\gameState.h"
#include "State\stateManager.h"
mainMenuState::mainMenuState(stateManager &manager)
: istate(manager)
, shape (100.0f)
{
shape.setFillColor(sf::Color::Green);
}
mainMenuState::~mainMenuState()
{
}
void mainMenuState::draw(sf::RenderWindow &window)
{
window.draw(shape);
}
void mainMenuState::update()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
{
sManager.requestChangeState(new gameState(sManager));
}
}<file_sep>#ifndef MAINMENUSTATE_H
#define MAINMENUSTATE_H
#include "State\istate.h"
class mainMenuState : public istate
{
public:
mainMenuState(stateManager &manager);
~mainMenuState();
virtual void draw(sf::RenderWindow &window);
virtual void update();
private:
sf::CircleShape shape;
};
#endif <file_sep>#include "gameState.h"
gameState::gameState(stateManager &manager)
: istate(manager)
, shape(100.0f)
{
shape.setFillColor(sf::Color::Blue);
}
gameState::~gameState()
{
}
void gameState::draw(sf::RenderWindow &window)
{
window.draw(shape);
}
void gameState::update()
{
}<file_sep># tetris
my first attempt at a game
<file_sep>#ifndef GAMESTATE_H
#define GAMESTATE_H
#include "State\istate.h"
class gameState : public istate
{
public:
gameState(stateManager &manager);
~gameState();
virtual void draw(sf::RenderWindow &window);
virtual void update();
private:
sf::CircleShape shape;
};
#endif
|
c87dad65da3559cf0763ad3310709a36570ecceb
|
[
"Markdown",
"C++"
] | 9 |
C++
|
Deandrea/tetris
|
ec8129dcd078ae837a1c1a9daf389172c01e896f
|
b5ab26d7fd88e2cc925991fc46b9e75b0e1d1d1b
|
refs/heads/master
|
<file_sep># Rashidrepos
simple fun codes
<file_sep>def allowed_dating_age(myage):
girls_age=myage/2 + 7
return girls_age
rash_limit=allowed_dating_age(28)
print("am allowed to date girls who are",rash_limit," years old or older")
<file_sep>import random
guessnumber = random.randint(1,20)
print('am thinking of a number between 1 and 20\n')
for number in range(1,7):
print('Take a guess')
guess = int(input())
if guess < guessnumber:
print('input is too low')
elif guess > guessnumber:
print('input is too high')
else:
break
if guess == guessnumber:
print('Good guess, you got the number in ' + guessnumber+ 'guesses')
else:
print('nop, the number in mind is ' + str(guessnumber))
<file_sep>import random
import time
def magic_ball():
response = ['you cant be serious','well i guess there is solution to your problem','i cant tell','yeah could be','not so sure','you are right','certainly not',
'the gues it right','yeah i still love her','i dont care','yes, of couse am with you']
while True:
question = str(input('Ask your mysterious question:\n'))
for i in range(0,4):
print('shaking the ball..')
time.sleep(0.30)
print(response[random.randint(0,len(response)-1)])
magic_ball()
<file_sep>alembic==1.0.5
atomicwrites==1.2.1
attrs==18.2.0
Click==7.0
colorama==0.4.1
Flask==1.0.2
Flask-Login==0.4.1
Flask-Migrate==2.3.1
Flask-SQLAlchemy==2.3.2
Flask-WTF==0.14.2
itsdangerous==1.1.0
Jinja2==2.10
Mako==1.0.7
MarkupSafe==1.1.0
more-itertools==4.3.0
Pillow==5.3.0
pluggy==0.8.0
py==1.7.0
pyparsing==2.3.0
pytest==4.0.1
python-dateutil==2.7.5
python-editor==1.0.3
six==1.11.0
SQLAlchemy==1.2.14
svgwrite==1.2.1
Tree==0.2.4
virtualenv==16.1.0
Werkzeug==0.14.1
WTForms==2.2.1
<file_sep>from app import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
__tablenam__ = 'users'
user_id = db.Column(db.Integer, primary_key = True, nullable = False)
name = db.Column(db.String(), nullable = False)
email = db.Column(db.String(), nullable = False)
password = db.Column(db.String(), nullable = False)
def __repr__(self):
return f'User{self.name}'
class Business(db.Model):
__tablenam__ = 'business'
id = db.Column(db.Integer, primary_key = True, nullable = False)
Business_name = db.Column(db.String(), nullable = False)
Business_location = db.Column(db.String(), nullable = False)
Business_owner = db.Column(db.String(), nullable = False)
Business_desc = db.Column(db.String(), nullable = False)
def __repr__(self):
return f'User: {self.business_name}, {self.Business_location}, {self.Business_owner}, {self.Business_desc}'<file_sep>birthdays = {'ben':'dec 12','rash':'Nov 21','hamis':'may 15', 'jijo':'dec 31','jemo':'dec 25'}
while True:
print('Enter blank space to quit')
name = input("Enter your friend's name:\n")
if name =='':
break
if name in birthdays:
print(birthdays [name] +' is the birthday of ' + name)
else:
print('There is no information for ' + name)
print('What his/her birthday?\n')
bday = input()
birthdays[name]= bday
print('data updated\n Thank you and have a great day')
<file_sep>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from app.models.user import *
class Register(FlaskForm):
username = StringField('Username', validators = [DataRequ ired(), Length(min = 2, max = 20)])
email = StringField('Email', validators = [DataRequired(), Email()])
password = PasswordField('<PASSWORD>', validators = [DataRequired()])
confirm_password = PasswordField('<PASSWORD>', validators = [DataRequired(), EqualTo('password')])
submit = SubmitField('sign up')
def validate_username(self, username):
user = user.query.filter_by(username = username.data).first()
if user:
raise ValidationError('username taken already')
def validate_email(self, Email):
user = user.query.filter_by(email = email.data).first()
if user:
raise ValidationError('email taken already')
#login formself
class LoginForm(FlaskForm):
email = StringField('Email', validators = [DataRequired(), Email()])
password = PasswordField('<PASSWORD>', validators = [DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
#business form
class BusinessForm(FlaskForm):
name = StringField('Business name', validators = [DataRequired()])
owner = StringField('Owners name', validators = [DataRequired()])
location = StringField('Location', validators = [DataRequired()])
date = StringField('date registered', validators = [DataRequired()])
<file_sep>from app import app, db, bcrypt
from flask import render_template, url_for, redirect
from flask_login import login_user, logout_user, current_user, login_required
from app.forms.register import Register
@app.route('/')
def home():
return render_template('home.html')
@app.route('/register', methods = ['GET','POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = Register()
if form.validate_on_submit():
user = User(username = form.username.data, email = form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash(f'Account for has been created', 'success')
return redirect(url_for('login'))
return render_template('signup.html', form =form)
@app.route('login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email = form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password):
login_user(user, remember = form.remember.data)
return redirect(url_for('home'))
else:
flash('login unsuccessful, check your credentials')
return render_template('login.html', title= 'login', form = form)
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('home'))
@app.route('/Business')
def new_business():
return render_template('business_reg.html')
|
c7b627347f3bde71492dfeb9080a46abdeb57a33
|
[
"Markdown",
"Python",
"Text"
] | 9 |
Markdown
|
Rashidramadhan/Rashidrepos
|
b2608976d90556e80ce1636fe23fcf94ff6c5ad0
|
c698f9549d0dda9d9669c82e52197b41cd3ccb78
|
refs/heads/master
|
<repo_name>ChimneySwift/name_colorize<file_sep>/README.md
# Automatic Name Colorization
Automatically generates colors based off names and colorizes them in chat.
## Idea
I know what you're thinking, "Jeeze, really, _another_ color chat CSM? Seriously man? If all I wanted to do was dick around with chat I'd select from the numerous other options, what's so different about this?". I'm glad you asked, some people might prefer manually setting colors, but I always forgot, name_colorize generates colors based off the user's name and colorizes their name through out all chat automatically.
Features:
- Colors stay the same for people with the same name (no matter what server)
- Colorizes regular messages, status messages, /me and join and leave messages
- Colorizes names mentioned in chat
Limitations:
- Will completely block all regular chat messages from making their way to other CSM
## The Algorithm
The color generation algorithm is subject to change (it's not particularly efficient), but does work for our purposes.
It's loosely based off the [please.js JavaScript library](https://github.com/ibarrajo/PleaseJS), basically it generates a hash of the name, then a hue from the hash and then combines preset saturation and value parameters to construct an HSV. It then converts the HSV to RGB based on [this gist](https://gist.github.com/raingloom/3cb614b4e02e9ad52c383dcaa326a25a), and then finally to hexadecimal based off the function used in [the colour_chat CSM](https://github.com/red-001/colour_chat/blob/master/init.lua).
This method doesn't create a wide enough range of colors for my liking, but does a good enough job for release, if you have any suggestions please submit a PR.
<file_sep>/init.lua
local online_players = {}
local saturation = 0.6
local value = 1
-- From: https://github.com/red-001/colour_chat/blob/master/init.lua
local function rgb_to_hex(rgb)
local hexadecimal = '#'
for key, value in pairs(rgb) do
local hex = ''
while(value > 0)do
local index = math.fmod(value, 16) + 1
value = math.floor(value / 16)
hex = string.sub('0123456789ABCDEF', index, index) .. hex
end
if(string.len(hex) == 0)then
hex = '00'
elseif(string.len(hex) == 1)then
hex = '0' .. hex
end
hexadecimal = hexadecimal .. hex
end
return hexadecimal
end
-- From: https://gist.github.com/raingloom/3cb614b4e02e9ad52c383dcaa326a25a
local function hsv_to_rgb(h, s, v)
h = h + math.pi/2
local r, g, b = 1, 1, 1
local h1, h2 = math.cos( h ), math.sin( h )
local r1, r2 = 0, 1.0
local g1, g2 = -math.sqrt( 3 )/2, -0.5
local b1, b2 = math.sqrt( 3 )/2, -0.5
--hue
r = h1*r1 + h2*r2
g = h1*g1 + h2*g2
b = h1*b1 + h2*b2
--saturation
r = r + (1-r)*s
g = g + (1-g)*s
b = b + (1-b)*s
r,g,b = r*v, g*v, b*v
return {math.floor(r*255), math.floor(g*255), math.floor(b*255)}
end
local function to_hash(str)
local hash = 0
str:gsub(".", function(c)
hash = c:byte() + hash
end)
return hash
end
local function get_color(str)
local hash = tostring(to_hash(str))
for i=4,1,-1 do
hash = tostring(to_hash(hash))
end
hash = tonumber(hash)
local hue = math.ceil(hash % 360)
return rgb_to_hex(hsv_to_rgb(hue, saturation, value))
end
minetest.register_on_receiving_chat_messages(function(message)
local message = minetest.strip_colors(message)
local original = message
-- Keep online player list updated
if message:sub(1, 4) == "*** " then
local parts = string.split(message, " ")
if parts then
if parts[3] == "joined" then
table.insert(online_players, parts[2])
elseif parts[3] == "left" then
for i, name in pairs(online_players) do
if name == parts[2] then
table.remove(online_players, i)
end
end
end
end
end
-- Initialize player list when server status message is sent
if message:sub(1, 2) == "# " then
local version, uptime, max_lag, clients = message:match("# Server: version=([^ ]+), uptime=([^ ]+), max_lag=([^ ]+), clients={(.+)}")
if clients then
online_players = string.split(clients, ", ")
local colored_clients = {}
for i, name in pairs(online_players) do
table.insert(colored_clients, minetest.colorize(get_color(name), name))
end
minetest.display_chat_message("# Server: version="..version..", uptime="..uptime..", max_lag="..max_lag..", clients={"..table.concat(colored_clients, ", ").."}")
return true
end
end
local name, msg
if message:sub(1, 1) == "<" then
name, msg = message:match("<([^ ]+)> (.+)")
if name then
name = minetest.colorize(get_color(name), "<"..name.."> ")
-- name = minetest.colorize(get_color(name), name..": ")
end
elseif message:sub(1, 2) == "* " or message:sub(1, 4) == "*** " then
local parts = string.split(message, " ", false, 2)
name = minetest.colorize(get_color(parts[2]), parts[1].." "..parts[2].." ")
msg = parts[3]
end
if msg then
for i, n in pairs(online_players) do
colorname = minetest.colorize(get_color(n), n)
msg = msg:gsub(n, colorname)
end
end
if name and msg then
minetest.display_chat_message(name..msg)
return true
end
end)
|
01ae1ff9d9d0f135f58376f1170f96438a3b323a
|
[
"Markdown",
"Lua"
] | 2 |
Markdown
|
ChimneySwift/name_colorize
|
ee16f12cd0a9cfd57cbcdf3a88c3bd85c8672975
|
30c5af5e4847077d96b9e8cd0e5799ba5870ba25
|
refs/heads/master
|
<file_sep># Practice of Algorithms and Data Structures
Created at: May 17, 2017
Created by: <NAME>
Language: Java 8 / Python 3
___________________________
<file_sep># this is for practicing some basic python functions
def subsetsWithDup(S):
S.sort()
res = set()
res.add(())
for elem in S:
res.add(tuple(subset) + (elem,) for subset in tuple(res))
return [[*subset] for subset in res]
res = subsetsWithDup([1,2,2,3,3,4])
print(res)<file_sep>/**
* Quick Selection
*
* Find K-th smallest number in O(n) time
*/
import java.util.*;
public class QuickSelect {
// public static int quickSelect(int[] arr, int rank) {
// int p = 0, r = arr.length - 1;
// while (p < r) {
// int index = partition(arr, p, r);
// if (index == rank) return arr[index];
// else if (index < rank) p = index + 1;
// else r = index - 1;
// }
// return arr[p];
// }
//
// private static int partition(int[] arr, int p, int r) {
// if (p == r) return p;
// int rand = (int)(Math.random() * (r - p + 1)) + p;
// swap(arr, r, rand);
// int pivot = arr[r];
// int i = p - 1, j = p;
// while (j <= r) {
// if (arr[j] <= pivot) swap(arr, ++i, j);
// j++;
// }
// return i;
// }
public static int quickSelect(int[] arr, int k) {
int left = 0, right = arr.length - 1;
while (true) {
int mid = partition(arr, left, right);
if (mid == k) return arr[mid];
else if (mid < k) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
// select the last number as pivot,
// put all numbers <= pivot to left,
// put all numbers > pivot to right,
// put pivot in the middle,
// return pivot's index
private static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j <= right; ++j) {
if (arr[j] <= pivot) swap(arr, ++i, j);
}
return i;
}
private static void swap(int[] arr, int p, int r) {
int t = arr[p];
arr[p] = arr[r];
arr[r] = t;
}
public static void main(String[] args) {
int[] arr = new int[] {9,4,2,8,7,6,5,4,3,2,1,2,3,12,56,23,5,1,3,7,9,4,21,4,6,8,3};
for (int i = 0; i < 10; ++i) {
int[] dup = Arrays.copyOf(arr, arr.length);
int a = quickSelect(dup, 17);
if (a != 7) {
System.out.println("error! " + a);
System.exit(1);
}
}
arr = new int[]{1};
if (quickSelect(arr, 0) == 1) {
System.out.println("pass {1}:0 -> 1");
}
arr = new int[]{1,2};
if (quickSelect(arr, 1) == 2) {
System.out.println("pass {1,2}:1 -> 2");
}
}
}
<file_sep>import java.util.*;
// // traditional Tree implementation
// class UnionFind {
// private class Node {
// int val, rank;
// Node parent;
// public Node(int val) {
// this.val = val;
// this.rank = 0;
// this.parent = this;
// }
// }
// private Map<Integer, Node> disjointSet;
//
// // if x is not already in the set, add x
// public void makeSet(int x) {
// if (disjointSet == null) disjointSet = new HashMap<>();
// if (! disjointSet.containsKey(x)) {
// disjointSet.put(x, new Node(x));
// }
// }
//
// public Node find(int x) {
// if (! disjointSet.containsKey(x)) return null;
// Node nodex = disjointSet.get(x);
// return find(nodex);
// }
// // find the root of x, do path compression along recursion
// private Node find(Node nodex) {
// // path compression
// if (nodex.parent == nodex) return nodex;
// nodex.parent = find(nodex.parent);
// return nodex.parent;
// }
//
// public void union(int x, int y) {
// Node rootx = find(x);
// Node rooty = find(y);
// if (rootx == null || rooty == null) return;
// // union by rank 优化
// if (rootx.rank < rooty.rank) {
// rootx.parent = rooty;
// } else if (rootx.rank > rooty.rank) {
// rooty.parent = rootx;
// } else {
// // 只有当合并之前两者rank相同的时候才需要增加rank
// rootx.parent = rooty;
// rooty.rank++;
// }
// }
//
// public static void main(String[] args) {
// // test
// UnionFind uf = new UnionFind();
// // 1,2,3,4,5 五个set
// uf.makeSet(1);
// uf.makeSet(2);
// uf.makeSet(3);
// uf.makeSet(4);
// uf.makeSet(5);
// // for (int i = 1; i < 6; ++i) System.out.println(uf.find(i).val);
//
// // 合并 1,2 以及 3,4,5
// uf.union(1,2);
// uf.union(3,4);
// uf.union(4,5);
// // for (int i = 1; i < 6; ++i) System.out.println(uf.find(i).val);
//
// // 合并 1,5
// uf.union(1, 5);
// for (int i = 1; i < 6; ++i) System.out.println(uf.find(i).val);
// }
// }
// int array implementation
// class UnionFind {
// private int[] ids; // index是id本身,val 存的是parent的index
// private int[] rank;
// public void makeSet(int maxSize) {
// ids = new int[maxSize];
// rank = new int[maxSize]; // 初始rank都为0
// for (int i = 0; i < ids.length; ++i) {
// // 初始时刻令每个元素的parent都指向自己
// ids[i] = i;
// }
// }
//
// public int find(int x) {
// if (ids[x] == x) {
// return x;
// } else {
// ids[x] = find(ids[x]);
// }
// return ids[x];
// }
//
// public void union(int x, int y) {
// // 先找到 x 和 y 的root
// int rootx = find(x);
// int rooty = find(y);
// // union by rank
// if (rank[rootx] < rank[rooty]) {
// ids[rootx] = rooty;
// } else if (rank[rooty] < rank[rootx]) {
// ids[rooty] = rootx;
// } else {
// ids[rootx] = rooty;
// rank[rooty]++;
// }
// }
class UnionFind {
private int[] ids;
private int[] rank;
public void makeSet(int maxSize) {
ids = new int[maxSize];
rank = new int[maxSize];
for (int i = 0; i < ids.length; ++i) ids[i] = i;
}
public int find(int id) {
if (ids[id] == id) return id;
while (ids[id] != id) {
id = ids[id];
}
return id;
}
public void union(int x, int y) {
int rootx = find(x);
int rooty = find(y);
if (rank[rootx] < rank[rooty]) ids[rootx] = rooty;
else if (rank[rootx] > rank[rooty]) ids[rooty] = rootx;
else {
ids[rootx] = rooty;
rank[rooty]++;
}
}
public static void main(String[] args) {
// test
UnionFind uf = new UnionFind();
// 1,2,3,4,5 五个set
uf.makeSet(6);
// for (int i = 1; i < 6; ++i) System.out.println(uf.find(i));
// 合并 1,2 以及 3,4,5
uf.union(1,2);
uf.union(3,4);
uf.union(4,5);
// for (int i = 1; i < 6; ++i) System.out.println(uf.find(i));
// 合并 1,5
uf.union(1, 5);
for (int i = 1; i < 6; ++i) System.out.println(uf.find(i));
}
}
|
4ea82ce9473d0c70143ef54e01b7eae99ed301fe
|
[
"Markdown",
"Java",
"Python"
] | 4 |
Markdown
|
Will-GXZ/Algorithm_Datastructures_Practice
|
43e92eabbacb01d1bbbbdaf073b2d9e72870bc8f
|
f491d382f099f947022ad1ce58885408457ed9e8
|
refs/heads/master
|
<file_sep><?php
include "header.php";
include "koneksi.php";
if(isset($_GET['user_id'])){
$query = mysqli_query($koneksi,"SELECT * from mhs WHERE id=".$_GET['user_id']);
$edit = mysqli_fetch_array($query);
}
?>
<form method="post" action="userDB.php">
<input type="hidden" name="user_id" value="<?php echo $_GET ['user_id'];?>">
<div class="row">
<div class="col-md-4 offset-4">
<div class="form-group">
<h1>edit</h1>
<label for="InputNama">Nama</label>
<input type="text" class="form-control" id="InputNama" placeholder="Enter Your Full Name" name="nama" value="<?php echo $edit['nama']; ?>" required>
<small id="InputNama" class="form-text text-muted">Please make sure your Name is correct</small>
</div>
<div class="form-group">
<label for="InputNPM">NPM</label>
<input type="text" class="form-control" id="InputNPM" placeholder="Enter Your NPM" name="npm" value="<?php echo $edit['npm']; ?>" required>
<small id="InputNPM" class="form-text text-muted">Please make sure your NPM is correct</small>
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" id="Username" placeholder="Enter Your Username" name="username" value="<?php echo $edit ['username']; ?>" required>
</div>
<div class="form-group">
<label for="PilihGender">Jenis Kelamin</label>
<select class="form-control" name="jenis_kelamin">
<option value="L">Laki-laki</option>
<option value="P">Perempuan</option>
</select>
</div>
<div class="form-group">
<label for="PilihJurusan">Jurusan</label>
<select class="form-control" name="jurusan">
<option value="teknik Informatika">Teknik Informatika</option>
<option value="Sistem Informasi">Sistem Informasi</option>
<option value="Sistem Komputer">Sistem Komputer</option>
</select>
</div>
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" placeholder="<EMAIL>" name="email" value="<?php echo $edit ['email']; ?>" required>
</div>
<div class="form-group">
<label for="InputTLP">Nomor Telepon</label>
<input type="text" class="form-control" name="no_tlp" placeholder="XXXX-XXXX-XXXX" value="<?php echo $edit ['no_telp']; ?>"required>
</div>
<div class="form-group">
<label for="Inputalamat">Alamat</label>
<input type="text" class="form-control" name="alamat" placeholder="alamat" value="<?php echo $edit ['alamat']; ?>"required>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="<PASSWORD>" class="form-control"placeholder="<PASSWORD>" name="password">
</div>
</div>
<button type="submit" class="btn btn-success my-2" name="edit">update</button>
</div>
</div>
</form>
<?php
include "footer.php";
?><file_sep><?php
include ("header.php");
// include("bootstrap.php");
require_once("koneksi.php");
?>
<main role="main">
<br>
<form method="post" action="userDB.php" id="formRegis">
<div class="row">
<div class="col-md-4 offset-4">
<div class="form-group">
<h1>Register</h1>
<label for="InputNama">Nama</label>
<input type="text" class="form-control" id="InputNama" placeholder="Masukkan Nama Lengkap Anda" name="nama">
<small id="InputNama" class="form-text text-muted">Pastikan Nama Anda benar</small>
</div>
<div class="form-group">
<label for="InputNPM">NPM</label>
<input type="text" class="form-control" id="InputNPM" placeholder="Masukkan NPM Anda" name="npm">
<small id="InputNPM" class="form-text text-muted">Pastikan NPM Anda benar</small>
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" id="InputUsername" placeholder="Masukkan Username Anda" name="username">
</div>
<div class="form-group">
<label for="PilihGender">Jenis Kelamin</label>
<select class="form-control" name="jenis_kelamin">
<option value="L">Laki-laki</option>
<option value="P">Perempuan</option>
</select>
</div>
<div class="form-group">
<label for="PilihJurusan">Jurusan</label>
<select class="form-control" name="jurusan">
<option value="teknik Informatika">Teknik Informatika</option>
<option value="Sistem Informasi">Sistem Informasi</option>
<option value="Sistem Komputer">Sistem Komputer</option>
</select>
</div>
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="text" class="form-control" id="InputEmail" placeholder="<EMAIL>" name="email">
</div>
<div class="form-group">
<label for="InputTLP">Nomor Telepon</label>
<input type="text" class="form-control" id="InputTLP" name="no_tlp" placeholder="XXXX-XXXX-XXXX">
</div>
<div class="form-group">
<label for="Inputalamat">Alamat</label>
<input type="text" class="form-control" id="Inputalamat" name="alamat" placeholder="Masukkan Alamat Anda">
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="<PASSWORD>" class="form-control" placeholder="Masukkan Password Anda" id="InputPassword" name="password">
</div>
<div class="form-group">
<label for="InputTanggal">Tanggal Lahir</label>
<input type="tanggalLahir" class="form-control" placeholder="XX/XX/XXXX" id="InputTanggal" name="tanggalLahir" >
</div>
</div>
<button type="submit" class="btn btn-success my-2" name="register">Register Now</button>
</div>
</div>
</form>
</main>
<?php
include 'footer.php';
?><file_sep><?php
include("header.php");
require_once("koneksi.php");
?>
<main role="main">
<br>
<form method="post" action="userDB.php">
<div class="row">
<div class="col-md-4 offset-4">
<div class="form-group">
<h1>add user</h1>
<label for="InputNama">Nama</label>
<input type="text" class="form-control" id="InputNama" placeholder="Enter Your Full Name" name="nama">
<small id="InputNama" class="form-text text-muted">Please make sure your Name is correct</small>
</div>
<div class="form-group">
<label for="InputNPM">NPM</label>
<input type="text" class="form-control" id="InputNPM" placeholder="Enter Your NPM" name="npm">
<small id="InputNPM" class="form-text text-muted">Please make sure your NPM is correct</small>
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" id="Username" placeholder="Enter Your Username" name="username">
</div>
<div class="form-group">
<label for="PilihGender">Jenis Kelamin</label>
<select class="form-control" name="jenis_kelamin">
<option value="L">Laki-laki</option>
<option value="P">Perempuan</option>
</select>
</div>
<div class="form-group">
<label for="PilihJurusan">Jurusan</label>
<select class="form-control" name="jurusan">
<option value="teknik Informatika">Teknik Informatika</option>
<option value="Sistem Informasi">Sistem Informasi</option>
<option value="Sistem Komputer">Sistem Komputer</option>
</select>
</div>
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" placeholder="<EMAIL>" name="email">
</div>
<div class="form-group">
<label for="InputTLP">Nomor Telepon</label>
<input type="text" class="form-control" name="no_tlp" placeholder="XXXX-XXXX-XXXX">
</div>
<div class="form-group">
<label for="Inputalamat">Alamat</label>
<input type="text" class="form-control" name="alamat" placeholder="alamat">
<div class="form-group">
<label for="<PASSWORD>">Password</label>
<input type="<PASSWORD>" class="form-control"placeholder="<PASSWORD>" name="<PASSWORD>">
</div>
</div>
<button type="submit" class="btn btn-success my-2" name="register">submit</button>
</div>
</div>
</form>
</main>
<?php
include ("footer.php");
?><file_sep><?php
$koneksi = mysqli_connect("localhost","root","","sidevitapp");
if($koneksi){
return true;
}else{
return false;
}
?><file_sep><?php
include 'header.php';
?>
<main role="main">
<!--BEGIN JUMBOTRON-->
<section class="jumbotron" style="background-image: url(gambar.png);">
<div class="container" style="margin-top: 3%">
<div class="row">
<div class="col-md-7">
<p class="lead" style="font-size: 50px; margin-top: 16%;">Bersama</p>
<p style=" margin-top: -7%; font-size: 70px">DevITApp</p>
<div style="color: white"><p style="font-size: 50px; margin-top: -6%">Belajar, Bersama, Berkarya</p>
<p></div>
<a href="register.php"><button type="button" class="btn btn-outline-light" style="font-size: 20px">Join Disini!!</button></a>
</p>
</div>
<div class="col-md-4">
<img src="source.png">
</div>
</div>
</div>
</section>
<!--END JUMBOTRON-->
<!--BEGIN CONTENT-->
<br><br><br><br><br><br>
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 style="text-align: center">Title one</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="col-md-6">
<h2 style="text-align: center">Title one</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 style="text-align: center">Title one</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="col-md-6">
<h2 style="text-align: center">Title one</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</div>
<br><br>
</main>
<?php
include 'footer.php';
?><file_sep><?php
include 'header.php'
?>
<div class="album py-5 bg-light">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" src="source.png" alt="Card image cap">
<div class="card-body">
<p class="card-text" style="text-align: center;"><a href="">nama anggota</a></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<?php
include 'footer.php'
?>
<file_sep> <?php
include "koneksi.php";
if(isset($_POST['register'])){
//$_post digunakan untuk mengumpulkan data dari bentuk dikirim dengan metode post
// fungsi isset() akan menghasilkan nilai true jika sebuah variabel telah didefinisi
$nama = $_POST['nama'];
$username = $_POST['username'];
$npm = $_POST['npm'];
$password = $_POST['<PASSWORD>'];
$email = $_POST['email'];
$jurusan = $_POST['jurusan'];
$no_tlp = $_POST['no_tlp'];
$alamat = $_POST['alamat'];
$jenis_kelamin =$_POST['jenis_kelamin'];
$tanggal = $_POST['tanggal'];
// INsert to database
$query = mysqli_query($koneksi,"INSERT INTO mhs(nama ,npm,username, password ,alamat,jenis_kelamin,email,no_telp)
VALUES('$nama','$npm','$username','$password','$alamat','$jenis_kelamin','$email','$no_tlp')");
if($query){
header("Location:tabel.php",true, 301);
die();
}
else{
echo "gagal". mysqli_error($koneksi);
}
}
if(isset($_POST['edit'])){
$userid=$_POST['user_id'];
$nama = $_POST['nama'];
$username = $_POST['username'];
$npm = $_POST['npm'];
$password = $_POST['<PASSWORD>'];
$email = $_POST['email'];
$jurusan = $_POST['jurusan'];
$no_tlp = $_POST['no_tlp'];
$alamat = $_POST['alamat'];
$jenis_kelamin =$_POST['jenis_kelamin'];
//INsert to database
$query = mysqli_query($koneksi,"update mhs set
nama='$nama',
npm='$npm',
username='$username',
password='<PASSWORD>',
alamat='$alamat',
jenis_kelamin='$jenis_kelamin',
email='$email',
no_telp='$no_tlp'
where id=" . $userid);
if($query){
header("Location:tabel.php",true, 301);
die();
}
else{
echo "gagal". mysqli_error($koneksi);
}
}
if(isset($_GET['user_id'])){
$query = mysqli_query($koneksi, "DELETE from mhs where id=" . $_GET['user_id']);
header("Location:tabel.php",true, 301);
die();
session_destroy();
}
?><file_sep><?php
include 'header.php'
?>
<br><br><br>
<div class="container">
<div class="col-md-10 offset-md-1">
<h2 style="text-align: center;">Tentang DevItApp</h2>
<p style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum sed, dicta nobis quisquam exercitationem? Nemo quas totam, a aspernatur excepturi recusandae nihil mollitia itaque modi doloremque. Officiis non, iure natus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates praesentium dignissimos doloribus. Repellat recusandae, ipsum ipsa deleniti vero, illum ea tenetur sint officia quam possimus sunt quidem libero nihil quos. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati aut amet, commodi est distinctio, magnam ea qui fugit minima voluptatem vitae ad quo, iure sapiente nemo. Eum fuga quas aliquam.</p>
</div>
</div>
<br><br>
<div class="container">
<div class="col-md-10 offset-md-1">
<h2 style="text-align: center;">Visi</h2>
<p style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum sed, dicta nobis quisquam exercitationem? Nemo quas totam, a aspernatur excepturi recusandae nihil mollitia itaque modi doloremque. Officiis non, iure natus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates praesentium dignissimos doloribus. Repellat recusandae, ipsum ipsa deleniti vero, illum ea tenetur sint officia quam possimus sunt quidem libero nihil quos. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati aut amet, commodi est distinctio, magnam ea qui fugit minima voluptatem vitae ad quo, iure sapiente nemo. Eum fuga quas aliquam.</p>
</div>
</div>
<br><br>
<div class="container">
<div class="col-md-10 offset-md-1">
<h2 style="text-align: center;">Misi</h2>
<p style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum sed, dicta nobis quisquam exercitationem? Nemo quas totam, a aspernatur excepturi recusandae nihil mollitia itaque modi doloremque. Officiis non, iure natus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates praesentium dignissimos doloribus. Repellat recusandae, ipsum ipsa deleniti vero, illum ea tenetur sint officia quam possimus sunt quidem libero nihil quos. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati aut amet, commodi est distinctio, magnam ea qui fugit minima voluptatem vitae ad quo, iure sapiente nemo. Eum fuga quas aliquam.</p>
</div>
</div>
<br><br>
<!--Start Struktur-->
<h2 style="text-align: center;">Struktur Kepengurusan</h2>
<div class="album py-3">
<div class="container">
<div class="row">
<div class="offset-md-3 col-md-3">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm image-fluid" alt="" height="250" width="250">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-3">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm image-fluid" alt="" height="250" width="250">
<a href="">Nama Pengurus</a>
</div>
</div>
</div>
</div>
<br>
<div class="container">
<div class="row">
<div class="offset-md-3 col-md-3">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm image-fluid" alt="" height="250" width="250">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-3">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm image-fluid" alt="" height="250" width="250">
<a href="">Nama Pengurus</a>
</div>
</div>
</div>
</div>
<br><br>
<div class="container">
<div class="row">
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
</div>
</div>
<br>
<div class="container">
<div class="row">
<div class="col-md-2">
e <div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="165" width="165">
<a href="">nama Pengurus</a>
</div>
</div>
</div>
</div>
<br><br><br>
<h2 style="text-align: center;">Galeri</h2>
<div class="container">
<div class="row">
<div class="offset-md-1 col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="offset-md-1 col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
<div class="col-md-2">
<div style="text-align: center;">
<img src="source.png" class="card-img-top; card mb-1 shadow-sm" alt="" height="180" width="180">
<a href="">nama Pengurus</a>
</div>
</div>
</div>
</div>
</div>
<?php
include 'footer.php'
?><file_sep><?php
include ("header.php");
?>
<div class= "container">
<div class="row" style="margin-top: 5%">
<div class="col-md-3">
<div class="card mb-4 shadow-sm">
<img src="image/devitapp.jpg" class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="Thumbnail [100%x225]" alt="Thumbnail [100%x225]" style="height: 225px; width: 100%; display: block;" src="" data-holder-rendered="true">
<div class="card-body">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-secondary" data-toogle="modal" data-target="#exampleModal"> View</button>
<button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
</div>
<small class="text-muted">9 mins</small>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card mb-4 shadow-sm">
<img src="image/madaPNG.png" class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="Thumbnail [100%x225]" style="height: 225px; width: 100%; display: block;" src="" data-holder-rendered="true">
<div class="card-body">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<!-- <button type="button" class="btn btn-sm btn-outline-secondary" data-toogle="modal" data-target="#exampleModal">View</button> -->
<button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
</div>
<small class="text-muted">9 mins</small>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card mb-4 shadow-sm">
<img src="image/madaPNG.png" class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="Thumbnail [100%x225]" style="height: 225px; width: 100%; display: block;" src="" data-holder-rendered="true">
<div class="card-body">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<!-- <button type="button" class="btn btn-sm btn-outline-secondary" data-toogle="modal" data-target="#exampleModal">View</button> -->
<button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
</div>
<small class="text-muted">9 mins</small>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card mb-4 shadow-sm">
<img src="image/devitapp.jpg" class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="Thumbnail [100%x225]" style="height: 225px; width: 100%; display: block;" src="" data-holder-rendered="true">
<div class="card-body">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<!-- <button type="button" class="btn btn-sm btn-outline-secondary" data-toogle="modal" data-target="#exampleModal">View</button> -->
<button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
</div>
<small class="text-muted">9 mins</small>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<?php
include ("footer.php")
?>
<file_sep><?php
require_once("koneksi.php");
if(isset($_POST['username']) and isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($koneksi, "SELECT * FROM mhs WHERE username='$username' and password='$password'");
if(mysqli_num_rows($query)){
header("Location:home.php",true, 301);
die();
}
else{
header("Location:formLogin.php?msg=Username atau Password salah");
}
}else{
header("Location:formLogin.php?msg=Username dan Password harus diisi");
}
?><file_sep><?php
include 'header.php';
?>
<p style="padding-top: 98px">
<h2 style="text-align: center;">Login</h2>
<form method="POST" action="actionlogin.php" id="formLogin">
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="nama" class="form-control" id="inputnama" name="username" aria-describedby="nama" placeholder="Masukkan username..">
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input type="<PASSWORD>" class="form-control" id="password" name="password" aria-describedby="emailHelp" placeholder="Masukkan Password..">
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<?php
if(isset($_GET['msg'])){
echo "
<div class='alert alert-danger alert-dismissible fade show' role='alert'>
<button type='button' class='close' data-dismiss='alert' aria-label='close'>
<span aria-hidden='true'>×</span>
</button>
<strong>Username atau Password salah.</strong>
</div>
";
}
?>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</div>
</div>
</form>
<br>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<p style="text-align: left;">if you dont have account <a href="register.php">Click Here!!</a></p>
</div>
</div>
</div>
<?php
include 'footer.php'
?><file_sep><?php
include ("header.php");
?>
<main role="main">
<div class="container">
<h2>Tabel User</h2>
<a href="adduser.php" class="btn btn-primary">create new user</a>
<table class="table table-condensed">
<thead>
<tr>
<th>Nama</th>
<th>NPM</th>
<th>Username</th>
<th>Alamat</th>
<th>Jenis Kelamin</th>
<th>Email</th>
<th>No telpon</th>
<th>Config</th>
</tr>
</thead>
<tbody>
<?php
include "koneksi.php";
$query=mysqli_query($koneksi, "select * from mhs"); //digunakan untuk memberikan perintah query ke MySql
while ($data = mysqli_fetch_array($query)) { //perintah yg digunakan untuk menampilkan data dari fungsi mysqli_query menggunakan while ketika menampilkan data lebih dari satu
?>
<tr>
<td><?php echo $data['nama']; ?></td>
<td><?php echo $data['npm']; ?></td>
<td><?php echo $data['username']; ?></td>
<td><?php echo $data['alamat']; ?></td>
<td><?php echo $data['jenis_kelamin']; ?></td>
<td><?php echo $data['email']; ?></td>
<td><?php echo $data['no_telp'];?></td>
<td>
<a href="edituser.php?user_id=<?php echo $data ['id']; ?>" class="btn btn-secondary">edit</a>
<a href="userDB.php?user_id=<?php echo $data ['id']; ?>" class="btn btn-danger">delete</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</main>
<?php
include "footer.php";
?><file_sep><?php
include 'header.php';
?>
<p style="padding-top: 98px">
<h2 style="text-align: center;">Registrasi</h2>
<form>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Nama</label>
<input type="nama" class="form-control" id="inputnama" aria-describedby="nama" placeholder="Masukkan nama lengkap..">
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Masukkan email..">
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Masukkan kata sandi..">
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<button type="submit" class="btn btn-primary">Daftar</button>
</div>
</div>
</div>
</form>
<p>
<br><br><br>
<?php
include 'footer.php'
?><file_sep><form action="uploadgambar.php" method="post" enctype="multipart/form-data">
<input type="file" name="gambar" accept="image/*">
<input type="submit" name="submit">
</form>
<?php
require_once("koneksi.php");
if (isset($_POST['submit'])){
//mindah file ke server folder project
move_uploaded_file($_FILES['gambar']['tmp_name'],'image/'.$_FILES['gambar']['name']);
//insert path file ke database
mysqli_query($koneksi, "INSERT INTO galeri (path_gambar) VALUES ('". 'image/'.$_FILES['gambar']['name'] ."')");
}
//nampil gambar
$query = mysqli_query($koneksi, "SELECT * FROM galeri");
if(mysqli_num_rows($query)>0){
while ($data = mysqli_fetch_array($query)) {
echo "<img src='".$data['path_gambar']."' alt='gambar'/>";
}
}
?>
|
1d2b1d9c51b9f6dc12bfaca19457d51ec6b13361
|
[
"PHP"
] | 14 |
PHP
|
joshuanatanielnm/WebDevITapp
|
a53e46edc9b832591fa825025669736e1a0b10d5
|
5bc80c556e085a75bca5f773df9c6b8a9dfd7e1b
|
refs/heads/main
|
<file_sep>package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"tweet-image-downloader/entity"
"tweet-image-downloader/utility"
"github.com/joho/godotenv"
)
var userNameF = flag.String("u", "_kz_dev", "input user name")
var keywordF = flag.String("k", "最新話です!", "input keyword which target tweet has")
var maxF = flag.Int("m", 50, "input number of maximum tweets you want between 10 and 100")
func main() {
/*
1. コマンドのフラグでツイート検索条件を取得
2. 条件より、目的の画像を持つツイートを取得
3. ツイートから目的の画像のリンク一覧を取得
4. 3のリンク一覧から、画像を自身のファイルに書き込む
*/
// 1. コマンドで条件を取得
flag.Parse()
con := utility.Conditions{
UserName: *userNameF,
Keyword: *keywordF,
Max: *maxF,
}
if err := con.ValidateConditions(); err != nil {
log.Fatal(err)
}
// 2. 条件より、目的の画像を持つツイートを取得
err := godotenv.Load()
if err != nil {
log.Fatal("error: loading .env file")
}
httpClient := &http.Client{}
client := utility.NewTwitterClient(os.Getenv("BEARER_TOKEN"), httpClient)
res, err := client.GetTweets(con)
if err != nil {
log.Fatal(err)
}
if len(res.Tweets) == 0 {
log.Fatal(entity.ErrorNoTweet)
}
// 3. 最新ツイートから目的の画像のリンク一覧を取得
links := make([]string, 0, 4)
tweet := latestTweet(res.Tweets)
for _, key := range tweet.Attachments.MediaKeys {
for _, media := range res.Includes.Media {
if key == media.MediaKey {
links = append(links, media.URL)
}
}
}
// 4. 3のリンク一覧から、画像を自身のファイルに書き込む
for i, link := range links {
res, err := http.Get(link)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
f, err := os.Create(fmt.Sprintf("%d.jpg", i))
if err != nil {
log.Fatal(err)
}
defer f.Close()
io.Copy(f, res.Body)
}
fmt.Println("Finish!")
}
func latestTweet(tweets []entity.Tweet) entity.Tweet {
var latestTweet entity.Tweet = tweets[0]
for _, tweet := range tweets {
if latestTweet.CreatedAt.After(tweet.CreatedAt) {
latestTweet = tweet
}
}
return latestTweet
}
<file_sep>package entity
import (
"errors"
"fmt"
)
var (
ErrorInputMaxFlag error = errors.New("error: you should input number between 10 and 100")
ErrorInputUserNameFlag error = errors.New("error: you should input user name")
ErrorLoadEnv error = errors.New("error: you didn't get any tweet. check url parameters")
ErrorNoTweet error = errors.New("error: you didn't get any tweet. check url parameters")
ErrorEmptyParameterValue error = errors.New("error: url parameter has empty value")
)
func ErrorIsnotIdealStatusCode(code int) error {
return fmt.Errorf("error: status code is not 200. result is %d", code)
}
<file_sep>package utility_test
import (
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"testing"
"time"
"tweet-image-downloader/entity"
mock "tweet-image-downloader/mock/utility"
"tweet-image-downloader/utility"
"github.com/golang/mock/gomock"
)
func Test_GetTweets(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
type input struct {
con utility.Conditions
setup func() *mock.MockHttpClient
}
correctCreatedAt, _ := time.Parse(time.RFC3339Nano, "2021-03-19T19:59:10.000Z")
tests := []struct {
name string
input input
want *entity.TweetResponse
hasErr bool
}{
{
name: "failed to send request",
input: input{
con: utility.Conditions{
UserName: "sample",
Keyword: "sample",
Max: 50,
},
setup: func() *mock.MockHttpClient {
m := mock.NewMockHttpClient(ctrl)
m.EXPECT().Do(gomock.Any()).Return(
nil,
errors.New("error: failed to send request"),
)
return m
},
},
want: nil,
hasErr: true,
},
{
name: "failed with StatusCode",
input: input{
con: utility.Conditions{
UserName: "sample",
Keyword: "sample",
Max: 50,
},
setup: func() *mock.MockHttpClient {
m := mock.NewMockHttpClient(ctrl)
m.EXPECT().Do(gomock.Any()).Return(
&http.Response{
StatusCode: http.StatusBadRequest,
},
errors.New("error: status code is not 200"),
)
return m
},
},
want: nil,
hasErr: true,
},
{
name: "failed when json unmarshal",
input: input{
con: utility.Conditions{
UserName: "sample",
Keyword: "sample",
Max: 50,
},
setup: func() *mock.MockHttpClient {
body := `{
"sample": "sample",
}`
m := mock.NewMockHttpClient(ctrl)
m.EXPECT().Do(gomock.Any()).Return(
&http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(body)),
},
nil,
)
return m
},
},
want: nil,
hasErr: true,
},
{
name: "success",
input: input{
con: utility.Conditions{
UserName: "sample",
Keyword: "sample",
Max: 50,
},
setup: func() *mock.MockHttpClient {
body := `{
"data": [
{
"id": "1",
"text": "sample",
"created_at": "2021-03-19T19:59:10.000Z",
"attachments": {
"media_keys": ["100", "200"]
}
}
],
"includes": {
"media": [
{
"media_key": "100",
"url": "http://sample.com/sample1.html"
},
{
"media_key": "200",
"url": "http://sample.com/sample2.html"
}
]
}
}`
m := mock.NewMockHttpClient(ctrl)
m.EXPECT().Do(gomock.Any()).Return(
&http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(body)),
},
nil,
)
return m
},
},
want: &entity.TweetResponse{
Tweets: []entity.Tweet{
{
ID: "1",
Text: "sample",
CreatedAt: correctCreatedAt,
Attachments: struct {
MediaKeys []string "json:\"media_keys\""
}{
MediaKeys: []string{"100", "200"},
},
},
},
Includes: struct {
Media []struct {
MediaKey string "json:\"media_key\""
URL string "json:\"url\""
} "json:\"media\""
}{
Media: []struct {
MediaKey string "json:\"media_key\""
URL string "json:\"url\""
}{
{
MediaKey: "100",
URL: "http://sample.com/sample1.html",
},
{
MediaKey: "200",
URL: "http://sample.com/sample2.html",
},
},
},
},
hasErr: false,
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("%d: %s", i, test.name), func(t *testing.T) {
c := utility.NewTwitterClient("sample", test.input.setup())
tweets, err := c.GetTweets(test.input.con)
if (err != nil) != test.hasErr {
t.Errorf("failed to match for error: result is %v, hasErr is %v, err content is %v", (err != nil), test.hasErr, err)
}
if !isSameContent(tweets, test.want, t) {
t.Errorf("failed to match for response: result is %v, want is %v", tweets, test.want)
}
})
}
}
func isSameContent(a, b *entity.TweetResponse, t *testing.T) bool {
// nilの場合
if a == nil && b == nil {
return true
}
if a != nil && b == nil {
return false
}
if a == nil && b != nil {
return false
}
// 中身の比較
if len(a.Tweets) != len(b.Tweets) {
t.Logf("number of tweets is not matched: result is %v, want is %v", len(a.Tweets), len(b.Tweets))
return false
}
if !reflect.DeepEqual(a.Includes, b.Includes) {
t.Logf("includes is not matched: result is %v, want is %v", a.Includes, b.Includes)
return false
}
for i := 0; i < len(a.Tweets); i++ {
if a.Tweets[i].ID != b.Tweets[i].ID {
t.Logf("tweet id is not matched: result is %v, want is %v", a.Tweets[i].ID, b.Tweets[i].ID)
return false
}
if a.Tweets[i].Text != b.Tweets[i].Text {
t.Logf("tweet text is not matched: result is %v, want is %v", a.Tweets[i].Text, b.Tweets[i].Text)
return false
}
if !a.Tweets[i].CreatedAt.Equal(b.Tweets[i].CreatedAt) {
t.Logf("tweet created_at is not matched: result is %v, want is %v", a.Tweets[i].CreatedAt, b.Tweets[i].CreatedAt)
return false
}
if !reflect.DeepEqual(a.Tweets[i].Attachments, b.Tweets[i].Attachments) {
t.Logf("tweet attatchments is not matched: result is %v, want is %v", a.Tweets[i].Attachments, b.Tweets[i].Attachments)
return false
}
}
return true
}
func Test_CreateResponse(t *testing.T) {
tests := []struct {
name string
input utility.Conditions
want string
hasErr bool
}{
{
name: "success",
input: utility.Conditions{
UserName: "sample",
Keyword: "sample",
Max: 50,
},
want: "expansions=attachments.media_keys&max_results=50&media.fields=media_key%2Curl&query=has%3Aimages+-is%3Aretweet+from%3Asample+%22sample%22&tweet.fields=created_at%2Cattachments",
},
{
name: "success without keyword",
input: utility.Conditions{
UserName: "sample",
Max: 50,
},
want: "expansions=attachments.media_keys&max_results=50&media.fields=media_key%2Curl&query=has%3Aimages+-is%3Aretweet+from%3Asample&tweet.fields=created_at%2Cattachments",
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("%d: %s", i, test.name), func(t *testing.T) {
req, err := utility.ExportCreateResponse(&utility.TwitterClient{}, test.input)
if (err != nil) != test.hasErr {
t.Errorf("failed to match for error: result is %v, hasErr is %v, err content is %v", (err != nil), test.hasErr, err)
}
result := req.URL.Query().Encode()
if result != test.want {
t.Errorf("failed to match for request: result is %v, want is %v", result, test.want)
}
})
}
}
<file_sep>module tweet-image-downloader
go 1.17
require (
github.com/golang/mock v1.6.0
github.com/joho/godotenv v1.4.0 // indirect
)
<file_sep>//go:generate mockgen -source=$GOFILE -destination=../mock/$GOPACKAGE/$GOFILE
package utility
import "net/http"
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}
<file_sep>package entity
import (
"fmt"
"time"
)
// query parametersの"expasions"に関する設定
type ExpansionField string
type ExpansionFields []ExpansionField
const (
ExpasionFieldMediaKeys ExpansionField = "attachments.media_keys"
)
func (e ExpansionField) toString() string {
return string(e)
}
func (es ExpansionFields) ToStringSlice() []string {
slice := make([]string, len(es))
for i, e := range es {
slice[i] = e.toString()
}
return slice
}
// query parametersの"media.fields"に関する設定
type MediaField string
type MediaFields []MediaField
const (
MediaFieldMediaKey MediaField = "media_key"
MediaFieldURL MediaField = "url"
)
func (m MediaField) toString() string {
return string(m)
}
func (ms MediaFields) ToStringSlice() []string {
slice := make([]string, len(ms))
for i, m := range ms {
slice[i] = m.toString()
}
return slice
}
// query parametersの"query"に関する設定
type QueryField string
type QueryFields []QueryField
const (
QueryFieldHasImages QueryField = "has:images"
QueryFieldIsRetweet QueryField = "is:retweet"
)
func (q QueryField) toString() string {
return string(q)
}
func QueryFieldFrom(user string) QueryField {
return QueryField(fmt.Sprintf("from:%s", user))
}
func QueryFieldKeyword(keyword string) QueryField {
return QueryField(fmt.Sprintf("\"%s\"", keyword))
}
func (q QueryField) NOT() QueryField {
return QueryField(fmt.Sprintf("-%v", q))
}
func (qs QueryFields) ToStringSlice() []string {
slice := make([]string, len(qs))
for i, q := range qs {
slice[i] = q.toString()
}
return slice
}
// query parametersの"tweet.fields"に関する設定
type TweetField string
type TweetFields []TweetField
const (
TweetFieldAttachments TweetField = "attachments"
TweetFieldCreatedAt TweetField = "created_at"
)
func (t TweetField) toString() string {
return string(t)
}
func (ts TweetFields) ToStringSlice() []string {
slice := make([]string, len(ts))
for i, t := range ts {
slice[i] = t.toString()
}
return slice
}
// responseに関する設定
type Tweet struct {
ID string `json:"id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
Attachments struct {
MediaKeys []string `json:"media_keys"`
} `json:"attachments"`
}
type TweetResponse struct {
Tweets []Tweet `json:"data"`
Includes struct {
Media []struct {
MediaKey string `json:"media_key"`
URL string `json:"url"`
} `json:"media"`
} `json:"includes"`
}
<file_sep>package utility
import (
"net/url"
"regexp"
"strconv"
"strings"
"tweet-image-downloader/entity"
)
type ParamBuilder struct {
url.Values
}
func NewParamBuilder() *ParamBuilder {
p := ParamBuilder{}
p.Values = url.Values{}
return &p
}
func (p *ParamBuilder) Expansions(fields entity.ExpansionFields) *ParamBuilder {
p.Add("expansions", strings.Join(fields.ToStringSlice(), ","))
return p
}
func (p *ParamBuilder) MaxResults(val int) *ParamBuilder {
p.Add("max_results", strconv.Itoa(val))
return p
}
func (p *ParamBuilder) MediaFields(fields entity.MediaFields) *ParamBuilder {
p.Add("media.fields", strings.Join(fields.ToStringSlice(), ","))
return p
}
func (p *ParamBuilder) Query(fields entity.QueryFields) *ParamBuilder {
// 複数の演算子を一つのクエリにまとめるには、
// コンマ(",")ではなくANDを意味する空白(" ")を用いる
p.Add("query", strings.Join(fields.ToStringSlice(), " "))
return p
}
func (p *ParamBuilder) TweetFields(fields entity.TweetFields) *ParamBuilder {
p.Add("tweet.fields", strings.Join(fields.ToStringSlice(), ","))
return p
}
func (p *ParamBuilder) Build() (string, error) {
encoded, err := p.validateEmptyParamValue()
return encoded, err
}
func (p *ParamBuilder) validateEmptyParamValue() (string, error) {
e := p.Encode()
r := regexp.MustCompile(`(?i)(expansions|media.fields|query|tweet.fields)=(&|$)`)
if r.MatchString(e) {
return e, entity.ErrorEmptyParameterValue
}
return e, nil
}
<file_sep>package utility
import (
"encoding/json"
"fmt"
"io"
"net/http"
"tweet-image-downloader/entity"
)
type TwitterClient struct {
token string
httpClient HttpClient
}
var baseURL string = "https://api.twitter.com/2/tweets/search/recent"
func NewTwitterClient(token string, hClient HttpClient) *TwitterClient {
return &TwitterClient{
token: token,
httpClient: hClient,
}
}
func (t *TwitterClient) GetTweets(con Conditions) (*entity.TweetResponse, error) {
// リクエストの作成
req, err := t.createRequest(con)
if err != nil {
return nil, err
}
// APIエンドポイントにリクエストを投げる
resp, err := t.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, entity.ErrorIsnotIdealStatusCode(resp.StatusCode)
}
// レスポンスの読み取り
defer resp.Body.Close()
jsonBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
data := new(entity.TweetResponse)
if err := json.Unmarshal(jsonBytes, data); err != nil {
return nil, err
}
return data, nil
}
func (t *TwitterClient) createRequest(con Conditions) (*http.Request, error) {
// apiのurlパラメータの設定
queryFields := entity.QueryFields{
entity.QueryFieldHasImages,
entity.QueryFieldIsRetweet.NOT(),
entity.QueryFieldFrom(con.UserName),
}
if len(con.Keyword) != 0 {
queryFields = append(queryFields, entity.QueryFieldKeyword(con.Keyword))
}
expansionFields := entity.ExpansionFields{
entity.ExpasionFieldMediaKeys,
}
mediaFields := entity.MediaFields{
entity.MediaFieldMediaKey,
entity.MediaFieldURL,
}
tweetFields := entity.TweetFields{
entity.TweetFieldCreatedAt,
entity.TweetFieldAttachments,
}
params, err := NewParamBuilder().
Query(queryFields).
MaxResults(con.Max).
Expansions(expansionFields).
MediaFields(mediaFields).
TweetFields(tweetFields).Build()
if err != nil {
return nil, err
}
// リクエストの作成
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s?%s", baseURL, params), nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", t.token))
return req, nil
}
type Conditions struct {
UserName string
Keyword string
Max int
}
func (c Conditions) ValidateConditions() error {
if !c.validateKeywordLength() {
return entity.ErrorInputUserNameFlag
}
if !c.validateMaxFieldValue() {
return entity.ErrorInputMaxFlag
}
return nil
}
func (c Conditions) validateMaxFieldValue() bool {
if 10 <= c.Max && c.Max <= 100 {
return true
}
return false
}
func (c Conditions) validateKeywordLength() bool {
return len(c.Keyword) > 0
}
<file_sep>package utility_test
import (
"fmt"
"testing"
"tweet-image-downloader/entity"
"tweet-image-downloader/utility"
)
func Test_ValidateEmptyParamValue(t *testing.T) {
tests := []struct {
name string
input *utility.ParamBuilder
want error
}{
{
name: "failed cause of expansion Parameter Value is empty",
input: utility.NewParamBuilder().Expansions(entity.ExpansionFields{}),
want: entity.ErrorEmptyParameterValue,
},
{
name: "failed cause of media.fields Parameter Value is empty",
input: utility.NewParamBuilder().MediaFields(entity.MediaFields{}),
want: entity.ErrorEmptyParameterValue,
},
{
name: "failed cause of query Parameter Value is empty",
input: utility.NewParamBuilder().Query(entity.QueryFields{}),
want: entity.ErrorEmptyParameterValue,
},
{
name: "failed cause of tweet.fields Parameter Value is empty",
input: utility.NewParamBuilder().TweetFields(entity.TweetFields{}),
want: entity.ErrorEmptyParameterValue,
},
{
name: "failed cause of tweet.fields Parameter Value is empty, but query Parameter Value is not empty",
input: utility.NewParamBuilder().TweetFields(entity.TweetFields{}).Query(entity.QueryFields{
entity.QueryFieldHasImages,
}),
want: entity.ErrorEmptyParameterValue,
},
{
name: "success only one parameter",
input: utility.NewParamBuilder().Query(entity.QueryFields{entity.QueryFieldHasImages}),
want: nil,
},
{
name: "success when multiple parameters",
input: utility.NewParamBuilder().
Query(entity.QueryFields{
entity.QueryFieldHasImages,
entity.QueryFieldFrom("test"),
}).
TweetFields(entity.TweetFields{
entity.TweetFieldCreatedAt,
entity.TweetFieldAttachments,
}),
want: nil,
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("%d: %s", i, test.name), func(t *testing.T) {
if str, err := utility.ExportValidateEmptyParamValue(test.input); err != test.want {
t.Errorf("failed to validate: str is %v, result is %v, want is %v", str, err, test.want)
}
})
}
}
<file_sep># tweet-image-downloader
このプログラムは推しの漫画家の最新話をGoとTwitterAPIを利用してダウンロードするプログラムです。ぱっとお試し程度に作りましたので問題点などがあれば、Pull Requestをぜひ投げてください!
- ※**コードによるテスト**は最低限の内容しか行っていないので、実際に利用になる際にはご自身でも動作確認をお願いします。(Pull Requestでテストを送ってくださると助かります)
```
- ParameterBuilderの`validateEmptyParamValue`
- httpリクエストやレスポンスをmock化したTwitterClientの`GetTweets`
- TwitterClientの`createResponse`
```
# How to use
1. create `.env` file.
```terminal
$ cp .env.exmaple .env
```
2. set your `Bearer Token` into `.env`
```.env
BEARER_TOKEN="your Bearer Token"
```
3. execute command with some options
```terminal
<!-- オプションの確認 -->
$ go run main.go -h
~~
-k string
input keyword which target tweet has (default "最新話です!")
-m int
input number of maximum tweets you want between 10 and 100 (default 50)
-u string
input user name (default "_kz_dev")
<!-- 好きなようにオプションをつけて実行 -->
$ go run main.go -k=hogehoge -m=100 -u=hogehoge
```<file_sep>package utility
import "net/http"
var ExportValidateEmptyParamValue func(*ParamBuilder) (string, error) = (*ParamBuilder).validateEmptyParamValue
var ExportCreateResponse func(*TwitterClient, Conditions) (*http.Request, error) = (*TwitterClient).createRequest
|
e57815c80d9d71241776cf891bba2a181b53eb9a
|
[
"Markdown",
"Go Module",
"Go"
] | 11 |
Go
|
kazdevl/tweet-image-downloader
|
2ca89e840414e367397fa02896f4be0ac68c17c0
|
2cb272c70ed66d2650d8d291025c77d264705f35
|
refs/heads/master
|
<file_sep>/* Name: main.c 2.3.2 Motor control
* Design of Mechatronic Systems - University of Pennsylvania
* Fall 2018
* Author: <NAME>
*/
#include "teensy_general.h" // includes the resources included in the teensy_general.h file
#include "t_usb.h"
// void setupADC(void); //declaring a function
// void readADC(int n);
int main(void)
{
teensy_clockdivide(0); // set the clock speed
teensy_led(ON); // turn on the on board LED
teensy_wait(1000);// wait 1000 ms when at 16 MHz
/*initializing variables*/
ICR1 = 1250; //sets motor 1 frequency (not actual freq. val)
ICR3 = 1250; //sets motor 2 frequency (not actual freq. val)
int rampA = 1;
int rampB = 1;
int dir1 = 0;
int dir2 = 0;
int error1; // motor 1
int error2; // motor 2
int oldADC1;
int obsADC1;
int oldADC2;
int obsADC2;
int control;
/* sets timer 1 prescale to 256 */
set(TCCR1B, CS12); //may need to change this
clear(TCCR1B, CS11);
clear(TCCR1B, CS10);
/* sets mode to 14 timer 1 */
set(TCCR1B, WGM13);
set(TCCR1B, WGM12);
set(TCCR1A, WGM11);
clear(TCCR1A, WGM10);
/* sets timer 3 prescale to 256 */
set(TCCR3B, CS32);
clear(TCCR3B, CS31);
clear(TCCR3B, CS30);
/* sets mode to 14 timer 3 */
set(TCCR3B, WGM33);
set(TCCR3B, WGM32);
set(TCCR3A, WGM31);
clear(TCCR3A, WGM30);
/* spin motor */
set(DDRB, 5); // set B5 as output, PWM
set(DDRC, 6);// set C6 as output, PWM
set(DDRF, 7); //DIR1 motor 1
set(DDRB, 6); //DIR2 motor 1
set(DDRD, 0); //DIR1 motor 2
set(DDRD, 2); //DIR2 motor 2
clear(DDRF, 0); //ADC pot 1 head (lol)
clear(DDRF, 1); //ADC pot 2 head
clear(DDRF, 4); //ADC pot 1 body
clear(DDRF, 5); //ADC pot 2 body
set(TCCR1A, COM1A1); // clear at OCR1A, set at rollover motor 1
clear(TCCR1A, COM1A0);
set(TCCR3A, COM3A1); // clear at OCR3A, set at rollover motor 2
clear(TCCR3A, COM3A0);
setupADC();//calls ADC function
m_usb_init();
while(!m_usb_isconnected()); // wait for a connection
for (;;) {
/* reading ADC values */
readADC(0); // F0
while(bit_is_clear(ADCSRA,ADIF));// does nothing unless flag is set
oldADC1 = ADC -20; //controller postition head
m_usb_tx_int(oldADC1);
m_usb_tx_string(" ");
set(ADCSRA,ADIF);
readADC(1); // F1
while(bit_is_clear(ADCSRA,ADIF));
obsADC1 = ADC + 85; //follower position head plus buffer
m_usb_tx_int(obsADC1);
m_usb_tx_string(" ");
set(ADCSRA,ADIF); // resets flag
readADC(2); //F4
while(bit_is_clear(ADCSRA, ADIF));
oldADC2 = ADC; //controller position body
m_usb_tx_int(oldADC2);
m_usb_tx_string(" ");
set(ADCSRA, ADIF);
readADC(3); //F5
while(bit_is_clear(ADCSRA, ADIF));
obsADC2 = ADC - 22; //follower position body plus buffer
m_usb_tx_int(obsADC2);
m_usb_tx_string(" ");
set(ADCSRA, ADIF);
error1 = obsADC1 - oldADC1; //calculates control error
m_usb_tx_int(error1);
m_usb_tx_string(" ");
error2 = obsADC2 - oldADC2;
m_usb_tx_int(error2);
m_usb_tx_string("\n");
/* motor 1 control */
if (error1 < -25){
clear(PORTF, 7);
set(PORTB, 6);
}
else if (error1 > 25){
set(PORTF, 7);
clear(PORTB, 6);
}
else {
clear(PORTF, 7);
clear(PORTB, 6);
}
/* motor 2 control */
if (error2 < -30){
set(PORTD, 0);
clear(PORTD, 2);
}
else if (error2 > 30){
clear(PORTD, 0);
set(PORTD, 2);
}
else {
clear(PORTD, 0);
clear(PORTD, 2);
}
OCR1A = 0.9 * ICR1; //setting duty cycle, speed of motor as apporaches angle
OCR3A = 0.8 * ICR3;
}
return 0;
}
void setupADC(void){ //sets up ADC
clear(ADMUX, REFS1); // setting voltage reference Vcc
set(ADMUX, REFS0);
/*set ADC clockdivide 128*/
set(ADCSRA, ADPS2);
set(ADCSRA, ADPS1);
set(ADCSRA, ADPS0);
/*enables free running mode*/
clear(ADCSRA, ADATE);
/*enables ADC subsystem*/
set(ADCSRA, ADEN);
/*begins conversion*/
}
void readADC(int n){ //reads ADC based on port specified
if (n == 0){
set (DIDR0, ADC0D); //disable pin
clear(ADCSRB, MUX5);
clear(ADMUX, MUX2);
clear(ADMUX, MUX1);
clear(ADMUX, MUX0);
}
if (n == 1){
set (DIDR0, ADC1D); //disable pin
clear(ADCSRB, MUX5);
clear(ADMUX, MUX2);
clear(ADMUX, MUX1);
set(ADMUX, MUX0);
}
if (n == 2){
set (DIDR0, ADC4D); //disable pin
clear(ADCSRB, MUX5);
set(ADMUX, MUX2);
clear(ADMUX, MUX1);
clear(ADMUX, MUX0);
}
if (n == 3){
set (DIDR0, ADC5D); //disable pin
clear(ADCSRB, MUX5);
set(ADMUX, MUX2);
clear(ADMUX, MUX1);
set(ADMUX, MUX0);
}
set(ADCSRA, ADSC);
}
|
c8cd3b8f3418c7a039fd5a644add567ccc3eb0fc
|
[
"C"
] | 1 |
C
|
rhiannalachance/Mechatronics-Ethel
|
9ff50d4e2ac165764684e2d240fb47a14c375264
|
934af52ad3755182edf273fa095c36af9669b829
|
refs/heads/main
|
<file_sep>#include "matrix.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
// Include SSE intrinsics
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))
#include <immintrin.h>
#include <x86intrin.h>
#endif
/* Below are some intel intrinsics that might be useful
* void _mm256_storeu_pd (double * mem_addr, __m256d a)
* __m256d _mm256_set1_pd (double a)
* __m256d _mm256_set_pd (double e3, double e2, double e1, double e0)
* __m256d _mm256_loadu_pd (double const * mem_addr)
* __m256d _mm256_add_pd (__m256d a, __m256d b)
* __m256d _mm256_sub_pd (__m256d a, __m256d b)
* __m256d _mm256_fmadd_pd (__m256d a, __m256d b, __m256d c)
* __m256d _mm256_mul_pd (__m256d a, __m256d b)
* __m256d _mm256_cmp_pd (__m256d a, __m256d b, const int imm8)
* __m256d _mm256_and_pd (__m256d a, __m256d b)
* __m256d _mm256_max_pd (__m256d a, __m256d b)
*/
/* Generates a random double between low and high */
double rand_double(double low, double high) {
double range = (high - low);
double div = RAND_MAX / range;
return low + (rand() / div);
}
/* Generates a random matrix */
void rand_matrix(matrix *result, unsigned int seed, double low, double high) {
srand(seed);
for (int i = 0; i < result->rows; i++) {
for (int j = 0; j < result->cols; j++) {
set(result, i, j, rand_double(low, high));
}
}
}
/*
* Returns the double value of the matrix at the given row and column.
* You may assume `row` and `col` are valid. Note that the matrix is in row-major order.
*/
double get(matrix *mat, int row, int col) {
// Task 1.1 TODO
}
/*
* Sets the value at the given row and column to val. You may assume `row` and
* `col` are valid. Note that the matrix is in row-major order.
*/
void set(matrix *mat, int row, int col, double val) {
// Task 1.1 TODO
}
/*
* Allocates space for a matrix struct pointed to by the double pointer mat with
* `rows` rows and `cols` columns. You should also allocate memory for the data array
* and initialize all entries to be zeros. `parent` should be set to NULL to indicate that
* this matrix is not a slice. You should also set `ref_cnt` to 1.
* You should return -1 if either `rows` or `cols` or both have invalid values. Return -2 if any
* call to allocate memory in this function fails.
* Return 0 upon success.
*/
int allocate_matrix(matrix **mat, int rows, int cols) {
// Task 1.2 TODO
// HINTS: Follow these steps.
// 1. Check if the dimensions are valid. Return -1 if either dimension is not positive.
// 2. Allocate space for the new matrix struct. Return -2 if allocating memory failed.
// 3. Allocate space for the matrix data, initializing all entries to be 0. Return -2 if allocating memory failed.
// 4. Set the number of rows and columns in the matrix struct according to the arguments provided.
// 5. Set the `parent` field to NULL, since this matrix was not created from a slice.
// 6. Set the `ref_cnt` field to 1.
// 7. Store the address of the allocated matrix struct at the location `mat` is pointing at.
// 8. Return 0 upon success.
}
/*
* You need to make sure that you only free `mat->data` if `mat` is not a slice and has no existing slices,
* or that you free `mat->parent->data` if `mat` is the last existing slice of its parent matrix and its parent
* matrix has no other references (including itself).
*/
void deallocate_matrix(matrix *mat) {
// Task 1.3 TODO
// HINTS: Follow these steps.
// 1. If the matrix pointer `mat` is NULL, return.
// 2. If `mat` has no parent: decrement its `ref_cnt` field by 1. If the `ref_cnt` field becomes 0, then free `mat` and its `data` field.
// 3. Otherwise, recursively call `deallocate_matrix` on `mat`'s parent, then free `mat`.
}
/*
* Allocates space for a matrix struct pointed to by `mat` with `rows` rows and `cols` columns.
* Its data should point to the `offset`th entry of `from`'s data (you do not need to allocate memory)
* for the data field. `parent` should be set to `from` to indicate this matrix is a slice of `from`
* and the reference counter for `from` should be incremented. Lastly, do not forget to set the
* matrix's row and column values as well.
* You should return -1 if either `rows` or `cols` or both have invalid values. Return -2 if any
* call to allocate memory in this function fails.
* Return 0 upon success.
* NOTE: Here we're allocating a matrix struct that refers to already allocated data, so
* there is no need to allocate space for matrix data.
*/
int allocate_matrix_ref(matrix **mat, matrix *from, int offset, int rows, int cols) {
// Task 1.4 TODO
// HINTS: Follow these steps.
// 1. Check if the dimensions are valid. Return -1 if either dimension is not positive.
// 2. Allocate space for the new matrix struct. Return -2 if allocating memory failed.
// 3. Set the `data` field of the new struct to be the `data` field of the `from` struct plus `offset`.
// 4. Set the number of rows and columns in the new struct according to the arguments provided.
// 5. Set the `parent` field of the new struct to the `from` struct pointer.
// 6. Increment the `ref_cnt` field of the `from` struct by 1.
// 7. Store the address of the allocated matrix struct at the location `mat` is pointing at.
// 8. Return 0 upon success.
}
/*
* Sets all entries in mat to val. Note that the matrix is in row-major order.
*/
void fill_matrix(matrix *mat, double val) {
// Task 1.5 TODO
}
/*
* Store the result of taking the absolute value element-wise to `result`.
* Return 0 upon success.
* Note that the matrix is in row-major order.
*/
int abs_matrix(matrix *result, matrix *mat) {
// Task 1.5 TODO
}
/*
* (OPTIONAL)
* Store the result of element-wise negating mat's entries to `result`.
* Return 0 upon success.
* Note that the matrix is in row-major order.
*/
int neg_matrix(matrix *result, matrix *mat) {
// Task 1.5 TODO
}
/*
* Store the result of adding mat1 and mat2 to `result`.
* Return 0 upon success.
* You may assume `mat1` and `mat2` have the same dimensions.
* Note that the matrix is in row-major order.
*/
int add_matrix(matrix *result, matrix *mat1, matrix *mat2) {
// Task 1.5 TODO
}
/*
* (OPTIONAL)
* Store the result of subtracting mat2 from mat1 to `result`.
* Return 0 upon success.
* You may assume `mat1` and `mat2` have the same dimensions.
* Note that the matrix is in row-major order.
*/
int sub_matrix(matrix *result, matrix *mat1, matrix *mat2) {
// Task 1.5 TODO
}
/*
* Store the result of multiplying mat1 and mat2 to `result`.
* Return 0 upon success.
* Remember that matrix multiplication is not the same as multiplying individual elements.
* You may assume `mat1`'s number of columns is equal to `mat2`'s number of rows.
* Note that the matrix is in row-major order.
*/
int mul_matrix(matrix *result, matrix *mat1, matrix *mat2) {
// Task 1.6 TODO
}
/*
* Store the result of raising mat to the (pow)th power to `result`.
* Return 0 upon success.
* Remember that pow is defined with matrix multiplication, not element-wise multiplication.
* You may assume `mat` is a square matrix and `pow` is a non-negative integer.
* Note that the matrix is in row-major order.
*/
int pow_matrix(matrix *result, matrix *mat, int pow) {
// Task 1.6 TODO
}
<file_sep># numc
### Provide answers to the following questions.
- How many hours did you spend on the following tasks?
- Task 1 (Matrix functions in C): ???
- Task 2 (Speeding up matrix operations): ???
- Was this project interesting? What was the most interesting aspect about it?
- <b>???</b>
- What did you learn?
- <b>???</b>
- Is there anything you would change?
- <b>???</b>
<file_sep>from distutils.core import setup, Extension
import sysconfig
def main():
CFLAGS = ['-g', '-Wall', '-std=c99', '-fopenmp', '-mavx', '-mfma', '-pthread', '-O3']
LDFLAGS = ['-fopenmp']
setup(name="numc",
version="0.0.1",
description="numc matrix operations",
ext_modules=[
Extension("numc",
sources=["src/numc.c", "src/matrix.c"],
extra_compile_args=CFLAGS,
extra_link_args=LDFLAGS,
language='c')
])
if __name__ == "__main__":
main()
<file_sep>#include "numc.h"
#include <structmember.h>
// numc.c mainly handles possible errors and unpacking the variables to then later use the functions
// from matrix.c. To get a better understanding of the Python-C interface function calls that are used
// in the code below, have a look at the spec.
static PyTypeObject Matrix61cType;
/* Below are some helper functions for throwing errors */
static int number_methods_err(const char *op, PyObject* args, Matrix61c *self, Matrix61c *other) {
/* PyObject_TypeCheck returns True if args is a subtype of Matrix61cType */
char err_msg[200];
/* First checks t make sure self is a subtype of matrix 61c type */
if (!PyObject_TypeCheck(self, &Matrix61cType)) {
sprintf(err_msg, "numc.matrix does not support %s with other types", op);
PyErr_SetString(PyExc_TypeError, err_msg);
return 1;
}
/* Secondly checks to make sure the args are a subtype of Matrix61c Type*/
if (!PyObject_TypeCheck(args, &Matrix61cType)) {
/* Unpack the tuple into other*/
if (!PyArg_ParseTuple(args, "O", &other)) {
sprintf(err_msg, "numc.matrix does not support %s with other types", op);
PyErr_SetString(PyExc_TypeError, err_msg);
return 1;
}
/* check to make sure that other is a sutype of Matrix61cType */
if (!PyObject_TypeCheck(other, &Matrix61cType)) {
sprintf(err_msg, "numc.matrix does not support %s with other types", op);
PyErr_SetString(PyExc_TypeError, err_msg);
return 1;
}
return 0;
}
return 0;
}
/* Helper function to either create a new Matrix61C object with the given new_mat matrix if op_result is non negative */
static PyObject *op_err(matrix *new_mat, int op_result){
if (op_result < 0) {
deallocate_matrix(new_mat);
return NULL;
} else {
Matrix61c* rv = (Matrix61c*) Matrix61c_new(&Matrix61cType, NULL, NULL);
rv->mat = new_mat;
rv->shape = PyTuple_Pack(2, PyLong_FromLong(new_mat->rows), PyLong_FromLong(new_mat->cols));
return (PyObject*)rv;
}
}
/* Helper functions for initalization of matrices and vectors */
/* Matrix(rows, cols, low, high). Fill a matrix random double values */
static int init_rand(PyObject *self, int rows, int cols, unsigned int seed, double low, double high) {
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return alloc_failed;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return alloc_failed;
}
rand_matrix(new_mat, seed, low, high);
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = PyTuple_Pack(2, PyLong_FromLong(rows), PyLong_FromLong(cols));
return 0;
}
/* Matrix(rows, cols, val). Fill a matrix of dimension rows * cols with val*/
static int init_fill(PyObject *self, int rows, int cols, double val) {
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return alloc_failed;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return alloc_failed;
}
else {
fill_matrix(new_mat, val);
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = PyTuple_Pack(2, PyLong_FromLong(rows), PyLong_FromLong(cols));
}
return 0;
}
/* Matrix(rows, cols, 1d_list). Fill a matrix with dimension rows * cols with 1d_list values */
static int init_1d(PyObject *self, int rows, int cols, PyObject *lst) {
if (rows * cols != PyList_Size(lst)) {
PyErr_SetString(PyExc_TypeError, "Incorrect number of elements in list");
return -1;
}
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return alloc_failed;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return alloc_failed;
}
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
set(new_mat, i, j, PyFloat_AsDouble(PyList_GetItem(lst, count)));
count++;
}
}
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = PyTuple_Pack(2, PyLong_FromLong(rows), PyLong_FromLong(cols));
return 0;
}
/* Matrix(2d_list). Fill a matrix with dimension len(2d_list) * len(2d_list[0]) */
static int init_2d(PyObject *self, PyObject *lst) {
int rows = PyList_Size(lst);
if (rows == 0) {
PyErr_SetString(PyExc_TypeError, "Cannot initialize numc.Matrix with an empty list");
return -1;
}
int cols;
if (!PyList_Check(PyList_GetItem(lst, 0))) {
PyErr_SetString(PyExc_TypeError, "List values not valid");
return -1;
} else {
cols = PyList_Size(PyList_GetItem(lst, 0));
}
for (int i = 0; i < rows; i++) {
if (!PyList_Check(PyList_GetItem(lst, i)) || PyList_Size(PyList_GetItem(lst, i)) != cols) {
PyErr_SetString(PyExc_TypeError, "List values not valid");
return -1;
}
}
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return alloc_failed;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return alloc_failed;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
set(new_mat, i, j, PyFloat_AsDouble(PyList_GetItem(PyList_GetItem(lst, i), j)));
}
}
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = PyTuple_Pack(2, PyLong_FromLong(rows), PyLong_FromLong(cols));
return 0;
}
/* This deallocation function is called when reference count is 0*/
static void Matrix61c_dealloc(Matrix61c *self) {
deallocate_matrix(self->mat);
Py_TYPE(self)->tp_free(self);
}
/* For immutable types all initializations should take place in tp_new */
static PyObject *Matrix61c_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
/* size of allocated memory is tp_basicsize + nitems*tp_itemsize*/
Matrix61c *self = (Matrix61c *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
/* This matrix61c type is mutable, so needs init function. Return 0 on success otherwise -1 */
static int Matrix61c_init(PyObject *self, PyObject *args, PyObject *kwds) {
/* Generate random matrices */
if (kwds != NULL) {
PyObject *rand = PyDict_GetItemString(kwds, "rand");
if (!rand) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
if (!PyBool_Check(rand)) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
if (rand != Py_True) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
PyObject *low = PyDict_GetItemString(kwds, "low");
PyObject *high = PyDict_GetItemString(kwds, "high");
PyObject *seed = PyDict_GetItemString(kwds, "seed");
double double_low = 0;
double double_high = 1;
unsigned int unsigned_seed = 0;
if (low) {
if (PyFloat_Check(low)) {
double_low = PyFloat_AsDouble(low);
} else if (PyLong_Check(low)) {
double_low = PyLong_AsLong(low);
}
}
if (high) {
if (PyFloat_Check(high)) {
double_high = PyFloat_AsDouble(high);
} else if (PyLong_Check(high)) {
double_high = PyLong_AsLong(high);
}
}
if (double_low >= double_high) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
// Set seed if argument exists
if (seed) {
if (PyLong_Check(seed)) {
unsigned_seed = PyLong_AsUnsignedLong(seed);
}
}
PyObject *rows = NULL;
PyObject *cols = NULL;
if (PyArg_UnpackTuple(args, "args", 2, 2, &rows, &cols)) {
if (rows && cols && PyLong_Check(rows) && PyLong_Check(cols)) {
return init_rand(self, PyLong_AsLong(rows), PyLong_AsLong(cols), unsigned_seed, double_low, double_high);
}
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
}
PyObject *arg1 = NULL;
PyObject *arg2 = NULL;
PyObject *arg3 = NULL;
if (PyArg_UnpackTuple(args, "args", 1, 3, &arg1, &arg2, &arg3)) {
/* arguments are (rows, cols, val) */
if (arg1 && arg2 && arg3 && PyLong_Check(arg1) && PyLong_Check(arg2) && (PyLong_Check(arg3) || PyFloat_Check(arg3))) {
if (PyLong_Check(arg3)) {
return init_fill(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), PyLong_AsLong(arg3));
}
else
return init_fill(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), PyFloat_AsDouble(arg3));
} else if (arg1 && arg2 && arg3 && PyLong_Check(arg1) && PyLong_Check(arg2) && PyList_Check(arg3)) {
/* Matrix(rows, cols, 1D list) */
return init_1d(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), arg3);
} else if (arg1 && PyList_Check(arg1) && arg2 == NULL && arg3 == NULL) {
/* Matrix(rows, cols, 1D list) */
return init_2d(self, arg1);
} else if (arg1 && arg2 && PyLong_Check(arg1) && PyLong_Check(arg2) && arg3 == NULL) {
/* Matrix(rows, cols, 1D list) */
return init_fill(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), 0);
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
}
/* List of lists representations for matrices */
static PyObject *Matrix61c_to_list(Matrix61c *self) {
int rows = self->mat->rows;
int cols = self->mat->cols;
PyObject *py_lst = PyList_New(rows);
for (int i = 0; i < rows; i++) {
PyList_SetItem(py_lst, i, PyList_New(cols));
PyObject *curr_row = PyList_GetItem(py_lst, i);
for (int j = 0; j < cols; j++) {
PyList_SetItem(curr_row, j, PyFloat_FromDouble(get(self->mat, i, j)));
}
}
return py_lst;
}
/* Class function which acts as a helper function to Matrix61c_to_list */
static PyObject *Matrix61c_class_to_list(Matrix61c *self, PyObject *args) {
PyObject *mat = NULL;
if (PyArg_UnpackTuple(args, "args", 1, 1, &mat)) {
if (!PyObject_TypeCheck(mat, &Matrix61cType)) {
PyErr_SetString(PyExc_TypeError, "Argument must of type numc.Matrix!");
return NULL;
}
Matrix61c* mat61c = (Matrix61c*)mat;
return Matrix61c_to_list(mat61c);
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
}
/* Add class methods */
static PyMethodDef Matrix61c_class_methods[] = {
{"to_list", (PyCFunction)Matrix61c_class_to_list, METH_VARARGS, "Returns a list representation of numc.Matrix"},
{NULL, NULL, 0, NULL}
};
/* Matrix61c string representation. For printing purposes. */
static PyObject *Matrix61c_repr(PyObject *self) {
PyObject *py_lst = Matrix61c_to_list((Matrix61c *)self);
return PyObject_Repr(py_lst);
}
/* For __getitem__. (e.g. mat[0])
Uses allocate_matrix_ref to return a new matrix from the original as a slice if we are dealing with multiple dimension matrix
*/
static PyObject *Matrix61c_subscript(Matrix61c* self, PyObject* key) {
if (!PyLong_Check(key)) {
PyErr_SetString(PyExc_TypeError, "Key is not valid");
return NULL;
}
int index = PyLong_AsLong(key);
if (index >= self->mat->rows || index < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range");
return NULL;
}
matrix *new_mat;
int ref_failed = allocate_matrix_ref(&new_mat, self->mat, index * self->mat->cols, self->mat->cols, 1);
if (ref_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return NULL;
}else if (ref_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return NULL;
}
Matrix61c* rv = (Matrix61c*) Matrix61c_new(&Matrix61cType, NULL, NULL);
rv->mat = new_mat;
rv->shape = PyTuple_Pack(2, PyLong_FromLong(new_mat->rows), PyLong_FromLong(1));
if (new_mat->rows == 1) { // if one single number, unwrap from list
return PyFloat_FromDouble(new_mat->data[0]);
}
return (PyObject*)rv;
}
/* For __setitem__ (e.g. mat[0] = 1) */
static int Matrix61c_set_subscript(Matrix61c* self, PyObject *key, PyObject *v) {
if (!PyLong_Check(key)) {
PyErr_SetString(PyExc_TypeError, "Key is not valid");
return -1;
}
int index = PyLong_AsLong(key);
if (index >= self->mat->rows || index < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range");
return -1;
}
int cols = self->mat->cols;
if (cols == 1) {
if (!PyFloat_Check(v) && !PyLong_Check(v)) {
PyErr_SetString(PyExc_TypeError, "Value is not valid");
return -1;
}
double val = PyFloat_AsDouble(v);
set(self->mat, index, 0, val);
return 0;
} else {
if (!PyList_Check(v)) {
PyErr_SetString(PyExc_TypeError, "Value is not valid");
return -1;
}
for (int i = 0; i < cols; i++) {
if (!PyFloat_Check(PyList_GetItem(v, i)) && !PyLong_Check(PyList_GetItem(v, i))) {
PyErr_SetString(PyExc_TypeError, "Value is not valid");
return -1;
}
set(self->mat, index, i, PyFloat_AsDouble(PyList_GetItem(v, i)));
}
return 0;
}
return -1;
}
static PyMappingMethods Matrix61c_mapping = {
NULL,
(binaryfunc) Matrix61c_subscript,
(objobjargproc) Matrix61c_set_subscript,
};
/*
* Adds two numc.Matrix (Matrix61c) objects together. The first operand is self, and
* the second operand can be obtained by casting `args`.
*/
static PyObject *Matrix61c_add(Matrix61c* self, PyObject* args) {
Matrix61c* other = NULL;
int args_invalid = number_methods_err("+", args, self, other);
if (args_invalid)
return NULL;
else {
other = (Matrix61c*)args;
}
matrix *new_mat;
matrix *mat1 = self->mat;
matrix *mat2 = other->mat;
if (mat1->rows != mat2->rows || mat1->cols != mat2->cols) {
PyErr_SetString(PyExc_ValueError, "Arguments' dimensions invalid");
return NULL;
}
int alloc_failed = allocate_matrix(&new_mat, self->mat->rows, self->mat->cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return NULL;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return NULL;
}
int add_result = add_matrix(new_mat, self->mat, other->mat);
return op_err(new_mat, add_result);
}
/*
* Subtracts the second numc.Matrix (Matrix61c) object from the first one. The first operand is
* self, and the second operand can be obtained by casting `args`.
*/
static PyObject *Matrix61c_sub(Matrix61c* self, PyObject* args) {
Matrix61c* other = NULL;
int args_invalid = number_methods_err("-", args, self, other);
if (args_invalid)
return NULL;
else {
other = (Matrix61c*)args;
}
matrix *new_mat;
matrix *mat1 = self->mat;
matrix *mat2 = other->mat;
if (mat1->rows != mat2->rows || mat1->cols != mat2->cols) {
PyErr_SetString(PyExc_ValueError, "Arguments' dimensions invalid");
return NULL;
}
int alloc_failed = allocate_matrix(&new_mat, self->mat->rows, self->mat->cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return NULL;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return NULL;
}
int sub_result = sub_matrix(new_mat, self->mat, other->mat);
return op_err(new_mat, sub_result);
}
/*
* Multiplies two numc.Matrix (Matrix61c) objects together. The first operand is self, and
* the second operand can be obtained by casting `args`.
*/
static PyObject *Matrix61c_multiply(Matrix61c* self, PyObject *args) {
Matrix61c* other = NULL;
int args_invalid = number_methods_err("*", args, self, other);
if (args_invalid)
return NULL;
else {
other = (Matrix61c*)args;
}
matrix *new_mat;
matrix *mat1 = self->mat;
matrix *mat2 = other->mat;
if (mat1->cols != mat2->rows) {
PyErr_SetString(PyExc_ValueError, "Arguments' dimensions invalid");
return NULL;
}
int alloc_failed = allocate_matrix(&new_mat, self->mat->rows, other->mat->cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return NULL;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return NULL;
}
int mul_result = mul_matrix(new_mat, self->mat, other->mat);
return op_err(new_mat, mul_result);
}
/*
* Negates the given numc.Matrix (Matrix61c).
*/
static PyObject *Matrix61c_neg(Matrix61c* self) {
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, self->mat->rows, self->mat->cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return NULL;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return NULL;
}
int neg_result = neg_matrix(new_mat, self->mat);
return op_err(new_mat, neg_result);
}
/*
* Take the element-wise absolute value of this numc.Matrix (Matrix61c).
*/
static PyObject *Matrix61c_abs(Matrix61c *self) {
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, self->mat->rows, self->mat->cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return NULL;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return NULL;
}
int abs_result = abs_matrix(new_mat, self->mat);
return op_err(new_mat, abs_result);
}
/*
* Raise numc.Matrix (Matrix61c) to the `pow`th power. You can ignore the argument `optional`.
*/
static PyObject *Matrix61c_pow(Matrix61c *self, PyObject *pow, PyObject *optional) {
if (self->mat->rows != self->mat->cols) {
PyErr_SetString(PyExc_ValueError, "Matrix must be square");
return NULL;
}
if (!PyLong_Check(pow)) {
PyErr_SetString(PyExc_TypeError, "Exponent must be of type integer");
return NULL;
} else {
int pow_c = PyLong_AsLong(pow);
if (pow_c < 0) {
PyErr_SetString(PyExc_ValueError, "Exponent must be positive");
return NULL;
}
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, self->mat->rows, self->mat->cols);
if (alloc_failed == -1){
PyErr_SetString(PyExc_ValueError, "Dimensions must be positive");
return NULL;
}else if (alloc_failed == -2){
PyErr_SetString(PyExc_RuntimeError, "Failed to allocate matrix");
return NULL;
}
int pow_result = pow_matrix(new_mat, self->mat, pow_c);
return op_err(new_mat, pow_result);
}
}
/*
* Create a PyNumberMethods struct for overloading operators with all the number methods
* defined as above.
* You might find this link helpful: https://docs.python.org/3.6/c-api/typeobj.html
*/
static PyNumberMethods Matrix61c_as_number = {
.nb_add = (binaryfunc)Matrix61c_add, // binaryfunc nb_add;
.nb_subtract = (binaryfunc)Matrix61c_sub, // binaryfunc nb_subtract;
.nb_multiply = (binaryfunc)Matrix61c_multiply, // binaryfunc nb_multiply;
.nb_power = (ternaryfunc)Matrix61c_pow, // ternaryfunc nb_power;
.nb_negative = (unaryfunc)Matrix61c_neg, // unaryfunc nb_negative;
.nb_absolute = (unaryfunc)Matrix61c_abs, // unaryfunc nb_absolute;
};
/* INSTANCE METHODS */
/*
* Given a numc.Matrix self, parse `args` to (int) row, (int) col, and (double) val.
* Throw a type error if the number of arguments parsed from args is not 3 or if the arguments
* are of the wrong types. Throw an index error if the parsed row and col are out of range.
* This function should return None in Python.
*/
static PyObject *Matrix61c_set_value(Matrix61c *self, PyObject* args) {
int row, col;
double val;
if (!PyArg_ParseTuple(args, "iid", &row, &col, &val)) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
if (row < 0 || col < 0 || row >= self->mat->rows || col >= self->mat->cols) {
PyErr_SetString(PyExc_IndexError, "row or column index out of range");
return NULL;
}
set(self->mat, row, col, val);
return Py_BuildValue("");
}
/*
* Given a numc.Matrix `self`, parse `args` to (int) row, (int) col, and (double) val.
* Throw a type error if the number of arguments parsed from args is not 3 or if the arguments
* are of the wrong types. Throw an index error if the parsed row and col are out of range.
* This function should return the value at the `row`th row and `col`th column, which is a Python
* float.
*/
static PyObject *Matrix61c_get_value(Matrix61c *self, PyObject* args) {
int row, col;
if (!PyArg_ParseTuple(args, "ii", &row, &col)) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
if (row < 0 || col < 0 || row >= self->mat->rows || col >= self->mat->cols) {
PyErr_SetString(PyExc_IndexError, "row or column index out of range");
return NULL;
}
return PyFloat_FromDouble(get(self->mat, row, col));
}
/*
* Create an array of PyMethodDef structs to hold the instance methods.
* Name the python function corresponding to Matrix61c_get_value as "get" and Matrix61c_set_value
* as "set".
* You might find this link helpful: https://docs.python.org/3.6/c-api/structures.html
*/
static PyMethodDef Matrix61c_methods[] = {
{"set", (PyCFunction)Matrix61c_set_value, METH_VARARGS,
"Change the value at a specific row and column index"},
{"get", (PyCFunction)Matrix61c_get_value, METH_VARARGS,
"Get the value at a specific row and column index"},
{NULL} /* Sentinel */
};
/* INSTANCE ATTRIBUTES*/
static PyMemberDef Matrix61c_members[] = {
{"shape", T_OBJECT_EX, offsetof(Matrix61c, shape), 0,
"(rows, cols)"},
{NULL} /* Sentinel */
};
/* INSTANCE ATTRIBUTES */
static PyTypeObject Matrix61cType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "numc.Matrix",
.tp_basicsize = sizeof(Matrix61c),
.tp_dealloc = (destructor)Matrix61c_dealloc,
.tp_repr = (reprfunc)Matrix61c_repr,
.tp_as_number = &Matrix61c_as_number,
.tp_flags = Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE,
.tp_doc = "numc.Matrix objects",
.tp_methods = Matrix61c_methods,
.tp_members = Matrix61c_members,
.tp_as_mapping = &Matrix61c_mapping,
.tp_init = (initproc)Matrix61c_init,
.tp_new = Matrix61c_new
};
/* Information about the Cython Module */
static struct PyModuleDef numcmodule = {
PyModuleDef_HEAD_INIT,
"numc",
"Numc matrix operations",
-1,
Matrix61c_class_methods
};
/* Initialize the numc module */
PyMODINIT_FUNC PyInit_numc(void) {
PyObject* m;
if (PyType_Ready(&Matrix61cType) < 0)
return NULL;
m = PyModule_Create(&numcmodule);
if (m == NULL)
return NULL;
Py_INCREF(&Matrix61cType);
PyModule_AddObject(m, "Matrix", (PyObject *)&Matrix61cType);
printf("CS61C Fall 2021 Project 4: numc imported!\n");
fflush(stdout);
return m;
}
|
5783d3d78f383ee397012bdeadc5387bc225b446
|
[
"Markdown",
"C",
"Python"
] | 4 |
C
|
61c-teach/fa21-proj4-starter
|
67765a8891d6a124244032eba71e1a6a3c9640d8
|
99a8f522c1e2b9e833fe6e9014ab678a509bf03a
|
refs/heads/master
|
<file_sep>$('document').ready(function() {
$('#all-products').click(function(){
$('.product-label').removeClass('filter-selected');
$('.all-label').addClass('filter-selected');
$('.product').removeClass('product-hidden');
});
$('#shoes').click(function() {
$('.product-label').removeClass('filter-selected');
$('.shoe-label').addClass('filter-selected');
$('.product').addClass('product-hidden');
$('.product-shoe').removeClass('product-hidden');
});
$('#shirts').click(function() {
$('.product-label').removeClass('filter-selected');
$('.shirt-label').addClass('filter-selected');
$('.product').addClass('product-hidden');
$('.product-shirt').removeClass('product-hidden');
});
$('#shorts').click(function() {
$('.product-label').removeClass('filter-selected');
$('.short-label').addClass('filter-selected');
$('.product').addClass('product-hidden');
$('.product-short').removeClass('product-hidden');
});
$('#jackets').click(function() {
$('.product-label').removeClass('filter-selected');
$('.jacket-label').addClass('filter-selected');
$('.product').addClass('product-hidden');
$('.product-jacket').removeClass('product-hidden');
});
$('#accessory').click(function() {
$('.product-label').removeClass('filter-selected');
$('.accessory-label').addClass('filter-selected');
$('.product').addClass('product-hidden');
$('.product-accessory').removeClass('product-hidden');
});
});
|
5f5259f915b808c6a88360599b0af611cd80f5dc
|
[
"JavaScript"
] | 1 |
JavaScript
|
austineady/nike-remake
|
63cd2f1fb1a4f288670f699e4a865d4348d1141d
|
0c8c2f16ed7baa2f83c5e9f54d527a66b7e5ccbc
|
refs/heads/master
|
<repo_name>ConjurTech/neon-wallet-db<file_sep>/api/db.py
from pymongo import MongoClient
import os
import redis
from rq import Queue
MONGO_URL = os.environ.get('MONGO_URL')
MONGO_DB_NAME = os.environ.get('MONGO_DB_NAME')
client = MongoClient(MONGO_URL, connect=False)
db = client[MONGO_DB_NAME]
# db["meta"].insert_one({"name":"lastTrustedBlock", "value":1162327})
# db["meta"].insert_one({"name":"lastTrustedTransaction", "value":1162327})
# redis
redis_url = os.environ.get('REDIS_URL')
redis_db = redis.from_url(redis_url)
# redis_db.flushdb()
q = Queue(connection=redis_db)
transaction_db = db['transactions']
blockchain_db = db['blockchain']
meta_db = db['meta']
logs_db = db['logs']
address_db = db['addresses']
|
8aa5865ef0b9ebfd0ed9c2b9314e9353527c30d4
|
[
"Python"
] | 1 |
Python
|
ConjurTech/neon-wallet-db
|
50b4b307f605889724dc1a5ce0e9b703e449e50d
|
5806abbe914e6282e00ddfa558e8330bea61cb20
|
refs/heads/master
|
<repo_name>Mrezagolbaba/React-server-side<file_sep>/README.md
# React-server-side
simple react server side app usign reactjs and nodejs server
change title server side by react-helmet
<file_sep>/src/pages/home.js
import React from 'react';
import { Helmet } from 'react-helmet';
class Home extends React.Component{
buttonOnclick(){
console.log('js is running')
}
head(){
return(
<Helmet>
<title>My page title</title>
</Helmet>
)
}
render(){
return(
<div>
{this.head()}
<h1>
My Home
</h1>
<button onClick={()=>this.buttonOnclick()}>Console log</button>
</div>
)
}
}
export default Home;
<file_sep>/src/app.js
import React from 'react';
import {Switch,Route} from 'react-router'
import Home from './pages/home'
class App extends React.Component{
render(){
return(
<Switch>
<Route path="/" render={props=>(
<Home {...props}/>
)}/>
</Switch>
)
}
}
export default App;
|
83409fba253239f045dd65c88ec3e7609b8890be
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
Mrezagolbaba/React-server-side
|
785e01e7084edcd87591b3214f6c39bfb2a7f9f4
|
c19acb23c111c2137a0143e8f39a8879f02e1f6c
|
refs/heads/master
|
<repo_name>PrinzMallen/MLE<file_sep>/src/main/java/Michael/EvolutionaererAlgorithmus/Gen.java
package Michael.EvolutionaererAlgorithmus;
import java.util.Random;
public class Gen implements Comparable<Gen>{
int []genBits;
double fitness;
public Gen(int genLaenge) {
genBits = new int [genLaenge];
for (int i = 0; i < genLaenge ; i++) {
genBits[i] = (int) Math.round(Math.random());
}
}
public Gen(int[] genBits) {
this.genBits = genBits;
}
@Override
public String toString() {
String string = "";
for (int bit : genBits) {
string += bit;
}
return string;
}
public void mutiere(){
int bitIndex = erstelleZufallsInt(0, genBits.length - 1);
genBits[bitIndex] = (genBits[bitIndex] + 1) % 2;
}
public Gen kreuzen(Gen gen){
int spaltungsStelle = erstelleZufallsInt(1, genBits.length - 1);
int [] gekreuztesGen = new int[genBits.length];
for (int i = 0; i < genBits.length; i++) {
if(i < spaltungsStelle){
gekreuztesGen[i] = genBits[i];
}else{
gekreuztesGen[i] = gen.genBits[i];
}
}
return new Gen(gekreuztesGen);
}
@Override
public boolean equals(Object gen) {
Gen vergleichsGen = (Gen) gen;
fitness = 0;
for (int i = 0; i < genBits.length ; i++) {
if(genBits[i] == vergleichsGen.genBits[i])
{
fitness += 1;
}
}
return fitness == genBits.length;
}
public static int erstelleZufallsInt(int min, int max) {
Random random = new Random();
return random.nextInt((max - min) + 1) + min;
}
@Override
public int compareTo(Gen gen) {
return (int) (gen.fitness - fitness);
}
}
<file_sep>/src/main/java/de/hsmannheim/mle/Individuum.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.hsmannheim.mle;
import java.util.BitSet;
import java.util.Random;
/**
*
* @author Alexander
*/
public class Individuum {
private BitSet gene;
private double fitness;
Random random;
public Individuum(int genAnzahl, Random random) {
gene = new BitSet(genAnzahl);
this.random = random;
for (int i = 0; i < genAnzahl; i++) {
if (random.nextBoolean()) {
gene.set(i);
}
}
}
public Individuum(BitSet gene, Random random) {
this.random = random;
this.gene = gene;
}
public double setFitness(BitSet besteGene) {
fitness = 0;
for (int i = 0; i < gene.length(); i++) {
if (besteGene.get(i) == gene.get(i)) {
fitness++;
}
}
return fitness;
}
public Individuum[] kreuzen(Individuum partner) {
//kein komplettes crossover .. 50 zu 50
int spaltungStelle = random.nextInt((gene.size() - 1));
BitSet gekreuzteGene1 = new BitSet(gene.size());
BitSet gekreuzteGene2 = new BitSet(gene.size());
for (int i = 0; i < gene.size(); i++) {
if (i <= spaltungStelle) {
gekreuzteGene1.set(i, this.gene.get(i));
gekreuzteGene2.set(i, partner.getGene().get(i));
} else {
gekreuzteGene1.set(i, partner.getGene().get(i));
gekreuzteGene2.set(i, this.gene.get(i));
}
}
Individuum[] kinder = new Individuum[2];
kinder[0] = new Individuum(gekreuzteGene1, random);
kinder[1] = new Individuum(gekreuzteGene2, random);
return kinder;
}
public void mutiere() {
gene.flip(random.nextInt(gene.size() - 1));
}
public BitSet getGene() {
return gene;
}
public double getFitness() {
return fitness;
}
public void setFitness(double fitness) {
this.fitness = fitness;
}
}
<file_sep>/src/main/java/de/hsmannheim/mle/HillClimber.java
package de.hsmannheim.mle;
import java.util.Random;
public class HillClimber {
private final int anzahlDurchläufe = 1000000;
// alle staedte in einer matrix.
private final int[][] entfernungen;
// alle staedte in einer bestimmten reihenfolge
private int[] tour;
public static void main(String[] args) {
HillClimber HillClimber = new HillClimber();
HillClimber.starteTour();
}
public HillClimber() {
entfernungen = new int[100][100];
Random zufallsGenerator = new Random();
for (int i = 0; i < entfernungen.length - 1; i++) {
for (int j = 0; j < entfernungen.length - 1; j++) {
//nur wenn es wirklich eine Distanz geben kann
if (j != i) {
//keine 0 als distanz
int zufälligeEntfernung = zufallsGenerator.nextInt(100) + 1;
//x zu y gleiche distanz wie y zu x
entfernungen[i][j] = zufälligeEntfernung;
entfernungen[j][i] = zufälligeEntfernung;
}
}
}
tour = new int[100];
for (int i = 0; i < tour.length; i++) {
tour[i] = i;
}
}
public int errechneGesamtDistanz(int[] tour) {
int tourStrecke = 0;
//errechne weg bis zur letzten stadt
for (int i = 0; i < tour.length - 1; i++) {
tourStrecke += entfernungen[tour[i]][tour[1 + i]];
}
//kehre zurück zur ersten Stadt
tourStrecke += entfernungen[tour.length - 1][tour[0]];
return tourStrecke;
}
public void starteTour() {
Random random = new Random();
//errechne tour von 1-100
int besteDistanz = errechneGesamtDistanz(tour);
int anzahlErfolgloserDurchgänge = 0;
System.out.println("Anfangsdistanz: "+besteDistanz);
for (int i = 0; i < anzahlDurchläufe; i++) {
//ändere Tour leicht, aber stelle sicher das sich etwas ändert
int stadtA = 0;
int stadtB = 0;
while(stadtA==stadtB){
stadtA=random.nextInt(100);
stadtB=random.nextInt(100);
}
int[] neueTour = swap(stadtA, stadtB);
//errechne veränderte Tour
int neueDistanz = errechneGesamtDistanz(neueTour);
//wenn neue beste Distanz gefunden, speichern + ausgabe
if (neueDistanz < besteDistanz) {
besteDistanz = neueDistanz;
this.tour = neueTour;
System.out.println("Durchlauf Nummer: " + i + ", Kürzester bisheriger Weg: " + besteDistanz
+ ", benötigte Durchläufe bis zur Verbesserung: " + anzahlErfolgloserDurchgänge);
anzahlErfolgloserDurchgänge=0;
} else {
anzahlErfolgloserDurchgänge++;
}
}
System.out.println("Beste errechnete Distanz: "+besteDistanz);
}
private int[] swap(int v1, int v2) {
//standard 3 Eck-Swap
int[] neueTour = this.tour;
int temp = neueTour[v1];
neueTour[v1] = neueTour[v2];
neueTour[v2] = temp;
return neueTour;
}
}
<file_sep>/src/main/java/PingPong/Agent.java
package PingPong;
public class Agent {
double[][][][][][] gehirn;
int richtungsEntscheidung;
int[] gedaechtnis;
int letzteRichtungsEntscheidung;
private double alpha = 0.01;
private double gamma = 0.9;
public Agent(int xBallSchritteMaximal, int yBallSchritteMaximal, int xSchlaegerSchritteMaximal) {
int xBallGeschwindigkeiten = 2;
int yBallGeschwindigkeiten = 2;
int richtungen = 3;
//jeder möglicher zustand gespeichert wird hierzu jede mögliche reaktion ( rechts,links, nichts tun) und ob diese belohnt wurde
this.gehirn = new double[xBallSchritteMaximal + 1][yBallSchritteMaximal + 1][xBallGeschwindigkeiten][yBallGeschwindigkeiten][xSchlaegerSchritteMaximal + 1][richtungen];
//initalisiere jeder aktion für jede situation mit einem sehr geringen wert
for (double[][][][][] xBallSchritte : gehirn) {
for (double[][][][] yBallSchritte : xBallSchritte) {
for (double[][][] xSchlaegerSchritte : yBallSchritte) {
for (double[][] xGeschwindigkeit : xSchlaegerSchritte) {
for (double[] yGeschwindigkeit : xGeschwindigkeit) {
for (int i = 0; i < yGeschwindigkeit.length; i++) {
yGeschwindigkeit[i] = Math.random() / 1000;
}
}
}
}
}
}
}
int maxQ(Status status) {
int maxIndex = (int) (Math.random() * 3);
double epsilon = 0.01;
if (Math.random() > epsilon) {
double maxValue = gehirn[status.xBallPos][status.yBallPos][status.xBallSpeed][status.yBallSpeed][status.xSchlägerPos][0];
maxIndex = 0;
//hole best bewertete aktion für diese situation
for (int i = 0; i < 3; i++) {
if (gehirn[status.xBallPos][status.yBallPos][status.xBallSpeed][status.yBallSpeed][status.xSchlägerPos][i] > maxValue) {
maxValue = gehirn[status.xBallPos][status.yBallPos][status.xBallSpeed][status.yBallSpeed][status.xSchlägerPos][i];
maxIndex = i;
}
}
}
return maxIndex;
}
void lernen(Status statusVorher, Status statusDanach, int aktion, int belohnung) {
//generelle bewertung der aktion in dieser situation
double bewertung = gehirn[statusVorher.xBallPos][statusVorher.yBallPos][statusVorher.xBallSpeed][statusVorher.yBallSpeed][statusVorher.xSchlägerPos][aktion];
//errechne bewertung der geraden ausgeführten aktion im hinblick auf ergebnis ( belohnung)
bewertung += alpha * (belohnung + gamma * gehirn[statusDanach.xBallPos][statusDanach.yBallPos][statusDanach.xBallSpeed][statusDanach.yBallSpeed][statusDanach.xSchlägerPos][maxQ(statusDanach)] - bewertung);
gehirn[statusVorher.xBallPos][statusVorher.yBallPos][statusVorher.xBallSpeed][statusVorher.yBallSpeed][statusVorher.xSchlägerPos][aktion] = bewertung;
}
}
<file_sep>/src/main/java/Michael/HillClimbing/Main.java
package Michael.HillClimbing;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int anzahlDerStaedte = 100;
int anzahlDerDurchlaeufe = 1000;
int[][] distanzenTabelle = erstelleDistanzenTabelle(anzahlDerStaedte);
int[] backupArray;
int[] hypothese = erstelleStartHypothese(anzahlDerStaedte);
ausgabe("Anfangszustand = ", hypothese);
for (int i = 0; i < anzahlDerDurchlaeufe; i++) {
backupArray = erstelleTiefeArryaKopie(hypothese);
int aktuelleDistanz = errechneAktuelleDistanz(hypothese, distanzenTabelle);
List<Integer> nummerierung = new ArrayList<Integer>();
for (int j = 1; j < anzahlDerStaedte; j++) {
nummerierung.add(j);
}
int zufallsInt;
zufallsInt = erstelleZufallsInt(0, (nummerierung.size()-1));
int zufallsIntA = nummerierung.get(zufallsInt);
nummerierung.remove(zufallsInt);
zufallsInt = erstelleZufallsInt(0, (nummerierung.size()-1));
int zufallsIntB = nummerierung.get(zufallsInt);
nummerierung.remove(zufallsInt);
int temp = hypothese[zufallsIntA];
hypothese[zufallsIntA] = hypothese[zufallsIntB];
hypothese[zufallsIntB] = temp;
int neueDistanz = errechneAktuelleDistanz(hypothese, distanzenTabelle);
if (aktuelleDistanz >= neueDistanz){
System.out.println("Distanzminderung in Schritt "+ i + ": von " + aktuelleDistanz + " auf " + neueDistanz + " gesunken");
}else{
hypothese = erstelleTiefeArryaKopie(backupArray);
}
}
ausgabe("Endzustand = ", hypothese);
}
public static int errechneAktuelleDistanz(int[] hypothese, int[][] distanzenTabelle){
int aktuelleDistanz = 0;
for (int i = 0; i < hypothese.length - 1; ++i)
{
aktuelleDistanz += distanzenTabelle[hypothese[i]][hypothese[i + 1]];
}
return aktuelleDistanz;
}
public static int[] erstelleTiefeArryaKopie(int[] originalArray){
int[] tiefeArryaKopie = new int[originalArray.length];
for (int i = 0; i < originalArray.length; ++i)
{
tiefeArryaKopie[i] = originalArray[i];
}
return tiefeArryaKopie;
}
public static int[] erstelleStartHypothese(int anzahlDerStaedte){
int[] startHypothese = new int[anzahlDerStaedte];
List<Integer> nummerierung = new ArrayList<Integer>();
startHypothese[0] = 0;
for (int i = 1; i < anzahlDerStaedte; i++) {
nummerierung.add(i);
}
for (int i = 1; i < startHypothese.length; i++) {
int zufallsInt = erstelleZufallsInt(0, (nummerierung.size()-1));
startHypothese[i] = nummerierung.get(zufallsInt);
nummerierung.remove(zufallsInt);
}
return startHypothese;
}
public static int[][] erstelleDistanzenTabelle(int anzahlDerStaedte){
int[][] distanzenTabelle = new int[anzahlDerStaedte][anzahlDerStaedte];
for(int i = 0; i < distanzenTabelle.length; i++) {
distanzenTabelle[i][i] = 0;
}
for (int i = 0; i < distanzenTabelle.length; i++) {
for (int j = (i+1); j < distanzenTabelle.length; j++) {
distanzenTabelle[j][i] = erstelleZufallsInt(1, 200);
distanzenTabelle[i][j] = distanzenTabelle[j][i];
}
}
return distanzenTabelle;
}
public static int erstelleZufallsInt(int min, int max) {
Random random = new Random();
return random.nextInt((max - min) + 1) + min;
}
public static void ausgabe(String textZusatz, int[] auszugebendesArray){
String ausgabe = "" + auszugebendesArray[0];
for (int i = 1; i < auszugebendesArray.length; i++) {
ausgabe += ", " + auszugebendesArray[i];
}
System.out.println(textZusatz + ausgabe);
}
}
<file_sep>/src/main/java/PingPong/Status.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package PingPong;
/**
*
* @author Alexander
*/
public class Status {
public int xBallPos;
public int yBallPos;
public int xBallSpeed;
public int yBallSpeed;
public int xSchlägerPos;
public Status(int xBallPos, int yBallPos, int xBallSpeed, int yBallSpeed, int xSchlägerPos) {
this.xBallPos = xBallPos;
this.yBallPos = yBallPos;
this.xBallSpeed = xBallSpeed;
this.yBallSpeed = yBallSpeed;
this.xSchlägerPos = xSchlägerPos;
if(xBallSpeed<0){
this.xBallSpeed=0;
}
if(yBallSpeed<0){
this.yBallSpeed=0;
}
}
}
|
7f0628e0be7cd22c325d0e7398d8484835d4b63c
|
[
"Java"
] | 6 |
Java
|
PrinzMallen/MLE
|
f36245ac7148f4fc291250750645735c6428339e
|
5745a9ffa13027a174579f04f6a692b6dd214ebd
|
refs/heads/main
|
<repo_name>spolyakovs/Lecture-4<file_sep>/src/main/java/ru/ifmo/backend_2021/expressions/UnaryExpression.java
package ru.ifmo.backend_2021.expressions;
public abstract class UnaryExpression implements Expression {
@Override
public int getPriority() {
return 0;
}
@Override
public String toMiniString() {
return this.toString();
}
}
<file_sep>/src/main/java/ru/ifmo/backend_2021/ExpressionParser.java
package ru.ifmo.backend_2021;
import ru.ifmo.backend_2021.expressions.*;
public class ExpressionParser {
private static String s;
private static int pos = 0;
public static Expression parse(String s) {
ExpressionParser.s = s.replaceAll("\\s+", "");
pos = 0;
Expression result = expression();
if (pos != ExpressionParser.s.length()) {
throw new IllegalStateException("Error in expression at " + pos);
}
return result;
}
private static Expression expression() {
final String CHARS_BEFORE_UNARY_MINUS = "*/(";
Expression first = term();
while (pos < s.length()) {
char operator = s.charAt(pos);
if (operator != '+' && operator != '-') {
break;
} else if (operator == '-' && (pos == 0 || CHARS_BEFORE_UNARY_MINUS.contains(String.valueOf(s.charAt(pos - 1))))) {
break; // it's unary minus
} else {
pos++;
}
Expression second = term();
if (operator == '+') {
first = new Add(first, second);
} else {
first = new Subtract(first, second);
}
}
return first;
}
private static Expression term() {
Expression first = factor();
while (pos < s.length()) {
char operator = s.charAt(pos);
if (operator != '*' && operator != '/') {
break;
} else {
pos++;
}
Expression second = factor();
if (operator == '*') {
first = new Multiply(first, second);
} else {
first = new Divide(first, second);
}
}
return first;
}
private static Expression factor() {
char next = s.charAt(pos);
Expression result = null;
if (next == '(') {
pos++;
result = expression();
char closingBracket;
if (pos < s.length()) {
closingBracket = s.charAt(pos);
} else {
throw new IllegalStateException("Unexpected end of expression");
}
if (closingBracket == ')') {
pos++;
return result;
}
throw new IllegalStateException("')' expected but " + closingBracket);
} else if (next == '-') {
pos++;
result = new UnaryMinus(factor());
} else if (Character.isDigit(next)) {
StringBuilder nextNumber = new StringBuilder();
while (pos < s.length() && Character.isDigit(s.charAt(pos))) {
nextNumber.append(s.charAt(pos));
pos++;
}
result = new Const(Integer.parseInt(nextNumber.toString()));
} else {
StringBuilder nextVar = new StringBuilder();
while (pos < s.length() && Character.isLetterOrDigit(s.charAt(pos))) {
nextVar.append(s.charAt(pos));
pos++;
}
result = new Variable(nextVar.toString());
}
return result;
}
}
<file_sep>/src/main/java/ru/ifmo/backend_2021/expressions/BinaryExpression.java
package ru.ifmo.backend_2021.expressions;
import java.util.Objects;
public abstract class BinaryExpression implements Expression {
public final boolean isSymmetrical;
protected final Expression first, second;
private final char operator;
public BinaryExpression(Expression first, Expression second, char operator, boolean isSymmetrical) {
this.isSymmetrical = isSymmetrical;
this.first = first;
this.second = second;
this.operator = operator;
}
public String toMiniString() {
StringBuilder sb = new StringBuilder("");
sb.append(first.toMiniString());
if (first instanceof BinaryExpression && first.getPriority() > this.getPriority()) {
sb.insert(0, "(");
sb.append(")");
}
sb.append(" ");
sb.append(this.operator);
sb.append(" ");
if (second instanceof BinaryExpression &&
(second.getPriority() > this.getPriority() ||
((!isSymmetrical || !((BinaryExpression) second).isSymmetrical)&&
second.getPriority() == this.getPriority()))) {
sb.append("(");
sb.append(second.toMiniString());
sb.append(")");
} else {
sb.append(second.toMiniString());
}
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("");
sb.append("(");
sb.append(first.toString());
sb.append(" ");
sb.append(this.operator);
sb.append(" ");
sb.append(second.toString());
sb.append(")");
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (o != null && getClass() == o.getClass()) {
BinaryExpression other = (BinaryExpression) o;
return first.equals(other.first) && second.equals(other.second);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(first, second, operator, isSymmetrical);
}
}
|
0021dbabe7f6c1665711e36c9ea0e7ad8b80edad
|
[
"Java"
] | 3 |
Java
|
spolyakovs/Lecture-4
|
6c331a406a0bd71ce55ae1ed4a0ea0a1007a58fc
|
abb93bd26ff3e0d0e72b25e9d04ad82f61f661af
|
refs/heads/master
|
<file_sep>describe('inputtypes', function() {
var inputtypes;
var cleanup;
before(function(done) {
requirejs.config({
baseUrl: '../src',
paths: { cleanup: '../test/cleanup' }
});
requirejs(['inputtypes', 'cleanup'], function(_inputtypes, _cleanup) {
inputtypes = _inputtypes;
cleanup = _cleanup;
done();
});
});
it('is an array', function() {
expect(inputtypes).to.be.an('array');
});
after(function() {
cleanup();
});
});
<file_sep>describe('mq', function() {
var ModernizrProto = {};
var testMediaQuery;
var cleanup;
var mq;
before(function(done) {
define('ModernizrProto', [], function(){return ModernizrProto;});
requirejs.config({
baseUrl: '../src',
paths: { cleanup: '../test/cleanup' }
});
requirejs(['mq', 'testMediaQuery', 'cleanup'], function(_mq, _testMediaQuery, _cleanup) {
testMediaQuery = _testMediaQuery;
mq = _mq;
cleanup = _cleanup;
done();
});
});
it('is just an alias to `testMediaQuery`', function() {
expect(mq).to.equal(testMediaQuery);
});
it('creates a reference on `ModernizrProto`', function() {
expect(mq).to.equal(ModernizrProto.mq);
});
after(function() {
cleanup();
});
});
<file_sep>describe('inputattrs', function() {
var inputattrs;
var cleanup;
before(function(done) {
requirejs.config({
baseUrl: '../src',
paths: { cleanup: '../test/cleanup' }
});
requirejs(['inputattrs', 'cleanup'], function(_inputattrs, _cleanup) {
inputattrs = _inputattrs;
cleanup = _cleanup;
done();
});
});
it('is an array', function() {
expect(inputattrs).to.be.an('array');
});
after(function() {
cleanup();
});
});
<file_sep>describe('attrs', function() {
var attrs;
var cleanup;
before(function(done) {
requirejs.config({
baseUrl: '../src',
paths: { cleanup: '../test/cleanup' }
});
requirejs(['attrs', 'cleanup'], function(_attrs, _cleanup) {
attrs = _attrs;
cleanup = _cleanup;
done();
});
});
it('is an object', function() {
expect(attrs).to.be.an('object');
});
after(function() {
cleanup();
});
});
|
23e82141c417ef5fb4d21fbd17b3d80a107475de
|
[
"JavaScript"
] | 4 |
JavaScript
|
RepmujNetsik/Modernizr
|
bed5f7c699c5a774cebdd1937a142eb30896a796
|
206da538d9e0078627a293bd014c08e495cc4411
|
refs/heads/master
|
<repo_name>DonatodAcunto/EmbeddedProject<file_sep>/Codice Base/NeuralNetworks-develop/README.md
[](License.md)

# Neural Network
## Embedded System Project
Final project of the Embedded System course based on the realization of a neural network and its implementation on
[Raspberry Pi model 3](https://www.raspberrypi.org/products/raspberry-pi-3-model-b/) and [Intel Movidius](https://software.intel.com/en-us/neural-compute-stick) neural compute stick.
## Install
Refer to [Readme](https://github.com/frank1789/NeuralNetworks/blob/master/README.md)
## Know issue
### Training
Cluster training (HPC) with Altair PBS does not allow saving the model file in
Keras format (*Hierarchical Data Format .h5*), so we use an internal routine to
export the model to the TensorFlow
format (*protobuff .pb*).
To guarantee that the model in keras format is compatible, it is necessary to insert the following script:
```python
kbe.set_learning_phase(0)
```
or
```python
K.set_learning_phase(0)
```
otherwise it will not be possible to convert the model into a graph format, as it will be lost in final values in the forecast.
### GPU
There may be memory allocation problems in the GPU, at the moment this solution
is used in the file *face_recognition.py*
```Python
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8, allow_growth=False)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
```
#### alterantive
Using this script, the entire GPU memory is mapped as described below.
##### Allowing GPU memory growth
By default, TensorFlow maps nearly all of the GPU memory of all GPUs (subject to
CUDA_VISIBLE_DEVICES) visible to the process. This is done to more
efficiently use the relatively precious GPU memory resources on the devices
by reducing memory fragmentation.
In some cases it is desirable for the process to only allocate a subset of the
available memory, or to only grow the memory usage as is needed by the process.
TensorFlow provides two Config options on the Session to control this.
The first is the **allow_growth** option, which attempts to allocate only as
much GPU memory based on runtime allocations: it starts out allocating very
little memory, and as Sessions get run and more GPU memory is needed, we extend
the GPU memory region needed by the TensorFlow process. Note that we do not
release memory, since that can lead to even worse memory fragmentation.
To turn this option on, set the option in the ConfigProto by a script optimized
already implemented:
```python
config = tf.ConfigProto()
config.gpu_options.allow_growth = True # dynamically grow the memory used on the GPU
config.log_device_placement = True # to log device placement (on which device the operation ran)
config.allow_soft_placement = True # search automatically free GPU
sess = tf.Session(config=config)
kbe.set_session(sess) # set this TensorFlow session as the default session for Keras
```
Refer documentation [Using GPU](https://www.tensorflow.org/guide/using_gpu).
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgments
* Embedded system lab @ UNITN
* HPC Cluster | ICTS - University of Trento - ICTS@unitn
<file_sep>/ES_Blob_Detection/main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <io.h>
#include <windows.h>
#include <filesystem>
#include <Windows.h>
using namespace std;
using namespace cv;
// Function to return a list
vector<string> get_all_files_names_within_folder(string folder);
int main()
{
//modifica alba
// List of files
vector<string> pictures_files;
pictures_files = get_all_files_names_within_folder("C:/Users/docdo/Documents/GitHub/EmbeddedProject/Immagini Prova Ordinate");
// Blob detection
//--- To do for all the pictures
Mat img = imread("PictureExample.jpg", IMREAD_GRAYSCALE);
// Set up Default parameters for the detector
SimpleBlobDetector detector;
// Detecting blobs
std::vector<KeyPoint> keypoints;
detector.detect(img, keypoints);
// Draw Circles on Blobs
Mat im_with_keypoints;
drawKeypoints(img, keypoints, im_with_keypoints, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
// Show blobs
imshow("keypoints", im_with_keypoints);
waitKey(0);
return 0;
}
vector<string> get_all_files_names_within_folder(string folder)
{
vector<string> names;
string search_path = folder + "/*.jpg*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if (hFind != INVALID_HANDLE_VALUE) {
do {
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
names.push_back(fd.cFileName);
}
} while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
return names;
}
|
4001319e347cccceacf8b40a3e704b2a3e38e088
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
DonatodAcunto/EmbeddedProject
|
e095fb8415ec78f4d6fc00ae802c13447782499e
|
54279fa85ca8316fb670bf81cae8dd9bdd5dec71
|
refs/heads/master
|
<repo_name>sandhya-ch/notetaker<file_sep>/blog/models.py
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class Note(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
modefied_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
|
86ff4624b86a963b2e4ac33d73c75519f4bbef22
|
[
"Python"
] | 1 |
Python
|
sandhya-ch/notetaker
|
e9d0940bd543d7f626d5091166394b694c5cd13b
|
eae99624dfff744a5004a91295724e54cb7e8b34
|
refs/heads/master
|
<repo_name>HanaAuana/beginner-projects-python<file_sep>/averages.py
def mean(nums):
sum = 0
for n in nums:
sum += n
return sum / len(nums)
def median(nums):
nums.sort()
midpoint = int(len(nums) / 2)
# For even number of items, we'll return two possible modes
if len(nums) % 2 == 0:
return nums[midpoint - 1:midpoint + 1]
else:
return nums[midpoint]
def mode(nums):
counts = [[n, nums.count(n)] for n in nums]
most = 0
for n in counts:
if n[1] >= most:
most = n[1]
candidates = []
for n in counts:
if n[1] >= most and n[0] not in candidates:
candidates.append(n[0])
if len(candidates) == 1:
return candidates[0]
return candidates
<file_sep>/magic8ball.py
from random import randint
responses = ['Ask again later',
'Outlook not good',
'Definitely',
'Unlikely',
'Perhaps',
'It is certain',
'Yes',
'Cannot predict now',
'Doubtful',
'Most likely', ]
def get_response():
choice = randint(0, 9)
return responses[choice]
while True:
question = input('Ask a question: ')
print('Thinking...')
print(get_response())
again = input('Do you want to ask again? Type yes to continue: ')
if again.lower() not in ('yes', 'y', 'continue'):
break
<file_sep>/menu_calculator.py
from collections import Counter
menu = [3.5,
2.5,
4.0,
3.5,
1.75,
1.50,
2.25,
3.75,
1.25
]
def parse_order(order):
"""Take a string, and return a dict of the order."""
numbers = [int(n) for n in list(order)]
counts = Counter(numbers)
return dict(counts)
def take_orders():
while True:
order = input("May I take your order?")
counts = parse_order(order)
total = 0
for number, count in counts.items():
total += (count * menu[number - 1])
print("Total is ${:.2f}".format(total))
again = input('Do you have another order? Type yes to continue: ')
if again.lower() not in ('yes', 'y', 'continue'):
break
if __name__ == '__main__':
take_orders()
<file_sep>/algorithms/merge_sort.py
def merge_sort(items):
if len(items) <= 1:
return items
# Split list into 2 roughly equal lists
middle = len(items) // 2
left = items[:middle]
right = items[middle:]
# Sort each sub-list recursively
# print("Sort: ", left, right)
left = merge_sort(left)
right = merge_sort(right)
# Merge the sorted sub-lists back together
return merge(left, right)
def merge(left, right):
merged = []
l = 0
r = 0
# Until we exhaust one of the sub-lists
while l < len(left) and r < len(right):
# If the next item in the left sub-list is smaller, take that item next
if left[l] <= right[r]:
merged.append(left[l])
l += 1
# Otherwise, take the righthand item next
else:
merged.append(right[r])
r += 1
# Append any remaining items in the lefthand list
while l < len(left):
merged.append(left[l])
l += 1
# Append any remaining items in the righthand list
while r < len(right):
merged.append(right[r])
r += 1
# print("Merged: ", merged)
return merged
items = [8, 5, 2, 6, 9, 3, 1, 4, 0, 7]
print(merge_sort(items))
<file_sep>/fibonacci.py
def fibonacci(num):
"""Return the num-th number in the fibonacci sequence."""
if num == 0:
return 0
else:
result = 1
n_1 = 0
n_2 = 1
for i in range(num - 1):
result = n_1 + n_2
n_1 = n_2
n_2 = result
return result
<file_sep>/factors.py
import sys
def find_factors(num):
"""Take a number, and print a list of the factors."""
divisors = list(range(2, int(num)))
factors = [1]
for d in divisors:
if num % d == 0:
factors.append(d)
factors.append(num)
print(factors)
if __name__ == '__main__':
find_factors(int(sys.argv[1]))
<file_sep>/multiplication_tables.py
import sys
def print_table(size):
"""Print a multiplication of 'size X size' dimensions (Up to 15X15)."""
if size > 15:
print("WARNING: Formatting may be off due to size (", size, ")")
numbers = range(1, size + 1)
# Length of the largest value
max = len(str(size * size))
# String of "-"'s to divide each row
row_divider = '\n ' + '-' * ((size) * (max + 2))
# Print header row
print(" " * (max + 2), end='')
for num in numbers:
print(" {0:>{1}}|".format(num, max), end='')
print(row_divider)
# Each cell will be justified based on the maximum length for the table
for row in numbers:
print(" {0:>{1}}|".format(row, max), end='')
for col in numbers:
print(" {0:>{1}}|".format(row * col, max), end='')
print(row_divider)
print_table(int(sys.argv[1]))
<file_sep>/algorithms/quick_sort.py
def quick_sort(items):
# If there is only 1 item, it's sorted
if len(items) <= 1:
return items
# Pick the middle item as the pivot
pivot = items[len(items) // 2]
# Partition items into 3 sub-lists based on the pivot
left = [item for item in items if item < pivot]
middle = [item for item in items if item == pivot]
right = [item for item in items if item > pivot]
# print(left)
# print(right)
# Recursively quick_sort the left and right partitions
left = quick_sort(left)
right = quick_sort(right)
# Recombine the partitions
return left + middle + right
items = [8, 5, 2, 6, 9, 3, 1, 4, 0, 7]
print(quick_sort(items))
<file_sep>/algorithms/bubble_sort.py
def bubble_sort(items):
# print(items)
swapped = True
# Continue until we don't have to swap anymore
last_check = len(items)
while swapped:
# print("{} items, checking up to {}".format(len(items), last_check))
swapped = False
# Loop through each pair of items in the list
for i in range(1, last_check):
# If the item on the left is larger, then swap the items
if items[i - 1] > items[i]:
items[i - 1], items[i] = items[i], items[i - 1]
# print("Swapping {}, {}".format(items[i - 1], items[i]))
swapped = True
# After the final swap in the loop, we know the remaining
# items are sorted, so we can skip them on later loops
last_check = i
# print(items)
return items
items = [8, 7, 6, 5, 4, 3, 2, 1]
bubble_sort(items)
<file_sep>/test_averages.py
import averages
import unittest
class KnownValues(unittest.TestCase):
known_means = (([1, 2, 3, 4, 5], 3.0),
([4, 4, 4, 4, 4], 4.0),
([10, 10, 20, 60, 70], 34.0),
([6, 7, 8], 7.0),
([2, 1], 1.5),
)
known_medians = (([1, 2, 3, 4, 5], 3),
([4, 4, 4, 4, 4], 4),
([10, 10, 20, 60, 70], 20),
([6, 7, 8], 7),
([1, 2, 3, 4], [2, 3]),
)
known_modes = (([1, 1, 2, 2, 2], 2),
([1, 2, 3, 5, 5], 5),
([1, 1, 1, 1, 1], 1),
([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]),
([1, 2], [1, 2]),
)
def test_mean_known_value(self):
"""mean should return known value from known input list."""
for nums, value in self.known_means:
result = averages.mean(nums)
self.assertEqual(value, result)
def test_median_known_value(self):
"""median should return known value from known input list."""
for nums, value in self.known_medians:
result = averages.median(nums)
self.assertEqual(value, result)
def test_mode_known_value(self):
"""mode should return known value from known input list."""
for nums, value in self.known_modes:
result = averages.mode(nums)
self.assertEqual(value, result)
if __name__ == '__main__':
unittest.main()
<file_sep>/99bottles.py
import sys
def print_bottles(max, min):
"""Print the lyrics to max Bottles of Beer on the wall."""
for num in range(max, min - 1, -1):
if num == 1:
print('1 bottle of beer on the wall, 1 bottle of beer')
print('Take one down, pass it around, no more bottles of beer on the wall'.format(num-1))
else:
print('{0} bottles of beer on the wall, {0} bottles of beer'.format(num))
if num - 1 == 1:
print('Take one down, pass it around, 1 bottle of beer on the wall')
else:
print('Take one down, pass it around, {} bottles of beer on the wall'.format(num-1))
print()
print_bottles(int(sys.argv[1]), int(sys.argv[2]))
<file_sep>/algorithms/insertion_sort.py
def insertion_sort(items):
# print(items)
size = len(items)
# Loop over each position in the items
for i in range(size):
this_item = items[i]
next_pos = i
# Check item against each previous item, until we reach the first item
while next_pos > 0 and items[next_pos - 1] > this_item:
# Shift the previous item "up" one position
items[next_pos] = items[next_pos - 1]
next_pos -= 1
# Once we find the right position, insert the current item into
items[next_pos] = this_item
# print(items)
return items
items = [8, 5, 2, 6, 9, 3, 1, 4, 0, 7]
insertion_sort(items)
<file_sep>/find_number.py
# 1 through 1000
# Two or more digits
possible = [i for i in range(1, 1001) if i > 9]
for i in possible:
should_add = True
string_num = str(i)
# Number does not contain 1 or 7
if '7' in string_num or '1' in string_num:
should_add = False
continue
# Remove if second to last digit is odd (not even)
if int(string_num[-2:-1]) % 2 != 0:
should_add = False
continue
# Remove if last digit doesn't equal number of digits in number
if int(string_num[-1]) != len(string_num):
should_add = False
continue
# Remove if first two digits are even (not odd)
sum_of_first_two = int(string_num[0]) + int(string_num[1])
if sum_of_first_two % 2 == 0:
should_add = False
continue
# Remove if sum of digits is greater than 10 (not <= 10)
sum_of_all = 0
for c in string_num:
sum_of_all += int(c)
if sum_of_all > 10:
should_add = False
continue
# Remove if number is not prime
divisors = list(range(2, int(i ** 0.5) + 1))
for d in divisors:
if i % d == 0:
should_add = False
continue
if should_add is True:
print(i)
<file_sep>/countdown.py
from datetime import datetime
from time import sleep
def countdown():
"""Take a date/time, and print a countdown of time remaining."""
while True:
target_date = input("Please enter a date (YYYY-MM-DD): ")
target_time = input("Please enter a time (HH:MM:SS): ")
target = target_date + ' ' + target_time
now = datetime.now()
target = datetime.strptime(target, '%Y-%m-%d %H:%M:%S')
if target > now:
break
print("Please enter a date/time in the future")
while target > now:
diff = target - now
remaining_minutes = diff.seconds / 60
print("{:.2f} minutes remaining".format(remaining_minutes))
sleep(5)
if target != datetime.now():
now = datetime.now()
else:
break
print("Target reached")
if __name__ == '__main__':
countdown()
<file_sep>/pythagorean_checker.py
def check_pythagorean(num1, num2, num3):
"""Verify whether the 3 parameters are a Pythagorean Triple."""
if num1 <= 0 or num2 <= 0 or num3 <= 0:
return False
hypotenuse = max(num1, num2, num3)
if num1 == hypotenuse:
return (num1 ** 2 == (num2 ** 2 + num3 ** 2))
elif num2 == hypotenuse:
return (num2 ** 2 == (num1 ** 2 + num3 ** 2))
else:
return (num3 ** 2 == (num1 ** 2 + num2 ** 2))
while True:
num1 = input('Enter a side: ')
num2 = input('Enter another side: ')
num3 = input('Enter the last side: ')
if check_pythagorean(int(num1), int(num2), int(num3)):
print('{}, {}, and {} are a Pythagorean Triple'.format(num1, num2, num3))
else:
print('{}, {}, and {} are not a Pythagorean Triple'.format(num1, num2, num3))
again = input('Do you want to check another? Type yes to continue: ')
if again.lower() not in ('yes', 'y', 'continue'):
break
<file_sep>/README.md
# beginner-projects-python
<file_sep>/change_calculator.py
import math
change_options = [("quarters", 25),
("dimes", 10),
("nickels", 5),
("pennies", 1)
]
while True:
money_due = float(input('Enter the price (in dollars: 1.50): '))
money_paid = float(input('Enter the money paid (in dollars): '))
change = round(money_paid - money_due, 2)
print('{0} due in change'.format(change))
change = change * 100
next_coin = 0
while change > 0 and next_coin < len(change_options):
divisor = change_options[next_coin][1]
number_of_coins = math.floor(change / divisor)
print('{0} {1}'.format(number_of_coins, change_options[next_coin][0]))
change = change % divisor
next_coin += 1
again = input('Need change for another amount? Type yes to continue: ')
if again.lower() not in ('yes', 'y', 'continue'):
break
<file_sep>/test_fibonacci.py
import fibonacci
import unittest
class KnownValues(unittest.TestCase):
known_fibs = [0, 1, 1, 2, 3, 5, 8, 13, 21]
def test_fib_known_value(self):
"""fibonacci should return known value from known input list."""
for i in range(0, len(self.known_fibs)):
result = fibonacci.fibonacci(i)
self.assertEqual(self.known_fibs[i], result)
if __name__ == '__main__':
unittest.main()
<file_sep>/algorithms/inplace_quick_sort.py
def partition(items, start, end, pivot_idx):
low = start
high = end - 1
pivot_val = items[pivot_idx]
items[pivot_idx], items[end] = items[end], items[pivot_idx]
while low <= high:
while items[low] < pivot_val:
low += 1
while items[high] >= pivot_val:
high -= 1
if low <= high:
items[low], items[high] = items[high], items[low]
low += 1
high -= 1
items[end], items[low] = items[low], items[end]
return low
def quick_sort(items, start=0, end=None):
if end is None:
end = len(items) - 1
pivot_idx = len(items) // 2
else:
pivot_idx = ((end - start) // 2) + start
# If there is only 1 item, it's sorted
if len(items[start:end]) <= 1:
return items[start:end]
# Partition items into 3 sub-lists based on the pivot
split = partition(items, start, end, pivot_idx)
left = quick_sort(items, start, split)
right = quick_sort(items, split + 1, end)
return left + items[split:split] + right
items = [8, 5, 2, 6, 9, 3, 1, 4, 0, 7]
print(items)
quick_sort(items)
print(items)
<file_sep>/algorithms/selection_sort.py
def selection_sort(items):
# print(items)
size = len(items)
# Continue until we have sorted each position
for done in range(size):
# print("Checking last {} of {} items".format(unsorted, size))
# Start by assuming the next item is the smallest
smallest = done
# Loop through all unsorted items
for i in range(done + 1, size):
# If an item is smaller than current smallest it's the new smallest
if items[i] <= items[smallest]:
smallest = i
# print("New smallest is {} at {}".format(items[i], i))
# If we found a different smallest item,
# swap the smallest item into the next unsorted position
if done != smallest:
items[done], items[smallest] = items[smallest], items[done]
# print(items)
return items
items = [8, 5, 2, 6, 9, 3, 1, 4, 0, 7]
selection_sort(items)
<file_sep>/coin_estimator.py
from math import ceil
coin_weights = {"penny": 2.5,
"nickel": 5.0,
"dime": 2.268,
"quarter": 5.67
}
wrapper_capacity = {"penny": 50,
"nickel": 40,
"dime": 50,
"quarter": 40
}
def weight_to_quantity(w, denomination):
coin_weight = coin_weights[denomination]
return int(round(w / coin_weight))
def quantity_to_wrappers(q, denomination):
num_wrappers = wrapper_capacity[denomination]
return ceil(q / num_wrappers)
def pounds_to_grams(n):
return n * 453.592
while True:
use_grams = input('Enter g for grams or lbs for pounds')
penny_weight = float(input('Enter the weight of your pennies: '))
nickel_weight = float(input('Enter the weight of your nickels: '))
dime_weight = float(input('Enter the weight of your dimes: '))
quarter_weight = float(input('Enter the weight of your quarters: '))
weights = [("penny", "pennies", penny_weight, 1),
("nickel", "nickels", nickel_weight, 5),
("dime", "dimes", dime_weight, 10),
("quarter", "quarters", quarter_weight, 25)
]
total = 0
for denomination, plural, weight, value in weights:
# If the user entered weights in pounds, convert to grams
if use_grams.lower() not in ('g', 'grams'):
w = pounds_to_grams(weight)
print('{0} lbs of {1}'.format(int(round(w)), plural))
else:
w = weight
print('{0} grams of {1}'.format(int(round(w)), plural))
quantity = weight_to_quantity(w, denomination)
print('Number of {0}: {1}'.format(plural, quantity))
wrappers = quantity_to_wrappers(quantity, denomination)
print('Number of {0} wrappers needed: {1}'.format(denomination, wrappers))
total += (quantity * value)
print('Total value in cents: {0}. In dollars: {1}'.format(total, total / 100))
again = input('Do you want to check another group? Type yes to continue: ')
if again.lower() not in ('yes', 'y', 'continue'):
break
|
4dfb8a4bf9bd6fd1da14bd255a9515c976867849
|
[
"Markdown",
"Python"
] | 21 |
Python
|
HanaAuana/beginner-projects-python
|
c14b67a1ef9dc977cd5f1f1a2d28e88d6e274c8d
|
b873f8a8f62c41b2936e305ef0ccc8c3fa8ceace
|
refs/heads/master
|
<file_sep>#!/bin/bash
#
# Commands to run while building the container
#
[ -d storage/logs ] || mkdir -p storage/logs
[ -d public ] || mkdir -p public
[ -f composer.json ] || exit 0
composer install --no-interaction --no-progress --prefer-dist --optimize-autoloader --ignore-platform-reqs --no-suggest --no-dev
#php artisan optimize
#php artisan key:generate
#php artisan migrate
# clearing cache
#php artisan cache:clear
#php artisan config:clear
# caching new changes
#php artisan config:cache
#php artisan route:cache
#php artisan storage:link
<file_sep>FROM centos:centos7 as base
LABEL name="lumen/php72"
LABEL maintainer="<NAME> <<EMAIL>>"
LABEL version="3.0"
LABEL summary="Lumen server with Apache, php, supervisor and cron"
# env
# note: PHP version as in remi repo
ARG PHP_VERSION="72"
ARG ROOT_PASSWORD="<PASSWORD>!"
USER root
RUN echo "root:${ROOT_PASSWORD}" | chpasswd
# install PHP ${PHP_VERSION} and dev tools
RUN true \
&& yum -y install --setopt=tsflags=nodocs \
yum-utils \
https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm \
http://rpms.remirepo.net/enterprise/remi-release-7.rpm \
curl \
httpd \
zip \
unzip \
crontabs \
&& yum-config-manager --enable remi-php${PHP_VERSION} \
&& yum -y install --setopt=tsflags=nodocs \
php php-common php-mysql php-mcrypt php-gd php-curl php-json php-zip php-xml php-fileinfo php-bcmath \
libpng12-devel \
libpng-devel \
pngquant \
supervisor \
composer \
&& yum -y clean all \
&& rm -rf /var/cache/yum
FROM base as build
# env
ARG TIMEZONE="UTC"
USER root
# custom configs for php.ini, add yours here.
RUN sed -i '\
s/;\?short_open_tag =.*/short_open_tag = On/; \
s/;\?expose_php =.*/expose_php = Off/; \
s/;\?post_max_size =.*/post_max_size = 101M/; \
s/;\?upload_max_filesize =.*/upload_max_filesize = 101M/; \
s/;\?max_execution_time =.*/max_execution_time = 120/; \
s/;\?memory_limit =.*/memory_limit = 512M/; \
s#;\?date.timezone =.*#date.timezone = '${TIMEZONE}'# \
' /etc/php.ini \
&& cp /etc/php.ini . \
&& ln -sf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime
COPY . /var/www/html
WORKDIR /var/www/html/
COPY ./devops/apache.conf /etc/httpd/conf.d/host.conf
COPY ./devops/crontab.conf /etc/crontab
COPY ./devops/supervisord.conf /etc/
RUN ./devops/build.sh
EXPOSE 80
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
<file_sep># Docker Images for web services
Currently supports Laravel, Lumen and Vue.js
## Structure
* Centos as base Image.
* Httpd or Nginx - per tag/branch.
* PHP - different versions per tag.
* PHP libs plus auxiliary tools: curl, zip, crontab and composer.
* Supervisor to hold services - listed below.
## Services
* Web server.
* Crontab for scheduled tasks.
* Artisan queue manager.
* Artisan consumer.
## Instructions
* Edit `devops/build.sh` to add your custom instruction on building your app.
* Edit `devops/init.sh` to select steps necessary when the container boots, comment out unwanted supervisor processes.
* You may add cronjobs in `devops/crontab.conf`
* You may tune _php_ custom configurations in `Dockerfile`, and/or timezone for container instance.
* You may add port 443 to `Dockerfile` if you don't have a reverse proxy/load balancer for handling SSL connections.
* You may need to edit `devops/supervisor.conf`, for example to select queue name for _consumer_ process.
* Add your source code to directory.
* You may add unwanted files/folder to `.dockerignore`
* Run Docker build.
<file_sep>#!/bin/bash
#
# Commands to run after booting up the container
#
# 1001 is the ops group number
chown apache:1001 -R storage public
chmod ug+rwx -R storage public
umask 0002
# start other supervisor jobs
## you may need to edit consumer name in supervisor.conf
supervisorctl start queue:*
supervisorctl start crontab
supervisorctl start consumer
|
e368bcac04f99247fe8bf20731bb68485084dbea
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 4 |
Shell
|
ThabetAmer/docker-web-images
|
9eb5d1bf904cbbb7edc5ca13e6495a077321c4b7
|
386dada8718021dc626ee432c6ec939af774bb27
|
refs/heads/master
|
<repo_name>msforbes09/middleware<file_sep>/project_middleware/index.php
<?php
session_start();
//print_r($_SESSION);
if( !$_SESSION["employee_code"] ) {
header( 'location: login.php' );
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ProjectCodeSystem</title>
<!-- Bootstrap -->
<link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="../bootstrap/js/jquery-1.11.3.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!--[if lt IE 9]>
<script src="../bootstrap/js/html5shiv.js"></script>
<script src="../bootstrap/js/respond.js"></script>
<![endif]-->
</head>
<body class="bg-default">
<?php require_once 'nav.php'; ?>
<div class="container-fluid" style="margin-top: 60px;">
<?php require_once 'form_control.php'; ?>
<center><div id="loading"></div></center>
<div id="main"></div>
</div>
<?php require_once 'modal.php'; ?>
<script src="script.js"></script>
</body>
</html><file_sep>/project_middleware/check_user.php
<?php
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=projectcodesystem;charset=utf8;', 'root', '' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
"SELECT * FROM users
WHERE
employee_code = :employee_code
AND
password = :<PASSWORD>"
);
$stmt->bindValue( ':employee_code', $_REQUEST["employee_code"], PDO::PARAM_STR );
$stmt->bindValue( ':password', md5($_REQUEST["password"]), PDO::PARAM_STR );
$stmt->execute();
$cnt = $stmt->rowCount();
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
$admin = $row["admin"];
}
} catch( PDOException $e) {
echo $e->getMessage();
}
$pdo = null;<file_sep>/project_middleware/ajax_get_images.php
<?php
//echo $_REQUEST["code"];
if( file_exists( './pictures/' . $_REQUEST["code"] ) ) {
if(@array_merge(array_diff(scandir( './pictures/' . $_REQUEST["code"] ),array('.','..')))[0]) {
foreach( array_merge(array_diff(scandir( './pictures/' . $_REQUEST["code"] ),array('.','..'))) as $image ) {
echo '<a href="./pictures/' . $_REQUEST["code"].'/'.$image.'" target="blank"><img src="./pictures/' . $_REQUEST["code"].'/'.$image.'" style="height: 100px;" title="./pictures/'.$_REQUEST["code"].'/'.$image.'"></a>';
}
}
}<file_sep>/project_middleware/projects.sql
CREATE TABLE `projects` (
`id` int(11) NOT NULL,
`company_id` int(11) NOT NULL,
`code` varchar(10) NOT NULL,
`name` varchar(255) NOT NULL,
`name_ja` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`finished_at` timestamp NULL DEFAULT '0000-00-00 00:00:00',
`remarks` longtext,
`cancel` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `projects`
ADD PRIMARY KEY (`id`);
ALTER TABLE `projects`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=138;<file_sep>/project_middleware/users.sql
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`employee_code` varchar(255) NOT NULL,
`password` varchar(32) NOT NULL,
`name` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;<file_sep>/project_middleware/ajax_update_timestamp.php
<?php
$current_timestamp = date("Y-m-d").' 00:00:00';
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=projectcodesystem;charset=utf8;', 'root', '' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
"UPDATE projects
SET finished_at = :finished_at
WHERE code = :code"
);
$stmt->bindValue( ':finished_at', $current_timestamp, PDO::PARAM_STR );
$stmt->bindValue( ':code', $_REQUEST["project_code"], PDO::PARAM_STR );
$flag = $stmt->execute();
if( ! $flag ) {
$info = $stmt->errorInfo();
exit( $info[2] );
}
} catch( PDOException $e ) {
echo $e->getMessage();
}
$pdo = null;
echo $current_timestamp;<file_sep>/project_middleware/ajax_delete_image.php
<?php
echo unlink($_REQUEST["path"]);<file_sep>/project_middleware/ajax_update.php
<?php
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=projectcodesystem;charset=utf8;', 'root', '' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
"UPDATE projects
SET
name = :project,
name_ja = :project_ja,
remarks = :remarks
WHERE
code = :code"
);
$stmt->bindValue( ':code', $_REQUEST["code"], PDO::PARAM_STR );
$stmt->bindValue( ':project', $_REQUEST["project"], PDO::PARAM_STR );
$stmt->bindValue( ':project_ja', $_REQUEST["project_ja"], PDO::PARAM_STR );
$stmt->bindValue( ':remarks', $_REQUEST["remarks"], PDO::PARAM_STR );
$flag = $stmt->execute();
if( ! $flag ) {
$info = $stmt->errorInfo();
exit( $info[2] );
}
} catch( PDOException $e ) {
echo $e->getMessage();
}
$pdo = null;<file_sep>/project_middleware/file_uploader.php
<?php
$images = '';
$seqNo = '';
for ( $i = 0; $i < count($_FILES["files"]["name"]); $i++ ) {
//print_r(@$_FILES["files"]["name"][$i]);
if( ! file_exists('./pictures/'.$_REQUEST["code"]) ) {
mkdir('./pictures/'.$_REQUEST["code"] );
}
$array = @array_merge(array_diff(scandir( './pictures/' . $_REQUEST["code"] ),array('.','..')));
rsort($array,SORT_NATURAL);
//print_r($array);
if( @$array[0] ) {
$seqNo = @preg_replace('/\.jpg/','',explode('-',$array[0])[2]) + 1;
//echo $seqNo;
} else {
$seqNo = 1;
}
if( move_uploaded_file(
@$_FILES["files"]["tmp_name"][$i],
'./pictures/'.$_REQUEST["code"].'/'.$_REQUEST["code"].'-'.$seqNo.'.jpg'
) ) {
$images .= '<a href="./pictures/'.$_REQUEST["code"].'/'.$_REQUEST["code"].'-'.$seqNo.'.jpg" target="blank">
<img src="./pictures/'.$_REQUEST["code"].'/'.$_REQUEST["code"].'-'.$seqNo.'.jpg" title="./pictures/'.$_REQUEST["code"].'/'.$_REQUEST["code"].'-'.$seqNo.'.jpg" style="height: 100px;"></a>';
}
}
echo $images;<file_sep>/project_middleware/pictures.sql
CREATE TABLE `pictures` (
`id` int(11) NOT NULL,
`project_code` varchar(10) NOT NULL,
`path` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `pictures`
ADD PRIMARY KEY (`id`);
ALTER TABLE `pictures`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;<file_sep>/project_middleware/functions.php
<?php
function admin( $admin ) {
if ( ! $admin ) {
return ' disabled ';
}
}<file_sep>/project_middleware/ajax_insert.php
<?php
function project_code($last_project_code) {
$segs = explode('-',$last_project_code);
$company_code = $segs[0];
$project_code = $segs[1];
$project_code++;
return $company_code.'-'.$project_code;
}
function last_project_code($company_id) {
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=projectcodesystem;charset=utf8;', 'root', '' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
"SELECT * FROM projects WHERE company_id = :company_id ORDER BY code DESC"
);
$stmt->bindValue(':company_id',$company_id,PDO::PARAM_INT );
$stmt->execute();
$array = array();
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$array[] = $row["code"];
}
} catch( PDOException $e ) {
echo $e->getMessage();
}
$pdo = null;
return $array[0];
}
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=projectcodesystem;charset=utf8;', 'root', '' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
"INSERT INTO projects
SET
company_id = :company_id,
code = :code,
name = :name,
name_ja = :name_ja
"
);
$stmt->bindValue( ':company_id', $_REQUEST["company_id"], PDO::PARAM_INT );
$stmt->bindValue( ':code', project_code(last_project_code($_REQUEST["company_id"])), PDO::PARAM_STR );
$stmt->bindValue( ':name', $_REQUEST["name"], PDO::PARAM_STR );
$stmt->bindValue( ':name_ja', $_REQUEST["name_ja"], PDO::PARAM_STR );
$flag = $stmt->execute();
if( ! $flag ) {
$info = $stmt->errorInfo();
exit( $info[2] );
}
} catch( PDOException $e ) {
echo $e->getMessage();
}
$pdo = null;
echo project_code(last_project_code($_REQUEST["company_id"]));<file_sep>/project_middleware/login.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ProjectCodeSystem</title>
<!-- Bootstrap -->
<link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="../bootstrap/js/jquery-1.11.3.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!--[if lt IE 9]>
<script src="../bootstrap/js/html5shiv.js"></script>
<script src="../bootstrap/js/respond.js"></script>
<![endif]-->
</head>
<body class="bg-default">
<!--Main start-->
<div class="container-fluid" style="margin-top: 100px;">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">ProjectCodeSystem <small>-Login Form-</small></h3>
</div>
<div class="panel-body">
<form role="form" method="post" action="">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="employee_code" name="employee_code" type="text" autofocus value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="<PASSWORD>" name="password" type="<PASSWORD>" value="">
</div>
<button class="btn btn-lg btn-block" style="background-color: black; color: white;">Login</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
if( $_SERVER["REQUEST_METHOD"] === 'POST' ) {
require_once 'check_user.php';
if( $cnt ) {
$_SESSION["employee_code"] = $_REQUEST["employee_code"];
$_SESSION["admin"] = $admin;
header( 'location: ./' );
}
}<file_sep>/project_middleware/ajax_table.php
<?php
session_start();
require_once 'functions.php';
function update_timestamp( $status, $finished_at ) {
if( $status === 'ongoing' ) {
return '<button class="btn btn-xs btn-warning update" '.admin($_SESSION["admin"]).'>Update</button>';
} else {
return $finished_at;
}
}
if( $_REQUEST["status"] === 'all' ) {
$status = " AND projects.cancel = 0 ";
} elseif( $_REQUEST["status"] === 'ongoing' ) {
$status = " AND projects.finished_at = '0000-00-00 00:00:00' AND projects.cancel = 0 ";
} elseif( $_REQUEST["status"] === 'finished' ) {
$status = " AND projects.finished_at <> '0000-00-00 00:00:00' AND projects.cancel = 0 ";
} elseif( $_REQUEST["status"] === 'canceled' ) {
$status = " AND projects.cancel = 1 ";
}
$company = '';
switch( $_REQUEST["company"] ) {
case 1:
$company = " AND companies.id = 1";
break;
case 2:
$company = " AND companies.id = 2";
break;
case 3:
$company = " AND companies.id = 3";
break;
case 4:
$company = " AND companies.id = 4";
break;
case 5:
$company = " AND companies.id = 5";
break;
case 6:
$company = " AND companies.id = 6";
break;
case 7:
$company = " AND companies.id = 7";
break;
default:
$company = "";
}
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=projectcodesystem;charset=utf8;', 'root', '' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare(
"SELECT
projects.code as code,
projects.name as project_name,
projects.name_ja as project_name_ja,
projects.created_at as project_created_at,
projects.finished_at as project_finished_at,
projects.remarks as remarks,
companies.name as company_name
FROM
projects,
companies
WHERE
projects.company_id = companies.id
$status
$company
"
);
$stmt->execute();
$cnt = $stmt->rowCount();
$tbody = '';
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
$tbody .= '<tr>';
$tbody .= '<td>'.$row["company_name"].'</td>';
$tbody .= '<td class="project_code">'.$row["code"].'</td>';
$tbody .= '<td class="project_name">'.$row["project_name"].'</td>';
$tbody .= '<td class="project_name_ja">'.$row["project_name_ja"].'</td>';
$tbody .= '<td>'.$row["project_created_at"].'</td>';
$tbody .= '<td>'.update_timestamp($_REQUEST["status"],$row["project_finished_at"]).'</td>';
$tbody .= '<td class="remarks">'.$row["remarks"].'</td>';
$tbody .= '<td><button class="btn btn-xs btn-warning edit " '.admin($_SESSION["admin"]).'>Edit <span class="glyphicon glyphicon-edit"></span></button></td>';
$tbody .= '<td><button class="btn btn-xs btn-danger cancel " '.admin($_SESSION["admin"]).'>Cancel<span class="glyphicon glyphicon-remove"></span></button></td>';
$tbody .= '</tr>';
}
} catch( PDOException $e ) {
echo $e->getMessage();
}
?>
<p><span style="color: red; font-weight: bold;"><?php echo $cnt; ?></span> record(s) found.</p>
<div class="table-responsive">
<table class="table">
<thead>
<tr class="bg-primary">
<th>Company</th>
<th>Code</th>
<th>Project</th>
<th>Project_ja</th>
<th>Code Assigned</th>
<th>Date Finished</th>
<th>Remarks</th>
<th>Edit</th>
<th>Cancel</th>
</tr>
</thead>
<tbody>
<?php echo $tbody; ?>
</tbody>
</table>
</div>
<file_sep>/project_middleware/form_control.php
<?php
require_once 'functions.php';
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=projectcodesystem;charset=utf8;', 'root', '' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare(
"SELECT id,name FROM companies;"
);
$stmt->execute();
$companies = '<option value=""></option>';
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
$companies .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
}
} catch( PDOException $e ) {
echo $e->getMessage();
}
$pdo = null;
?>
<div class="row" style="margin-bottom: 30px;">
<div class="col-sm-3 col-xs-3">
<label for="status">status</label>
<select class="form-control input-sm" id="status">
<option value="all">All Projects</option>
<option value="ongoing">On-going Projects</option>
<option value="finished">Finished Projects</option>
<option value="canceled">Canceled Projects</option>
</select>
</div>
<div class="col-sm-3 col-xs-3">
<label for="company">company</label>
<select class="form-control input-sm" id="company">
<?php echo $companies; ?>
</select>
</div>
<div class="col-sm-2 col-xs-2">
<label for="add">Add</label><br>
<button class="btn btn-sm btn-primary" id="add" <?php echo admin($_SESSION["admin"]);?>>add <span class="glyphicon glyphicon-plus"></span></button>
</div>
</div><file_sep>/project_middleware/companies.sql
CREATE TABLE `companies` (
`id` int(11) NOT NULL,
`code` varchar(1) NOT NULL,
`name` varchar(100) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `companies` (`id`, `code`, `name`, `created_at`, `updated_at`) VALUES
(1, 'R', 'HRD', '2017-08-08 16:04:54', '2017-08-08 16:04:54'),
(2, 'W', 'WUKONG', '2017-08-08 16:04:54', '2017-08-08 16:04:54'),
(3, 'S', 'SCAD', '2017-08-08 16:06:08', '2017-08-08 16:06:08'),
(4, 'H', 'HTI', '2017-08-08 16:06:08', '2017-08-08 16:06:08'),
(5, 'P', 'PVTECH', '2017-08-08 16:07:03', '2017-08-08 16:07:03'),
(6, 'M', 'MLC', '2017-08-08 16:07:03', '2017-08-08 16:07:03'),
(7, 'E', 'MEC', '2017-08-08 16:07:12', '2017-08-08 16:07:12');
ALTER TABLE `companies`
ADD PRIMARY KEY (`id`);
ALTER TABLE `companies`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
|
9cbdfc9b0def364504cb20cd73d16ee32b5a4c15
|
[
"SQL",
"PHP"
] | 16 |
PHP
|
msforbes09/middleware
|
4ba5e273ab4491e8ee34301fbd9e4efc831277a2
|
49a7aa12799410820b5ade7be087d81f9c97b035
|
refs/heads/master
|
<file_sep>import React, { useState } from "react";
import { Button } from "reactstrap";
import { Engine, Scene, Skybox } from "react-babylonjs";
import {
Vector3,
Color3,
ActionManager,
SetValueAction
} from "@babylonjs/core";
import Octicon, { ArrowDown, ArrowUp } from "@githubprimer/octicons-react";
import ScaledModelWithProgress from "./ScaledModelWithProgress";
const onModelLoaded = model => {
let mesh = model.meshes[1];
// console.log("loaded mesh:", mesh);
console.log("loaded mesh:", mesh._scene.materials);
const materials = mesh._scene.materials;
console.log("Materials:", materials);
materials.map(mt => {
return console.log(mt.id);
});
mesh.actionManager = new ActionManager(mesh._scene);
mesh.actionManager.registerAction(
new SetValueAction(
ActionManager.OnPointerOverTrigger,
mesh.material,
"wireframe",
true
)
);
mesh.actionManager.registerAction(
new SetValueAction(
ActionManager.OnPointerOutTrigger,
mesh.material,
"wireframe",
false
)
);
};
const WithModel = props => {
const [shaftview, setShaftView] = useState(<></>);
const [elevatorSettings, updateElevatorSettings] = useState({
elevatorYPos: -1.5,
elevatorScaling: 3.0
});
const moveElevatorDown = () => {
updateElevatorSettings(state => ({
...state,
elevatorYPos: state.elevatorYPos - 0.5
}));
};
const moveElevatorUp = () => {
updateElevatorSettings(state => ({
...state,
elevatorYPos: state.elevatorYPos + 0.5
}));
};
const activateShaftView = () => {
setShaftView(
<ScaledModelWithProgress
rootUrl={`scene/`}
sceneFilename="morris-shaft.glb"
scaleTo={13.5}
progressBarColor={Color3.FromInts(255, 165, 0)}
center={new Vector3(0, -1.5, 0)}
/>
);
};
const deactivateShaftView = () => {
setShaftView(<></>);
};
// const increaseAvocadoSize = () => {
// updateElevatorSettings((state) => ({
// ...state,
// elevatorScaling: state.elevatorScaling + 0.1
// }))
// }
// const decreaseAvocadoSize = () => {
// updateElevatorSettings((state) => ({
// ...state,
// elevatorScaling: state.elevatorScaling - 0.1
// }))
// }
return (
<div>
<div className="row">
<div className="col-xs-3 col-lg-3 align-top">
Move Elevator:
<Button onClick={moveElevatorUp}>
<Octicon icon={ArrowUp} />
</Button>
<Button onClick={moveElevatorDown}>
<Octicon icon={ArrowDown} />
</Button>
</div>
<div className="col-xs-3 col-lg-3 align-top">
<Button onClick={activateShaftView}>Shaft View</Button>
<Button onClick={deactivateShaftView}>Car View</Button>
</div>
</div>
<div className="row">
<div className="col-xs-12 col">
<Engine
antialias={true}
adaptToDeviceRatio={true}
canvasId="sample-canvas"
>
<Scene>
<Skybox rootUrl={"textures/environment.dds"} />
<arcRotateCamera
name="camera1"
allowUpsideDown={false}
cameraDirection={Vector3.Zero()}
ignoreParentScaling={true}
alpha={Math.PI / 2}
beta={Math.PI / 2}
radius={9.0}
target={Vector3.Zero()}
minZ={0.001}
pinchPrecision={0.00000001}
pinchToPanMaxDistance={0.0001}
zoomOnFactor={0.00001}
/>
<hemisphericLight
name="light1"
intensity={0.7}
direction={Vector3.Up()}
/>
{shaftview}
<ScaledModelWithProgress
rootUrl={`scene/`}
sceneFilename="morris.glb"
scaleTo={3}
progressBarColor={Color3.FromInts(255, 165, 0)}
center={new Vector3(0, elevatorSettings.elevatorYPos, 0)}
onModelLoaded={onModelLoaded}
/>
</Scene>
</Engine>
</div>
</div>
</div>
);
};
export default WithModel;
<file_sep>import React, { Component } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router";
import { NavLink } from "react-router-dom";
import { Navbar, Nav, NavItem } from "reactstrap";
import Octicon, { Home, TriangleRight } from "@githubprimer/octicons-react";
import PropTypes from "prop-types";
import classNames from "classnames";
import { toggleSidebar } from "../reducers";
import "./layout.css";
class Layout extends Component {
render() {
var sideBarClassNames = classNames({
active: !this.props.showSidebar
});
var sideBarCollapseClassNames = classNames(
{ active: !this.props.showSidebar },
"navbar-btn"
);
return (
<div>
<div className="wrapper">
<nav id="sidebar" className={sideBarClassNames}>
<div className="sidebar-header">
<img
src="http://morrisgcc.com/assets/site/images/logo-white.png"
alt="Morris Elevators"
/>
</div>
<ul className="list-unstyled components">
<h3 className="sidebar-h3">Menu</h3>
<NavItem>
<NavLink
exact={true}
to={`${process.env.PUBLIC_URL}/`}
activeClassName="active"
className="nav-link"
>
<Octicon icon={Home} /> Home
</NavLink>
</NavItem>
<NavItem>
<NavLink
to={`${process.env.PUBLIC_URL}/defaultPlayground`}
activeClassName="active"
className="nav-link"
>
<Octicon icon={TriangleRight} /> Default Playground
</NavLink>
</NavItem>
</ul>
</nav>
<div id="content">
<div style={{ marginTop: "35px" }}>{this.props.children}</div>
</div>
</div>
</div>
);
}
}
Layout.propTypes = {
sidebarCollapsed: PropTypes.bool.isRequired,
onToggleSidebar: PropTypes.func.isRequired
};
const mapDispatchToProps = dispatch => {
return {
onToggleSidebar: () => {
dispatch(toggleSidebar());
}
};
};
const mapStateToProps = state => {
return state.layout;
};
const LayoutConnected = withRouter(
connect(mapStateToProps, mapDispatchToProps)(Layout)
);
export default LayoutConnected;
<file_sep>import * as React from "react";
import { Route, Switch } from "react-router-dom";
import Layout from "./layout/components";
import WithModel from "./withModel";
export const routes = (
<Layout sidebarCollapsed={false}>
<Switch>
<Route
exact={true}
path={`${process.env.PUBLIC_URL}/`}
component={WithModel}
/>
</Switch>
</Layout>
);
|
c2eea40a15b429c806adbfdd9e1c9f00ead63dcc
|
[
"JavaScript"
] | 3 |
JavaScript
|
merrillkoshy/morris-elevators
|
bac575dd15f06ddf95c066010964d45c3466b34c
|
29e37d5d185a0baedbd1929eaeff9006d9087763
|
refs/heads/master
|
<file_sep># Budgetify APP
## About
A clean administrative budget app for everyday finances. This is an ongoing personal project to fully develop a functional and complete app.
## How to use
This version works with the default local server running on port 3000. To get all the necessary modules for the app to work just run:
```sh-session
npm install
```
And then use the following command to start running the app locally:
```sh-session
npm start
```
## Pending features
This version works without data storing. In the following versions it will support:
- Database integration.
- Fully responsive front-end.
- User authentication.
<file_sep>// For authentication feature use dotenv
const express = require('express');
const bodyParser = require('body-parser');
const financeController = require('./controller/financeController');
// Building the server
const app = express();
const path = require('path');
const port = 3000;
// Rendering HTML
app.use('/assets', express.static(path.join(__dirname, 'assets')));
app.set('views', './views');
// Middleware (Parser)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/finance', financeController);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
app.listen(port, () => {
console.log('Hello! Im listening...');
});
<file_sep>-- CreateTable
CREATE TABLE "Finances" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"description" TEXT,
"value" INTEGER NOT NULL,
"type" TEXT,
"date" DATETIME NOT NULL
);
|
25ad54d428636337fbdb70a7ee6522a6339fd237
|
[
"Markdown",
"SQL",
"JavaScript"
] | 3 |
Markdown
|
gerardgal/Budgetify
|
8e10b1d827f256054bc34817406e26f35f68f05e
|
0e6138760e8236f1fea0d8b12e3bb72dd8dbe331
|
refs/heads/master
|
<file_sep>#ifndef UART_STUFF_H
#define UART_STUFF_H
#include "master_include.h"
void initUart(void);
void sendByte(int b);
void sendFloat(float f);
void uart_send_data(void);
void uart_bufferFloat(volatile uint8_t* bufptr, float f);
void uart_bufferInt32(volatile uint8_t* bufptr, uint32_t integer);
void DMA2_Stream7_IRQHandler(void);
#endif
//#ifndef UART_STUFF_H
//#define UART_STUFF_H
//
//#include "master_include.h"
//
//void initUart(void);
//void sendByte(int b);
//void sendIntsToProcessing(int a, int b, int c);
//int reverseInt(int num);
//void sendInt(int r);
//void sendFloat(float f);
//
//void uart_send_data(void);
//void uart_bufferFloat(volatile uint8_t* bufptr, float f);
//void DMA2_Stream7_IRQHandler(void);
//
//#endif
<file_sep>#ifndef VILSECOPTERBOARD_H
#define VILSECOPTERBOARD_H
#include "master_include.h"
// LED macros
#define SET_LED() GPIO_ResetBits(GPIOA, GPIO_Pin_12)
#define CLEAR_LED() GPIO_SetBits(GPIOA, GPIO_Pin_12)
//pwm out
#define PWM_OUT_GPIO GPIOC
#define PWM_OUT_TIMER TIM8 //16 bit, 168MHz clk
#define PWM_OUT_TIMER_FREQ 168000000 //RCC_GetClocksFreq(PWM_OUT_TIM_CLK);
#define PWM_OUT_AF GPIO_AF_TIM8
#define PWM_OUT_GPIO_CLK RCC_AHB1Periph_GPIOC
#define PWM_OUT_TIM_CLK RCC_APB2Periph_TIM8
#define PWM_OUT_PIN1 GPIO_Pin_6
#define PWM_OUT_PIN2 GPIO_Pin_7
#define PWM_OUT_PIN3 GPIO_Pin_8
#define PWM_OUT_PIN4 GPIO_Pin_9
#define PWM_OUT_PINSOURCE1 GPIO_PinSource6
#define PWM_OUT_PINSOURCE2 GPIO_PinSource7
#define PWM_OUT_PINSOURCE3 GPIO_PinSource8
#define PWM_OUT_PINSOURCE4 GPIO_PinSource9
#endif //VILSECOPTERBOARD_H
<file_sep>/*
* adc.c
*
* Created on: 28 feb 2014
* edited 2015-08-20
* Author: vilse
*/
#include "master_include.h"
// Settings
// Global variables
volatile uint16_t ADC_Value[ADC_CHANNEL_NUM] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
volatile float ADC_ValueAveraged[ADC_CHANNEL_NUM] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
//Private variables
// Private functions
void init_adc(void) {
/*
* using: PC0,PC1,PC2,PC3, PA0,PA1,PA2,PA3,PA4
* ADC1, ADC2
* ch10- ch13, ch0-ch4
*
* TIM4, cc4
* old: TIM3, CC1
*/
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
GPIO_Init(GPIOC, &GPIO_InitStructure);
#define ADC_CDR_ADDRESS ((uint32_t)0x40012308)
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2,ENABLE);
/* DMA2 Stream0 channel0 configuration */
DMA_InitTypeDef DMA_InitStructure;
DMA_InitStructure.DMA_Channel = DMA_Channel_0;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)&ADC_Value;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)ADC_CDR_ADDRESS;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
DMA_InitStructure.DMA_BufferSize = ADC_CHANNEL_NUM; // 12 fungerar
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
DMA_Init(DMA2_Stream0, &DMA_InitStructure);
// DMA2_Stream0 enable
DMA_Cmd(DMA2_Stream0, ENABLE);
// Enable transfer complete interrupt
DMA_ITConfig(DMA2_Stream0, DMA_IT_TC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2, ENABLE);
ADC_DeInit();
// ADC Common Init
ADC_CommonInitTypeDef ADC_CommonInitStructure;
ADC_CommonInitStructure.ADC_Mode = ADC_DualMode_RegSimult;
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2;
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_1;
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&ADC_CommonInitStructure);
// Channel-specific settings
ADC_InitTypeDef ADC_InitStructure;
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = ENABLE;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_Falling;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T4_CC4;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 8;
ADC_Init(ADC1, &ADC_InitStructure);
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_ExternalTrigConv = 0;
ADC_Init(ADC2, &ADC_InitStructure);
#define SAMPLETIME ADC_SampleTime_3Cycles
// ADC1 regular channels 0, 5, 10, 13
ADC_RegularChannelConfig(ADC1, ADC_Channel_10, 1, SAMPLETIME);
ADC_RegularChannelConfig(ADC1, ADC_Channel_12, 2, SAMPLETIME);
ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 3, SAMPLETIME);
ADC_RegularChannelConfig(ADC1, ADC_Channel_2, 4, SAMPLETIME);
ADC_RegularChannelConfig(ADC1, ADC_Channel_4, 5, SAMPLETIME);
ADC_RegularChannelConfig(ADC1, ADC_Channel_6, 6, SAMPLETIME);
ADC_RegularChannelConfig(ADC1, ADC_Channel_14, 7, SAMPLETIME);
ADC_RegularChannelConfig(ADC1, ADC_Channel_8, 8, SAMPLETIME);
// ADC2 regular channels 1, 6, 11, 15
ADC_RegularChannelConfig(ADC2, ADC_Channel_11, 1, SAMPLETIME);
ADC_RegularChannelConfig(ADC2, ADC_Channel_13, 2, SAMPLETIME);
ADC_RegularChannelConfig(ADC2, ADC_Channel_1, 3, SAMPLETIME);
ADC_RegularChannelConfig(ADC2, ADC_Channel_3, 4, SAMPLETIME);
ADC_RegularChannelConfig(ADC2, ADC_Channel_5, 5, SAMPLETIME);
ADC_RegularChannelConfig(ADC2, ADC_Channel_7, 6, SAMPLETIME);
ADC_RegularChannelConfig(ADC2, ADC_Channel_15, 7, SAMPLETIME);
ADC_RegularChannelConfig(ADC2, ADC_Channel_9, 8, SAMPLETIME);
// Enable DMA request after last transfer (Multi-ADC mode)
ADC_MultiModeDMARequestAfterLastTransferCmd(ENABLE);
// ADC_EOCOnEachRegularChannelCmd(ADC1, ENABLE);
// Enable ADC1
ADC_Cmd(ADC1, ENABLE);
// Enable ADC2
ADC_Cmd(ADC2, ENABLE);
// ------------- Timer4 for ADC sampling ------------- //
// Time Base configuration
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
TIM_TimeBaseStructure.TIM_Prescaler = 1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 84000000 / ADC_SAMPLING_FREQUENCY;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 100;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Set;
TIM_OC4Init(TIM4, &TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Disable);
TIM_OC2Init(TIM4, &TIM_OCInitStructure); //why is cc2 initiated?? it doesn't work without
TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Disable);
// PWM outputs have to be enabled in order to trigger ADC on CCx
TIM_CtrlPWMOutputs(TIM4, ENABLE);
TIM_Cmd(TIM4, ENABLE);
/* Enable ADC1 DMA since ADC1 is the Master*/
ADC_DMACmd(ADC1, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the DMA2 Stream0 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream0_IRQn ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
// Called every time all ADC channels are converted
void DMA2_Stream0_IRQHandler() {
/* Test on DMA Stream Transfer Complete interrupt */
if(DMA_GetITStatus(DMA2_Stream0, DMA_IT_TCIF0)){
/* Clear DMA Stream Transfer Complete interrupt pending bit */
DMA_ClearITPendingBit(DMA2_Stream0, DMA_IT_TCIF0);
}
int i;
for(i=0; i < ADC_CHANNEL_NUM; i++ ){
ADC_ValueAveraged[i]= ADC_AVERAGE_FILTERCONSTANT*ADC_ValueAveraged[i] + (1.0f - ADC_AVERAGE_FILTERCONSTANT)*ADC_Value[i];
}
}
<file_sep>#ifndef MPU9250_H
#define MPU9250_H
#include "master_include.h"
extern volatile float accelerometer_data[3]; //XYZ i g's
extern volatile float gyroscope_data[3]; //XYZ i degrees/s
extern volatile float magnetometer_data[3]; //XYZ i uTesla
extern volatile float mpu_temperature;
//#define MPU_ON_TFT
//#define MPU_ONBOARD
#define MPU_F4breakout
#ifdef MPU_ON_TFT
/*
* mpu on tft-port
* SCLK PPB13
* MISO PB14
* MOSI PB15
* CS PB12
* Interupt -
*
* SPI2
*/
#define MPU_CLK_GPIO GPIOB
#define MPU_CLK_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_CLK_GPIO_PIN GPIO_Pin_13
#define MPU_CLK_GPIO_PINSOURCE GPIO_PinSource13
#define MPU_MISO_GPIO GPIOB
#define MPU_MISO_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_MISO_GPIO_PIN GPIO_Pin_14
#define MPU_MISO_GPIO_PINSOURCE GPIO_PinSource14
#define MPU_MOSI_GPIO GPIOB
#define MPU_MOSI_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_MOSI_GPIO_PIN GPIO_Pin_15
#define MPU_MOSI_GPIO_PINSOURCE GPIO_PinSource15
#define MPU_CS_GPIO GPIOB
#define MPU_CS_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_CS_GPIO_PIN GPIO_Pin_12
#define MPU_SPI SPI2
#define MPU_SPI_CLK_CMD_ENABLE RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
#define MPU_AF_SPI GPIO_AF_SPI2
#elif defined MPU_ONBOARD
/*
* onboard mpu
* SCLK PA5
* MISO PA6
* MOSI PA7
* CS PC4
* Interupt PA4
*
* SPI1
*
*/
#define MPU_CLK_GPIO GPIOA
#define MPU_CLK_GPIO_CLK RCC_AHB1Periph_GPIOA
#define MPU_CLK_GPIO_PIN GPIO_Pin_5
#define MPU_CLK_GPIO_PINSOURCE GPIO_PinSource5
#define MPU_MISO_GPIO GPIOA
#define MPU_MISO_GPIO_CLK RCC_AHB1Periph_GPIOA
#define MPU_MISO_GPIO_PIN GPIO_Pin_6
#define MPU_MISO_GPIO_PINSOURCE GPIO_PinSource6
#define MPU_MOSI_GPIO GPIOA
#define MPU_MOSI_GPIO_CLK RCC_AHB1Periph_GPIOA
#define MPU_MOSI_GPIO_PIN GPIO_Pin_7
#define MPU_MOSI_GPIO_PINSOURCE GPIO_PinSource7
#define MPU_CS_GPIO GPIOC
#define MPU_CS_GPIO_CLK RCC_AHB1Periph_GPIOC
#define MPU_CS_GPIO_PIN GPIO_Pin_4
#define MPU_SPI SPI1
#define MPU_SPI_CLK_CMD_ENABLE RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
#define MPU_AF_SPI GPIO_AF_SPI1
#elif defined MPU_F4breakout
/*
* onboard mpu
* SCLK PB13
* MISO PB14
* MOSI PB15
* CS PB12
* Interupt PB11
*
* SPI2
*
*/
#define MPU_CLK_GPIO GPIOB
#define MPU_CLK_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_CLK_GPIO_PIN GPIO_Pin_13
#define MPU_CLK_GPIO_PINSOURCE GPIO_PinSource13
#define MPU_MISO_GPIO GPIOB
#define MPU_MISO_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_MISO_GPIO_PIN GPIO_Pin_14
#define MPU_MISO_GPIO_PINSOURCE GPIO_PinSource14
#define MPU_MOSI_GPIO GPIOB
#define MPU_MOSI_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_MOSI_GPIO_PIN GPIO_Pin_15
#define MPU_MOSI_GPIO_PINSOURCE GPIO_PinSource15
#define MPU_CS_GPIO GPIOB
#define MPU_CS_GPIO_CLK RCC_AHB1Periph_GPIOB
#define MPU_CS_GPIO_PIN GPIO_Pin_12
#define MPU_SPI SPI2
#define MPU_SPI_CLK_CMD_ENABLE RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
#define MPU_AF_SPI GPIO_AF_SPI2
#endif
#define MPU9250_CS_ENABLE GPIO_ResetBits(MPU_CS_GPIO, MPU_CS_GPIO_PIN); //Chip enable
#define MPU9250_CS_DISABLE GPIO_SetBits(MPU_CS_GPIO, MPU_CS_GPIO_PIN); //Chip enable
void initMPU9250(void);
uint8_t mpu9250Write_Reg(uint8_t WriteAddr, uint8_t WriteData);
#define mpu9250Read_Reg(WriteAddr, WriteData) mpu9250Write_Reg((WriteAddr) | READ_FLAG,WriteData)
void mpu9250_set_acc_scale(int scale);
void mpu9250_set_gyro_scale(int scale);
void mpu9250_read_accelerometer(void);
void mpu9250_read_gyroscope(void);
void mpu9250_read_temp(void);
void mpu9250_read_acc_calib_data(void);
void mpu9250_read_magnetometer_calib_data(void);
uint8_t mpu9250_AK8963_whoami(void);
void mpu9250_read_magnetometer(void);
void mpu9250_read_all(void);
#endif
<file_sep>#include "master_include.h"
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
void initPwm_out(){
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(PWM_OUT_GPIO_CLK,ENABLE);
/* GPIOC Configuration */
GPIO_InitStructure.GPIO_Pin=PWM_OUT_PIN1 | PWM_OUT_PIN2 | PWM_OUT_PIN3 | PWM_OUT_PIN4;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_DOWN;
GPIO_Init(PWM_OUT_GPIO,&GPIO_InitStructure);
GPIO_PinAFConfig(PWM_OUT_GPIO,PWM_OUT_PINSOURCE1,PWM_OUT_AF);
GPIO_PinAFConfig(PWM_OUT_GPIO,PWM_OUT_PINSOURCE2,PWM_OUT_AF);
GPIO_PinAFConfig(PWM_OUT_GPIO,PWM_OUT_PINSOURCE3,PWM_OUT_AF);
GPIO_PinAFConfig(PWM_OUT_GPIO,PWM_OUT_PINSOURCE4,PWM_OUT_AF);
RCC_APB2PeriphClockCmd(PWM_OUT_TIM_CLK,ENABLE);
TIM_TimeBaseStructure.TIM_Period=PWM_OUT_PERIOD_TICKS;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_ClockDivision=0;
TIM_TimeBaseStructure.TIM_Prescaler=PWM_OUT_PRESCALER;
TIM_TimeBaseInit(PWM_OUT_TIMER,&TIM_TimeBaseStructure);
//PWM out 1
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_Pulse =PWM_OUT1_INITDUTY;
TIM_OC1Init(PWM_OUT_TIMER, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(PWM_OUT_TIMER, TIM_OCPreload_Enable);
//PWM out 2
TIM_OCInitStructure.TIM_Pulse=PWM_OUT2_INITDUTY;
TIM_OC2Init(PWM_OUT_TIMER,&TIM_OCInitStructure);
TIM_OC2PreloadConfig(PWM_OUT_TIMER,TIM_OCPreload_Enable);
//PWM out 3
TIM_OCInitStructure.TIM_Pulse=PWM_OUT3_INITDUTY;
TIM_OC3Init(PWM_OUT_TIMER,&TIM_OCInitStructure);
TIM_OC3PreloadConfig(PWM_OUT_TIMER,TIM_OCPreload_Enable);
//PWM out 4
TIM_OCInitStructure.TIM_Pulse=PWM_OUT4_INITDUTY;
TIM_OC4Init(PWM_OUT_TIMER,&TIM_OCInitStructure);
TIM_OC4PreloadConfig(PWM_OUT_TIMER,TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(PWM_OUT_TIMER,ENABLE);
TIM_CtrlPWMOutputs(TIM8, ENABLE); // because timer 1 & 8 is special and doesn't just work like they ought to (ARRGH)
TIM_Cmd(PWM_OUT_TIMER,ENABLE);
}
<file_sep>/*
* vilseSensor.h
*
* Created on: 9 mar 2014
* Author: vilse
*/
#ifndef VILSESENSOR_H_
#define VILSESENSOR_H_
#include "master_include.h"
#define SENSOR_COUNT 8
#define BLACK_TRESHOLD 0.5 //1000 // is all readings lower than this, something happens
#define WHITE_TRESHOLD 0.5 //1000 // is the average of readings higher than this, something happens
typedef enum {init, onLine, lostLineRight, lostLineLeft, inAir}sensorState;
extern sensorState lineSensorState;
extern float lineSensorValue;
extern int32_t sensorCoordinate[SENSOR_COUNT];
extern int32_t sensorMins[SENSOR_COUNT];
extern int32_t sensorMaxs[SENSOR_COUNT];
extern const int32_t orderInADC[SENSOR_COUNT];
#define getSensorReadingRaw(i) (ADC_ValueAveraged[orderInADC[i]])
#define getSensorReadingNormalized(i) ((getSensorReadingRaw(i) - sensorMins[i])/(float)(sensorMaxs[i] - sensorMins[i]))
void initLineSensor(void);
void lineSensorCalibrate(void);
void updateSensorReading(void);
#endif /* VILSESENSOR_H_ */
<file_sep>#include "master_include.h"
//TODO led indicate when in a delay
void delay_ms(uint32_t ms){
volatile uint32_t stop_time= (TIM2->CNT)+ms*100;
while(stop_time > TIM2->CNT);
}
void delay_us(uint32_t us){
volatile uint32_t stop_time= (TIM2->CNT)+(us/10);
while(stop_time > TIM2->CNT);
}
//uint32_t get_time_tics(){
// return TIM2->CNT;
//}
//void sleep_until_ticks(uint32_t stop_tick){
// while(stop_tick > TIM2->CNT);
//}
void initTime(){
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//84mhz, 10us per tick
TIM_TimeBaseStructure.TIM_Prescaler=840;
TIM_TimeBaseStructure.TIM_Period=0xFFFFFFFF;// 4294967295;//2^32-1 gets overflow after about 11.9 hours
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_ClockDivision=0;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);
TIM_Cmd(TIM2,ENABLE);
}
<file_sep># lineFollowerV2
a line follower robot
<file_sep>
#include "master_include.h"
DMA_InitTypeDef DMA_InitStructure; //this declaration is here because the initstructure is used every time a new DMA transfer is done to set everything up
#define UART_TX_MAX_DATA_ITEMS 11
#define UART_TX_MAX_BUFFERSIZE (6+4+4*UART_TX_MAX_DATA_ITEMS) // 4 bytes of sync data and then each data item is 4 uart transfers long
volatile uint8_t uart_tx_buf[UART_TX_MAX_BUFFERSIZE];
volatile bool uart_tx_complete = true;
volatile bool uart_send_data_1 = true;
volatile bool uart_send_data_2 = false;
volatile bool uart_send_data_3 = false;
volatile bool uart_send_data_4 = false;
volatile bool uart_send_time = false;
volatile float dummy = 0;
//don't use this, it is slow
void sendFloat(float f){
int i;
char *str = (char *) &f;
for(i=3; i>=0;i--){
sendByte(str[i]); // reverse order
}
}
/*
* fills the specified buffer with 4 bytes containing the float
*/
void uart_bufferFloat(volatile uint8_t* bufptr, float f){
int i;
char *str = (char *) &f;
int j = 0;
for(i=3; i>=0;i--){
bufptr[j] = str[i];
j++;
// reverse order
}
}
/*
* fills the specified buffer with 4 bytes containing the integer
*/
void uart_bufferInt32(volatile uint8_t* bufptr, uint32_t integer){
int i;
char *str = (char *) &integer;
for(i=0; i<4;i++){
bufptr[i] = str[i];
}
}
void initUart(void) {
/*
* PA9 tx
* PA10 rx
*
* USART1
*/
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIO clock */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
/* Configure USART Rx & Tx as alternate function */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Mux out USART1 Rx & Tx */
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);
/* Enable USART1 clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_InitTypeDef USART_InitStructure;
USART_OverSampling8Cmd(USART1, DISABLE);
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
/* USART configuration */
USART_Init(USART1, &USART_InitStructure);
//interrupt setup
NVIC_InitTypeDef NVIC_InitStructure; // this is used to configure the NVIC (nested vector interrupt controller)
/* Here the USART1 receive interrupt is enabled
* and the interrupt controller is configured
* to jump to the USART1_IRQHandler() function
* if the USART1 receive interrupt occurs
*/
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; // we want to configure the USART1 interrupts
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;// this sets the priority group of the USART1 interrupts, this is the next highest priority
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; // this sets the subpriority inside the group
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; // the USART1 interrupts are globally enabled
NVIC_Init(&NVIC_InitStructure); // the properties are passed to the NVIC_Init function which takes care of the low level stuff
NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream7_IRQn;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); // enable the USART1 receive interrupt
//DMA TX setup
/*
* DMA2, channel 4, stream7: USART1_TX
*
*/
/* Enable DMA clock */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
while (DMA_GetCmdStatus(DMA2_Stream7) != DISABLE){
}
if(DMA_GetCmdStatus(DMA2_Stream7) == ENABLE){
while(DMA_GetFlagStatus(DMA2_Stream7, DMA_FLAG_TCIF7) == RESET);
}
/* Configure DMA Stream */
DMA_StructInit(&DMA_InitStructure);
DMA_InitStructure.DMA_Channel = DMA_Channel_4;
DMA_InitStructure.DMA_PeripheralBaseAddr = USART1_BASE+0x04;//(uint32_t) USART1->DR; //??
DMA_InitStructure.DMA_Memory0BaseAddr =(uint32_t)uart_tx_buf; // tog bort & framför
DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
DMA_InitStructure.DMA_BufferSize = (uint16_t)UART_TX_MAX_BUFFERSIZE;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;
DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable; //??
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
// Init of dma everytime i use it
USART_DMACmd(USART1,USART_DMAReq_Tx, ENABLE);
/* Enable USART */
USART_Cmd(USART1, ENABLE);
}
void DMA2_Stream7_IRQHandler(void){
//TODO kolla om TC enabled, dock onödigt nu pga inga andra interrupt aktiverade
//clear pending bit
DMA_ClearITPendingBit(DMA2_Stream7,DMA_IT_TCIF7);
//disable dma
DMA_Cmd(DMA2_Stream7, DISABLE); //ev onödigt
uart_tx_complete = true;
}
// this is the interrupt request handler (IRQ) for ALL USART1 interrupts
void USART1_IRQHandler(void){
// check if the USART1 receive interrupt flag was set
if( USART_GetITStatus(USART1, USART_IT_RXNE) ){
char temp = USART1->DR;
//check which command the
float recieved_parameter; // dummy variable, not used
(void) recieved_parameter;
switch(temp){
case 'P' :
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); /* Wait for next rx */
recieved_parameter = 0.01f*0.00392156862f* USART1->DR; // the following value is the parameter
// Kp_p = 0.00392156862f* USART1->DR; // the following value is the parameter
//if 255 is sent, kp will end up as around 1
break;
case 'I' :
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); /* Wait for next rx */
recieved_parameter = 0.01f*0.00392156862f* USART1->DR; // the following value is the parameter
// Ki_p = 0.00392156862f* USART1->DR; // the following value is the parameter
break;
case 'D' :
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); /* Wait for next rx */
recieved_parameter = 0.01f*0.00392156862f* USART1->DR; // the following value is the parameter
// Kd_p = 0.00392156862f* USART1->DR; // the following value is the parameter
break;
case 'C' :
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); /* Wait for next rx */
int temp1 = USART1->DR;
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); /* Wait for next rx */
int temp2 = USART1->DR;
bool temp3=false;
if(temp2 == 'E') {
temp3 = true;
}
switch (temp1) {
case 0:
uart_send_data_1=temp3;
break;
case 1:
uart_send_data_2=temp3;
break;
case 2:
uart_send_data_3=temp3;
break;
case 3:
uart_send_data_4=temp3;
break;
case 4:
uart_send_time=temp3;
break;
default:
break;
}
break;
}
}
}
/*
* call this function to begin uart transfer of data
* transfer is taken care of by DMA and nothing will happen if the DMA is busy
*/
void uart_send_data(void){
if(!uart_tx_complete){
if(DMA_GetFlagStatus(DMA2_Stream7,DMA_FLAG_TCIF7) == RESET){
return; // if last data transfer isn't complete yet, we can't wait here to let it finish, just throw away the data
}
}
//check if there is something to send
if(!uart_send_data_1 && !uart_send_data_2 && !uart_send_data_3 && !uart_send_data_4 && !uart_send_time){
return;
}
// fill buffer with data
// start with the 4 sync-bytes ,TODO this doesn't need to be done every time
uart_tx_buf[0] = 0xFF;
uart_tx_buf[1] = 0xFF;
uart_tx_buf[2] = 0x00;
uart_tx_buf[3] = 0xFF;
int j = 4;
if(uart_send_data_1){
uart_tx_buf[j] = '1';
j++;
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(0));
j=j+4;
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(1));
j=j+4;
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(2));
j=j+4;
}
if(uart_send_data_2){
uart_tx_buf[j] = '2';
j++;
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(3));
j=j+4;
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(4));
j=j+4;
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(5));
j=j+4;
}
if(uart_send_data_3){
uart_tx_buf[j] = '3';
j++;//2700
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(6));
j=j+4;
uart_bufferFloat(uart_tx_buf + j, 300*getSensorReadingNormalized(7));
j=j+4;
uart_bufferFloat(uart_tx_buf + j, dummy);
j=j+4;
}
if(uart_send_data_4){
uart_tx_buf[j] = '4';
j++;
uart_bufferFloat(uart_tx_buf + j, (300/(float)35)*lineSensorValue);
j=j+4;
}
if(uart_send_time){
uart_tx_buf[j] = 't';
j++;
uint32_t curr_time = get_time_tics();
uart_bufferInt32(uart_tx_buf + j, curr_time);
j=j+4;
}
uart_tx_buf[j] = 4; // indicating the end with "end of transmission in ascii
j++;
//TODO clean up rest of the buffer
//set up DMA to transmit buffer
DMA_ITConfig(DMA2_Stream7,DMA_IT_TC, DISABLE);
DMA_ClearFlag(DMA2_Stream7,DMA_FLAG_TCIF7);
uart_tx_complete = false;
DMA_Cmd(DMA2_Stream7, DISABLE);
DMA_SetCurrDataCounter(DMA2_Stream7, j);
/* Reset DMA Stream registers (for debug purpose) */
DMA_DeInit(DMA2_Stream7);
DMA_InitStructure.DMA_Memory0BaseAddr =(uint32_t)uart_tx_buf; // tog bort & framför
DMA_InitStructure.DMA_BufferSize = (uint16_t)j;
DMA_Init(DMA2_Stream7, &DMA_InitStructure);
// /* Enable DMA Stream Transfer Complete interrupt */
// DMA_ITConfig(DMA2_Stream7, DMA_IT_TC, ENABLE);
/* DMA Stream enable */
DMA_Cmd(DMA2_Stream7, ENABLE);
/* Check if the DMA Stream has been effectively enabled.
The DMA Stream Enable bit is cleared immediately by hardware if there is an
error in the configuration parameters and the transfer is no started (ie. when
wrong FIFO threshold is configured ...) */
while ((DMA_GetCmdStatus(DMA2_Stream7) != ENABLE)){
}
DMA_ITConfig(DMA2_Stream7,DMA_IT_TC, ENABLE); // enable the transfer complete interrupt
}
void sendByte(int b) {
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); /* Waitwhile TX full */
USART_SendData(USART1, b);
}
<file_sep>#ifndef MASTER_INCLUDE_H
#define MASTER_INCLUDE_H
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_spi.h"
#include "math.h"
#include "stdint-gcc.h"
#include "stm32f4xx_tim.h"
#include "misc.h"
#include "stm32f4xx_usart.h"
#include "stm32f4xx_dma.h"
#include "stm32f4xx_adc.h"
#include <stdbool.h>
#include <stdio.h>
#include <stddef.h>
#include "time.h"
#include "MPU9250_register_map.h"
#include "MPU9250.h"
//#include "MS5611_01BA03.h"
#include "board.h"
#include "pwm_out.h"
//#include "quadcopter_control.h"
#include "uart_stuff.h"
//#include "control.h"
#include "adc.h"
#include "main.h"
#include "motors.h"
#include "lineSensor.h"
//#include "stm32f4xx_conf.h"
//#include <stdlib.h>
#endif //MASTER_INCLUDE_H
<file_sep>#ifndef PWM_OUT_H
#define PWM_OUT_H
#include "master_include.h"
#include <stdio.h>
#include <math.h>
#define PWM_OUT_FREQ 15000//Hz
#define PWM_OUT_PERIOD_MS (1000/(float)PWM_OUT_FREQ) //2 ms
#define PWM_OUT_PERIOD_US (1000000/(float)PWM_OUT_FREQ) //2000 us
#define PWM_OUT1_INITDUTY 0
#define PWM_OUT2_INITDUTY 0
#define PWM_OUT3_INITDUTY 0
#define PWM_OUT4_INITDUTY 0
#define PWM_OUT_TIMER_MAX_PERIOD 65535
#if (PWM_OUT_TIMER_FREQ/PWM_OUT_TIMER_MAX_PERIOD) >= PWM_OUT_FREQ
#define PWM_OUT_PRESCALER (ceil(PWM_OUT_TIMER_FREQ/(float)PWM_OUT_TIMER_MAX_PERIOD/(float)PWM_OUT_FREQ) - 1)
#else
#define PWM_OUT_PRESCALER 0
#endif
#define PWM_OUT_PERIOD_TICKS (PWM_OUT_TIMER_FREQ/(PWM_OUT_PRESCALER+1)/PWM_OUT_FREQ)
#define PWM_OUT_NORMALIZED_TO_TICKS(pwm) ((pwm)*(float)PWM_OUT_PERIOD_TICKS)
#define PWM_OUT1_DUTY PWM_OUT_TIMER->CCR1
#define PWM_OUT2_DUTY PWM_OUT_TIMER->CCR2
#define PWM_OUT3_DUTY PWM_OUT_TIMER->CCR3
#define PWM_OUT4_DUTY PWM_OUT_TIMER->CCR4
void initPwm_out(void);
#endif //PWM_OUT_H
<file_sep>
#include "master_include.h"
uint32_t acc_divider;
float gyro_divider;
volatile float accelerometer_data[3]; //XYZ i g's
volatile float gyroscope_data[3]; //XYZ i degrees/s
volatile float magnetometer_data[3]; //XYZ i uTesla
volatile float mpu_temperature;
volatile int accelerometer_calib_data[3];
volatile float gyroscope_calib_data[3]={0,0,0}; // simple offset from startup value
float Magnetometer_ASA[3];
void initMPU9250(void){
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
/*
* SCLK PB13
* MISO PB14
* MOSI PB15
* CS PB12
* Interupt --
*
* SPI2
*
*/
//GPIO config
RCC_AHB1PeriphClockCmd(MPU_CLK_GPIO_CLK, ENABLE);
RCC_AHB1PeriphClockCmd(MPU_MISO_GPIO_CLK, ENABLE);
RCC_AHB1PeriphClockCmd(MPU_MOSI_GPIO_CLK, ENABLE);
RCC_AHB1PeriphClockCmd(MPU_CS_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Pin = MPU_MOSI_GPIO_PIN; //MOSI
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;//?
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //?
GPIO_Init(MPU_MOSI_GPIO, &GPIO_InitStructure);//MOSI
GPIO_InitStructure.GPIO_Pin = MPU_CLK_GPIO_PIN;
GPIO_Init(MPU_CLK_GPIO, &GPIO_InitStructure);//CLK
// OD för SDO?
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
GPIO_InitStructure.GPIO_Pin = MPU_MISO_GPIO_PIN;
GPIO_Init(MPU_MISO_GPIO, &GPIO_InitStructure);//MISO
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_Pin = MPU_CS_GPIO_PIN;
GPIO_Init(MPU_CS_GPIO, &GPIO_InitStructure);// CS
MPU9250_CS_DISABLE
// SDN_L;
// SDI_L;
// SEL_H;
// delay_ms(10);
GPIO_PinAFConfig(MPU_CLK_GPIO, MPU_CLK_GPIO_PINSOURCE, MPU_AF_SPI);
GPIO_PinAFConfig(MPU_MISO_GPIO, MPU_MISO_GPIO_PINSOURCE, MPU_AF_SPI);
GPIO_PinAFConfig(MPU_MOSI_GPIO, MPU_MOSI_GPIO_PINSOURCE, MPU_AF_SPI);
//SPI config
MPU_SPI_CLK_CMD_ENABLE
SPI_I2S_DeInit(MPU_SPI);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft | SPI_NSSInternalSoft_Set;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64; //APB1 kör 42Mhz, mpu vill ha max 1mhz
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
/* Initializes the SPI communication */
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_Init(MPU_SPI, &SPI_InitStructure);
SPI_Cmd(MPU_SPI, ENABLE); // enable SPI2
delay_ms(150);
// uint8_t test = mpu9250Read_Reg(0x75, 0);
uint8_t i = 0;
uint8_t MPU_Init_Data[17][2] = {
{0x80, MPUREG_PWR_MGMT_1}, // Reset Device
{0x01, MPUREG_PWR_MGMT_1}, // Clock Source
{0x00, MPUREG_PWR_MGMT_2}, // Enable Acc & Gyro
{BITS_DLPF_CFG_10HZ, MPUREG_CONFIG}, // Use DLPF set Gyroscope bandwidth 184Hz, temperature bandwidth 188Hz
{0x18, MPUREG_GYRO_CONFIG}, // +-2000dps
{0x08, MPUREG_ACCEL_CONFIG}, // +-4G
{0x09, MPUREG_ACCEL_CONFIG_2}, // Set Acc Data Rates, Enable Acc LPF , Bandwidth 184Hz
{0x30, MPUREG_INT_PIN_CFG}, //
//{0x40, MPUREG_I2C_MST_CTRL}, // I2C Speed 348 kHz
//{0x20, MPUREG_USER_CTRL}, // Enable AUX
{0x20, MPUREG_USER_CTRL}, // I2C Master mode
{0x0D, MPUREG_I2C_MST_CTRL}, // I2C configuration multi-master IIC 400KHz
{AK8963_I2C_ADDR, MPUREG_I2C_SLV0_ADDR}, //Set the I2C slave addres of AK8963 and set for write.
//{0x09, MPUREG_I2C_SLV4_CTRL},
//{0x81, MPUREG_I2C_MST_DELAY_CTRL}, //Enable I2C delay
{AK8963_CNTL2, MPUREG_I2C_SLV0_REG}, //I2C slave 0 register address from where to begin data transfer
{0x01, MPUREG_I2C_SLV0_DO}, // Reset AK8963
{0x81, MPUREG_I2C_SLV0_CTRL}, //Enable I2C and set 1 byte
{AK8963_CNTL1, MPUREG_I2C_SLV0_REG}, //I2C slave 0 register address from where to begin data transfer
{0x12, MPUREG_I2C_SLV0_DO}, // Register value to continuous measurement in 16bit
{0x81, MPUREG_I2C_SLV0_CTRL} //Enable I2C and set 1 byte
};
for(i=0; i<17; i++) {
mpu9250Write_Reg(MPU_Init_Data[i][1], MPU_Init_Data[i][0]);
delay_ms(1); //I2C must slow down the write speed, otherwise it won't work
}
delay_ms(100);
// uint8_t whoami = mpu9250Read_Reg(MPUREG_WHOAMI, 0x00);
mpu9250_set_acc_scale(BITS_ACCEL_FS_SEL_2G);
mpu9250_set_gyro_scale(BITS_GYRO_FS_SEL_250DPS);
mpu9250_read_acc_calib_data();
mpu9250_read_magnetometer_calib_data();
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16; //APB1 kör 42Mhz, mpu vill ha max 20mhz på sensorvärde registren
SPI_Init(MPU_SPI, &SPI_InitStructure);
mpu9250_read_all();
gyroscope_calib_data[0] = gyroscope_data[0];
gyroscope_calib_data[1] = gyroscope_data[1];
gyroscope_calib_data[2] = gyroscope_data[2];
//AK8963_calib_Magnetometer(); //Can't load this function here , strange problem?
}
uint8_t mpu9250Write_Reg(uint8_t WriteAddr, uint8_t WriteData){
uint8_t temp;
MPU9250_CS_ENABLE
// (void)MPU_SPI->DR;// to clear the rxne flag
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_TXE) == RESET); //waiting for spi being ready
SPI_I2S_SendData(MPU_SPI, WriteAddr);
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_RXNE) == RESET); // could change to txe
temp=MPU_SPI->DR;
SPI_I2S_SendData(MPU_SPI, WriteData);
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_RXNE) == RESET);
temp=MPU_SPI->DR;
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_BSY) == SET);
//tiny delay
volatile int i;
for(i=0;i<10;i++);
MPU9250_CS_DISABLE
for(i=0;i<100;i++);//probably unecessary
return temp;
}
void mpu9250Read_Regs( uint8_t ReadAddr, uint8_t *ReadBuf, unsigned int Bytes ){
volatile uint8_t temp;
volatile unsigned int i = 0;
MPU9250_CS_ENABLE
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_TXE) == RESET); //waiting for spi being ready
SPI_I2S_SendData(MPU_SPI, ReadAddr | READ_FLAG);
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_RXNE) == RESET); // could change to txe
temp=MPU_SPI->DR;//clear RXNE
(void)temp;
for(i=0; i<Bytes; i++){
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_TXE) == RESET);
SPI_I2S_SendData(MPU_SPI, 0x00);
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_RXNE) == RESET); // could change to txe
ReadBuf[i] = MPU_SPI->DR;
}
while(SPI_I2S_GetFlagStatus(MPU_SPI, SPI_I2S_FLAG_BSY) == SET);
//tiny delay
for(i=0;i<1;i++);
MPU9250_CS_DISABLE
for(i=0;i<100;i++);//probably unecessary
}
/*-----------------------------------------------------------------------------------------------
ACCELEROMETER SCALE
usage: call this function at startup, after initialization, to set the right range for the
accelerometers. Suitable ranges are:
BITS_FS_2G
BITS_FS_4G
BITS_FS_8G
BITS_FS_16G
returns the range set (2,4,8 or 16)
-----------------------------------------------------------------------------------------------*/
void mpu9250_set_acc_scale(int scale){
mpu9250Write_Reg(MPUREG_ACCEL_CONFIG, scale); // TODO read register first and mask with original content of register
switch (scale){
case BITS_ACCEL_FS_SEL_2G:
acc_divider=16384;
break;
case BITS_ACCEL_FS_SEL_4G:
acc_divider=8192;
break;
case BITS_ACCEL_FS_SEL_8G:
acc_divider=4096;
break;
case BITS_ACCEL_FS_SEL_16G:
acc_divider=2048;
break;
}
}
/*-----------------------------------------------------------------------------------------------
GYROSCOPE SCALE
usage: call this function at startup, after initialization, to set the right range for the
gyroscopes. Suitable ranges are:
BITS_FS_250DPS
BITS_FS_500DPS
BITS_FS_1000DPS
BITS_FS_2000DPS
returns the range set (250,500,1000 or 2000)
-----------------------------------------------------------------------------------------------*/
void mpu9250_set_gyro_scale(int scale){
mpu9250Write_Reg(MPUREG_GYRO_CONFIG, scale);// TODO read register first and mask with original content of register
switch (scale){
case BITS_GYRO_FS_SEL_250DPS:
gyro_divider=131;
break;
case BITS_GYRO_FS_SEL_500DPS:
gyro_divider=65.5;
break;
case BITS_GYRO_FS_SEL_1000DPS:
gyro_divider=32.8;
break;
case BITS_GYRO_FS_SEL_2000DPS:
gyro_divider=16.4;
break;
}
}
/*-----------------------------------------------------------------------------------------------
READ ACCELEROMETER
usage: call this function to read accelerometer data. Axis represents selected axis:
0 -> X axis
1 -> Y axis
2 -> Z axis
-----------------------------------------------------------------------------------------------*/
void mpu9250_read_accelerometer(){
uint8_t response[6];
int16_t bit_data;
float data;
int i;
mpu9250Read_Regs(MPUREG_ACCEL_XOUT_H,response,6);
for(i=0; i<3; i++) {
bit_data=((int16_t)response[i*2]<<8)|response[i*2+1];
data=(float)bit_data;
accelerometer_data[i]=data/acc_divider;
}
}
/*-----------------------------------------------------------------------------------------------
READ GYROSCOPE
usage: call this function to read gyroscope data. Axis represents selected axis:
0 -> X axis
1 -> Y axis
2 -> Z axis
-----------------------------------------------------------------------------------------------*/
void mpu9250_read_gyroscope(){
uint8_t response[6];
int16_t bit_data;
float data;
int i;
mpu9250Read_Regs(MPUREG_GYRO_XOUT_H,response,6);
for(i=0; i<3; i++) {
bit_data=((int16_t)response[i*2]<<8)|response[i*2+1];
data=(float)bit_data;
gyroscope_data[i]=data/gyro_divider -gyroscope_calib_data[i];
}
}
/*-----------------------------------------------------------------------------------------------
READ TEMPERATURE
usage: call this function to read temperature data.
returns the value in °C
-----------------------------------------------------------------------------------------------*/
void mpu9250_read_temp(){
uint8_t response[2];
int16_t bit_data;
float data;
mpu9250Read_Regs(MPUREG_TEMP_OUT_H,response,2);
bit_data=((int16_t)response[0]<<8)|response[1];
data=(float)bit_data;
mpu_temperature=(data/340)+36.53;
}
/*-----------------------------------------------------------------------------------------------
READ ACCELEROMETER CALIBRATION
usage: call this function to read accelerometer data. Axis represents selected axis:
0 -> X axis
1 -> Y axis
2 -> Z axis
returns Factory Trim value
-----------------------------------------------------------------------------------------------*/
void mpu9250_read_acc_calib_data(){
uint8_t response[4];
int temp_scale;
//READ CURRENT ACC SCALE
temp_scale=mpu9250Read_Reg(MPUREG_ACCEL_CONFIG, 0x00);
mpu9250_set_acc_scale(BITS_ACCEL_FS_SEL_8G);//calibration must be done with this scale
//ENABLE SELF TEST need modify
//temp_scale=WriteReg(MPUREG_ACCEL_CONFIG, 0x80>>axis);
mpu9250Read_Regs(MPUREG_SELF_TEST_X,response,4);
accelerometer_calib_data[0]=((response[0]&11100000)>>3)|((response[3]&00110000)>>4);
accelerometer_calib_data[1]=((response[1]&11100000)>>3)|((response[3]&00001100)>>2);
accelerometer_calib_data[2]=((response[2]&11100000)>>3)|((response[3]&00000011));
mpu9250_set_acc_scale(temp_scale); //change back the scale
}
uint8_t mpu9250_AK8963_whoami(){
uint8_t response;
mpu9250Read_Reg(MPUREG_I2C_SLV0_ADDR,AK8963_I2C_ADDR); //Set the I2C slave addres of AK8963 and set for read.
mpu9250Write_Reg(MPUREG_I2C_SLV0_REG, AK8963_WIA); //I2C slave 0 register address from where to begin data transfer
mpu9250Write_Reg(MPUREG_I2C_SLV0_CTRL, 0x81); //Read 1 byte from the magnetometer
//WriteReg(MPUREG_I2C_SLV0_CTRL, 0x81); //Enable I2C and set bytes
delay_ms(1);
response=mpu9250Read_Reg(MPUREG_EXT_SENS_DATA_00, 0x00); //Read I2C
//ReadRegs(MPUREG_EXT_SENS_DATA_00,response,1);
//response=WriteReg(MPUREG_I2C_SLV0_DO, 0x00); //Read I2C
return response;
}
void mpu9250_read_magnetometer_calib_data(){
uint8_t response[3];
float data;
int i;
mpu9250Write_Reg(MPUREG_I2C_SLV0_ADDR,AK8963_I2C_ADDR|READ_FLAG); //Set the I2C slave addres of AK8963 and set for read.
mpu9250Write_Reg(MPUREG_I2C_SLV0_REG, AK8963_ASAX); //I2C slave 0 register address from where to begin data transfer
mpu9250Write_Reg(MPUREG_I2C_SLV0_CTRL, 0x83); //Read 3 bytes from the magnetometer
//WriteReg(MPUREG_I2C_SLV0_CTRL, 0x81); //Enable I2C and set bytes
delay_ms(1);
//response[0]=WriteReg(MPUREG_EXT_SENS_DATA_01|READ_FLAG, 0x00); //Read I2C
mpu9250Read_Regs(MPUREG_EXT_SENS_DATA_00,response,3);
//response=WriteReg(MPUREG_I2C_SLV0_DO, 0x00); //Read I2C
for(i=0; i<3; i++) {
data=response[i];
Magnetometer_ASA[i]=((float)(data-128)/256+1)*Magnetometer_Sensitivity_Scale_Factor;
}
}
void mpu9250_read_magnetometer(){
uint8_t response[7];
int16_t bit_data;
float data;
int i;
mpu9250Write_Reg(MPUREG_I2C_SLV0_ADDR,AK8963_I2C_ADDR|READ_FLAG); //Set the I2C slave addres of AK8963 and set for read.
mpu9250Write_Reg(MPUREG_I2C_SLV0_REG, AK8963_HXL); //I2C slave 0 register address from where to begin data transfer
mpu9250Write_Reg(MPUREG_I2C_SLV0_CTRL, 0x87); //Read 6 bytes from the magnetometer
delay_ms(1);
mpu9250Read_Regs(MPUREG_EXT_SENS_DATA_00,response,7);
//must start your read from AK8963A register 0x03 and read seven bytes so that upon read of ST2 register 0x09 the AK8963A will unlatch the data registers for the next measurement.
for(i=0; i<3; i++) {
bit_data=((int16_t)response[i*2+1]<<8)|response[i*2];
data=(float)bit_data;
magnetometer_data[i]=data*Magnetometer_ASA[i];
}
}
void mpu9250_read_all(){
uint8_t response[21];
int16_t bit_data;
float data;
int i;
// uncomment if you will use magnetometer
// //Send I2C command at first
// mpu9250Write_Reg(MPUREG_I2C_SLV0_ADDR,AK8963_I2C_ADDR|READ_FLAG); //Set the I2C slave addres of AK8963 and set for read.
// mpu9250Write_Reg(MPUREG_I2C_SLV0_REG, AK8963_HXL); //I2C slave 0 register address from where to begin data transfer
// mpu9250Write_Reg(MPUREG_I2C_SLV0_CTRL, 0x87); //Read 7 bytes from the magnetometer
// //must start your read from AK8963A register 0x03 and read seven bytes so that upon read of ST2 register 0x09 the AK8963A will unlatch the data registers for the next measurement.
//delay_ms(1);
mpu9250Read_Regs(MPUREG_ACCEL_XOUT_H,response,21);
//Get accelerometer value
for(i=0; i<3; i++) {
bit_data=((int16_t)response[i*2]<<8)|response[i*2+1];
data=(float)bit_data;
accelerometer_data[i]=data/acc_divider;
}
//Get temperature
bit_data=((int16_t)response[i*2]<<8)|response[i*2+1];
data=(float)bit_data;
mpu_temperature=((data-21)/333.87)+21;
//Get gyroscop value
for(i=4; i<7; i++) {
bit_data=((int16_t)response[i*2]<<8)|response[i*2+1];
data=(float)bit_data;
gyroscope_data[i-4]=data/gyro_divider-gyroscope_calib_data[i-4];
}
//Get Magnetometer value
for(i=7; i<10; i++) {
bit_data=((int16_t)response[i*2+1]<<8)|response[i*2];
data=(float)bit_data;
magnetometer_data[i-7]=data*Magnetometer_ASA[i-7];
}
}
<file_sep>#ifndef MOTORS_H_
#define MOTORS_H_
#include "master_include.h"
extern volatile float motor_right;
extern volatile float motor_left;
extern volatile uint32_t motor_right_ticks;
extern volatile uint32_t motor_left_ticks;
void initMotors(void);
void stopMotors(void);
void setRightMotor(float pwm);
void setLeftMotor(float pwm);
#endif /* MOTORS_H_ */
<file_sep>#ifndef TIME_H
#define TIME_H
#include "master_include.h"
#define CONTROL_LOOP_FREQ 2000
#define CONTROL_LOOP_PERIOD (1/(float)CONTROL_LOOP_FREQ)
#define get_time_tics() TIM2->CNT
#define sleep_until_ticks(finish_tick) while(finish_tick > TIM2->CNT){}
#define ms_to_tics(ms) (ms*(float)100)
void delay_ms(uint32_t ms);
void delay_us(uint32_t us);
void initTime(void);
#endif //TIME_H
<file_sep>
#include "master_include.h"
volatile float motor_right;
volatile float motor_left;
volatile uint32_t motor_right_ticks;
volatile uint32_t motor_left_ticks;
#define PWM_IN1_A2 PWM_OUT1_DUTY//PC6
#define PWM_IN2_A2 PWM_OUT2_DUTY//PC7
#define PWM_IN2_B2 PWM_OUT3_DUTY//PC8
#define PWM_IN1_B2 PWM_OUT4_DUTY//PC9
//uint8_t pin_in1[] = {pin_in1_A1, pin_in1_A2, pin_in1_B1, pin_in1_B2};
//uint8_t pin_in2[] = {pin_in2_A1, pin_in2_A2, pin_in2_B1, pin_in2_B2};
//
//float lastPwm[] = {0,0};
//int32_t motorPwmFreq = 15000;
//volatile float timeStepcurrentmilliAmpsControll = 1/(float)motorPwmFreq;
//
//// U=R*I, R = 270, I = 0.0024*currentmilliAmps
//// U = 270*0.0024*currentmilliAmps
//// U = 0,648*currentmilliAmps
//float lsbVolt = 0.0012;
//volatile int32_t multiplier = round(1000*(1/(float)0.648)*lsbVolt);
//
//volatile int32_t currentmilliAmpsRef = 0;
//
//volatile int32_t currentmilliAmpsIntergral = 0;
//volatile int32_t val = 0;
//
//volatile int32_t pidP = (float)0.2*(float)motorPwmFreq;
//volatile int32_t pidI = 250;
//volatile int32_t currentmilliAmps = 0;
#define ENABLE_MOTORS() GPIO_ResetBits(GPIOB, GPIO_Pin_5)
#define DISABLE_MOTORS() GPIO_SetBits(GPIOB, GPIO_Pin_5)
void initMotors(){
//disable motors PB5
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// stopMotors();
ENABLE_MOTORS();
}
float saturate(float in){
if (in > 1){
return 1;
}else if(in < -1){
return -1;
}else {
return in;
}
}
void setRightMotor(float pwm){
pwm = saturate(pwm);
pwm *= 0.5;
if(pwm >= 0){
PWM_IN1_A2 = PWM_OUT_NORMALIZED_TO_TICKS(pwm);
PWM_IN2_A2 = PWM_OUT_NORMALIZED_TO_TICKS(0);
}else{
PWM_IN1_A2 = PWM_OUT_NORMALIZED_TO_TICKS(0);
PWM_IN2_A2 = PWM_OUT_NORMALIZED_TO_TICKS(-pwm);
}
}
void setLeftMotor(float pwm){
pwm = saturate(pwm);
if(pwm >= 0){
PWM_IN1_B2 = PWM_OUT_NORMALIZED_TO_TICKS(pwm);
PWM_IN2_B2 = PWM_OUT_NORMALIZED_TO_TICKS(0);
}else{
PWM_IN1_B2 = PWM_OUT_NORMALIZED_TO_TICKS(0);
PWM_IN2_B2 = PWM_OUT_NORMALIZED_TO_TICKS(-pwm);
}
}
///*
// * motorPwm is in range -1000 to 1000
// */
//void setMotorPwm(int motorIndex, int32_t motorPwm){
// int32_t maxPwm = 1000;
// if (motorPwm > maxPwm){
// motorPwm = maxPwm;
// }else if(motorPwm < -maxPwm){
// motorPwm = -maxPwm;
// }
//
// int32_t absPwm = motorPwm;
// if (absPwm < 0) absPwm = - absPwm;
//
//// if (motorIndex == 0){
//// temptemp = (maxAnalogWrite*(maxPwm-absPwm))/maxPwm;
//// }
//
//// if (motorPwm == 0){
//// analogWrite(pin_in1[motorIndex], 0);
//// analogWrite(pin_in2[motorIndex], 0);
//// }else if (motorPwm < 0){
//// analogWrite(pin_in1[motorIndex], maxAnalogWrite);
//// analogWrite(pin_in2[motorIndex], (maxAnalogWrite*(maxPwm-absPwm))/maxPwm);
//// }else{
//// analogWrite(pin_in1[motorIndex], (maxAnalogWrite*(maxPwm-absPwm))/maxPwm);
//// analogWrite(pin_in2[motorIndex], maxAnalogWrite);
//// }
// // if (motorPwm*lastPwm[motorIndex] > 0){
// // //keep going in same direction, so nothing to do
// // }else if (motorPwm==0) {
// // digitalWrite(directionPin1[motorIndex],HIGH);
// // digitalWrite (directionPin2[motorIndex],HIGH);
// // }else if(motorPwm>0){
// // digitalWrite(directionPin1[motorIndex],HIGH);
// // digitalWrite (directionPin2[motorIndex],LOW);
// // }
// // else{
// // digitalWrite(directionPin1[motorIndex],LOW);
// // digitalWrite (directionPin2[motorIndex],HIGH);
// // }
// //
// // analogWrite(pwmPin[motorIndex], abs((int)round(maxAnalogWrite*motorPwm)));
// // lastPwm[motorIndex]=motorPwm;
//}
//void setMotorPwms(float* motorPwms){
// int i;
// for(i = 0; i < 3; ++i){
// setMotorPwm(i, motorPwms[i]);
// }
//}
void stopMotors(void){
setLeftMotor(0);
setRightMotor(0);
}
//void initMotors(void){
// pinMode(pin_disable_motors,OUTPUT);
// digitalWrite(pin_disable_motors, LOW);
//
// pinMode(pin_in1_A1,OUTPUT);
// pinMode(pin_in2_A1,OUTPUT);
// pinMode(pin_statusFlag_A1,INPUT);
//
// pinMode(pin_in1_A2,OUTPUT);
// pinMode(pin_in2_A2,OUTPUT);
// pinMode(pin_statusFlag_A2,INPUT);
//
// pinMode(pin_in1_B1,OUTPUT);
// pinMode(pin_in2_B1,OUTPUT);
// pinMode(pin_statusFlag_B1,INPUT);
//
// pinMode(pin_in1_B2,OUTPUT);
// pinMode(pin_in2_B2,OUTPUT);
// pinMode(pin_statusFlag_B2,INPUT);
//
// analogWriteFrequency(pin_in1_A1, motorPwmFreq);//affects all pwm pins on the same timer
//
//
// stopMotors();
//}
//motor value is between 0 and 1 for vortex, -1 to 1 for drive motors
//void pwm_out_sendSignalsToMotors(){
// if(motor_right > 1) motor_right = 1;
// if(motor_right < 0) motor_right=0;
//
// motor_right_ticks = PWM_OUT_NORMALIZED_TO_TICKS(motor_right);
// PWM_OUT2_DUTY = motor_right_ticks;
//
// if(motor_left > 1) motor_left = 1;
// if(motor_left < 0) motor_left=0;
//
// motor_left_ticks = PWM_OUT_NORMALIZED_TO_TICKS(motor_left);
// PWM_OUT1_DUTY = motor_left_ticks;
//}
//INTERUPT:
//digitalWrite(tempPin,1);
//// FTM0_SC &= ~FTMx_CnSC_CHF; // clear channel 0 interrupt
// FTM0_SC &= ~FTM_SC_TOF;
//// for(volatile int j= 0; j < 3; j++);//mini delay
//
// currentmilliAmps = multiplier*analogRead(pin_feedbackA1);
// if (val < 0) currentmilliAmps = -currentmilliAmps;
// /*
// * 0.068V = 60
// * 0.734V = 620
// * lsb = 0.0012 V
// * offset = 0V
// *
// */
// // float currentmilliAmps = (4.53/(float)1023) * analogRead(pin_feedbackA1);
// // currentmilliAmps = 0.648*currentmilliAmps;
// // float p = 0.04;
// // float currentmilliAmpsError = 0.1 - currentmilliAmps;
// // float val = p*currentmilliAmpsError;
//
//
// // val = 0.5;
// // val = ref;
//
// int32_t currentmilliAmpsError = currentmilliAmpsRef - currentmilliAmps;
//// currentmilliAmpsIntergral += timeStepcurrentmilliAmpsControll*currentmilliAmpsError;
//// currentmilliAmpsIntergral += currentmilliAmpsError/motorPwmFreq;
// currentmilliAmpsIntergral += currentmilliAmpsError*pidI;
// int32_t integralMax = 1000*motorPwmFreq;
// if(currentmilliAmpsIntergral > integralMax) currentmilliAmpsIntergral = integralMax;
// if(currentmilliAmpsIntergral < -integralMax) currentmilliAmpsIntergral = -integralMax;
//
//
// val = (pidP*currentmilliAmpsError + currentmilliAmpsIntergral)/motorPwmFreq;
//
//
// setMotorPwm(0, val);
//// setMotorPwm(1, val);
//// setMotorPwm(2, val);
//// setMotorPwm(3, val);
//
// digitalWrite(tempPin,0);
<file_sep>#include "master_include.h"
void initLEDS(void){
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
CLEAR_LED();
}
int main(void) {
int i=0;
// SystemCoreClockUpdate(); //makes sure SystemCoreClock is set to the correct value
initLEDS(); //GPIOA
initTime(); // TIM2
initPwm_out(); //TIM8
init_adc(); //ADC1, ADC2, TIM4
initMotors();
initMPU9250(); //SPI2
// initUart(); //USART1
initLineSensor();
uint32_t start_tick = get_time_tics();
uint32_t control_period_ticks = 100000*CONTROL_LOOP_PERIOD; //500Hz control loop
// setLeftMotor(0);
// setRightMotor(0.3);
// while(1);
// SET_LED();
// delay_ms(200);
// CLEAR_LED();
// delay_ms(200);
while (1) {
SET_LED();
sleep_until_ticks(start_tick);
CLEAR_LED();
start_tick=get_time_tics()+ control_period_ticks;
mpu9250_read_all();
if(i > 30){
lineSensorCalibrate();
i = 0;
}else{
i++;
}
updateSensorReading();
// float derp = gyroscope_data[2];
// float temp = ADC_ValueAveraged[0];
float leftPwm = 0;
float rightPwm = 0;
float error = lineSensorValue/35.0f;
if (error >1) error = 1;
float forwardPwm = 0.9 - 0.7*fabs(error);
// leftPwm = forwardPwm -lineSensorValue/30.0f + gyroscope_data[2]/500.0f;
// rightPwm = forwardPwm + lineSensorValue/30.0f - gyroscope_data[2]/200.0f;
float referenceAngRate = lineSensorValue*18;
leftPwm = forwardPwm + (gyroscope_data[2]- referenceAngRate)/800.0f;
rightPwm = forwardPwm -(gyroscope_data[2]- referenceAngRate)/800.0f;
// if (lineSensorState==lostLineLeft){
// leftPwm = 0;
// rightPwm = -0.5;
// }
// if (lineSensorState==lostLineRight){
// leftPwm = -0.5;
// rightPwm = 0;
// }
setLeftMotor(leftPwm);
setRightMotor(rightPwm);
// uart_send_data();
}
}
<file_sep>/*
* vilseAdc.h
*
* Created on: 28 feb 2014
* Author: vilse
*/
#ifndef ADC_H_
#define ADC_H_
#include "master_include.h"
// Settings
#define ADC_CHANNEL_NUM 16
#define ADC_SAMPLING_FREQUENCY 10000
#define ADC_AVERAGE_FILTERCONSTANT 0.8
// Global variables
extern volatile uint16_t ADC_Value[ADC_CHANNEL_NUM];
extern volatile float ADC_ValueAveraged[ADC_CHANNEL_NUM];
// Functions
void init_adc(void);
void DMA2_Stream0_IRQHandler(void);
#endif /* ADC_H_ */
<file_sep>#ifndef MAIN_H
#define MAIN_H
#include "master_include.h"
volatile uint32_t state;
volatile uint32_t begun_backing_tick;
volatile float acc_filt[3];
volatile float acc_angle;
#endif //MAIN_H
<file_sep>/*
* vilseSensor.c
*
* Created on: 9 mar 2014
* Author: vilse
*/
#include "master_include.h"
sensorState lineSensorState = init;
float lineSensorValue = 0;
// the coordinate for each sensor in x-axis
int32_t sensorCoordinate[SENSOR_COUNT]= {-40, -25, -15, -5, 5, 15, 25, 40};
const int32_t orderInADC[SENSOR_COUNT]= {2, 3, 4, 5, 6, 7, 10, 11};
int32_t sensorMins[SENSOR_COUNT]= {4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000};
int32_t sensorMaxs[SENSOR_COUNT]= {0, 0, 0, 0, 0, 0, 0, 0,};
void initLineSensor(void){
CLEAR_LED();
delay_ms(100);
SET_LED();
delay_ms(100);
CLEAR_LED();
delay_ms(100);
SET_LED();
volatile int32_t finishedTick = get_time_tics() + ms_to_tics(3000);
while(get_time_tics()<finishedTick){
lineSensorCalibrate();
}
CLEAR_LED();
delay_ms(100);
}
void lineSensorCalibrate(void){
int i;
for(i=0; i<SENSOR_COUNT; i++){
if(lineSensorState== onLine){
sensorMaxs[i]-=1;
sensorMins[i]+=1;
}
float reading = getSensorReadingRaw(i);
if (reading >sensorMaxs[i]) sensorMaxs[i] = reading;
else if(reading < sensorMins[i]) sensorMins[i] = reading;
}
}
//uint16_t sortArrayIndexes(int n, float indexes[], float x[]){
// uint16_t temp;
// int i, j;
// // the following two loops sort the array x in ascending order
// for(i=0; i<n-1; i++) {
// for(j=i+1; j<n; j++) {
// if(x[j] < x[i]) {
// // swap elements
// temp = x[i];
// x[i] = x[j];
// x[j] = temp;
// }
// }
// }
// https://en.wikiversity.org/wiki/C_Source_Code/Find_the_median_and_mean
uint16_t median(int n, uint16_t x[]) {
uint16_t temp;
int i, j;
// the following two loops sort the array x in ascending order
for(i=0; i<n-1; i++) {
for(j=i+1; j<n; j++) {
if(x[j] < x[i]) {
// swap elements
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
//return the average of the elements in the middle
#define AVERAGE_SAMPLES 20
int start = n/2 - AVERAGE_SAMPLES/2;
int end = n/2 + AVERAGE_SAMPLES/2;
uint32_t average = 0;
for(i = start; i < end; i++) average += x[i];
average /= AVERAGE_SAMPLES;
return average;
}
void updateSensorReading(void){
int32_t y = 0;
float sensorSum = 0;
int i;
float sensorVal=0;
// float indexesSorted[SENSOR_COUNT];
float sensorMax = 0;
int maxIndex = 0;
float sensorSecondMax = 0;
int secondMaxIndex = 0;
for(i=0; i < SENSOR_COUNT; ++i){
sensorVal = getSensorReadingNormalized(i);//ADC_ValueAveraged[i] - sensorMins[i];
// sensorVal-= 0.1;
if (sensorVal < 0) sensorVal =0;
y += sensorCoordinate[i]*sensorVal;
sensorSum += sensorVal;
if(sensorVal>sensorMax){
sensorMax = sensorVal;
maxIndex = i;
}else if (sensorVal>sensorSecondMax){
sensorSecondMax = sensorVal;
secondMaxIndex = i;
}
}
if(sensorMax < BLACK_TRESHOLD){ // if no sensor sees black, it must be seeing only white= lost line
if(lineSensorValue < 0){
lineSensorState=lostLineLeft;
}else{
lineSensorState=lostLineRight;
}
}else if(sensorSum > SENSOR_COUNT * WHITE_TRESHOLD){//if the average is more than white
lineSensorState=inAir;
}else{
lineSensorState = onLine;
lineSensorValue = y/sensorSum;
// lineSensorValue = (sensorCoordinate[maxIndex]*sensorMax + sensorCoordinate[secondMaxIndex]*sensorSecondMax)/(sensorMax + sensorSecondMax);
}
}
|
2a7f975a2389c863ea98720e80d3ee908164dee0
|
[
"Markdown",
"C"
] | 19 |
C
|
mikaeltulldahl/lineFollowerV2
|
369e57d37178fa760bee2d1e05a3017ca4fe7281
|
b89998cde0cb8c997d6b4ae52974568394409e02
|
refs/heads/main
|
<repo_name>Eugene-36/go-it-js-hw-10<file_sep>/src/index.js
import css from "./css/styles.css";
import menu from "./data/menu.json";
import ref from "./js/refs.js";
import cardsTemplate from "../src/templates/post.hbs";
// Сделал шаблон
const newCard = cardsTemplate(menu);
const containerRef = document.querySelector(".menu");
containerRef.insertAdjacentHTML("afterbegin", newCard);
<file_sep>/src/js/refs.js
export default {
setMenu : document.querySelector('.menu')
};
const Theme = {
LIGHT: 'light-theme',
DARK: 'dark-theme',
};
//Add класс
const pressAddTheme = document.getElementById('theme-switch-toggle')
const bodyAccesse = document.querySelector('body')
pressAddTheme.addEventListener('click', addClass)
function addClass(e){
bodyAccesse.classList.toggle(Theme.DARK)
bodyAccesse.classList.toggle(Theme.LIGHT)
if(e.target.checked){
localStorage.setItem('theme', Theme.DARK)
}else{
localStorage.setItem('theme', Theme.LIGHT)
}
}
const refs = {
body: document.querySelector('body'),
switch: document.querySelector('.theme-switch__toggle'),
};
function setLocalStorage() {
if (localStorage.theme === Theme.DARK) {
bodyAccesse.classList.add(Theme.DARK);
pressAddTheme.checked = true;
}else {
bodyAccesse.classList.add(Theme.LIGHT);
}
}
setLocalStorage()
<file_sep>/src/js/menu.js
import recipe from "./data/menu.json";
// const { setMenu: menunNew } = recipe;
const newCard = cardsTemplate(menu);
|
5f2ad841d9688fb7c7f2d7824a3f700fa35e3463
|
[
"JavaScript"
] | 3 |
JavaScript
|
Eugene-36/go-it-js-hw-10
|
b16c3c2a77ddea09e9633a1efce3e2e7d707dc5b
|
cc573a6a359dcd71efe3d0fb5bea56dbecf256f4
|
refs/heads/master
|
<repo_name>Normmatt/GameYob<file_sep>/arm9/source/gameboy.cpp
#include <nds.h>
#include <stdlib.h>
#include <stdio.h>
#include "gameboy.h"
#include "gbcpu.h"
#include "gbgfx.h"
#include "gbsnd.h"
#include "mmu.h"
#include "timer.h"
#include "main.h"
#include "inputhelper.h"
int mode2Cycles, mode3Cycles;
int scanlineDrawn;
int scanlineCounter;
int doubleSpeed;
int madeInterrupt;
int quit;
int turbo;
int turboFrameSkip;
int frameskip;
int frameskipCounter;
bool fpsOutput=true;
bool timeOutput=true;
// ...what is phase? I think I made that up. Used for timing when the gameboy
// screen is off.
int phaseCounter;
int dividerCounter;
int timerCounter;
int timerPeriod;
long periods[4];
int cyclesToEvent;
int maxWaitCycles;
inline void setEventCycles(int cycles) {
if (cycles < cyclesToEvent) {
cyclesToEvent = cycles;
/*
if (cyclesToEvent <= 0) {
cyclesToEvent = 1;
}
*/
}
}
int updateInput() {
readKeys();
int retval = handleEvents(); // Input mostly
if (getTimerTicks() >= 1000)
{
int line=0;
if (fpsOutput) {
consoleClear();
printf("FPS: %d\n", fps);
line++;
}
fps = 0;
startTimer();
if (timeOutput) {
for (; line<23-1; line++)
printf("\n");
time_t rawTime = time(NULL);
char *timeString = ctime(&rawTime);
for (int i=0;; i++) {
if (timeString[i] == ':') {
timeString += i-2;
break;
}
}
char s[50];
strncpy(s, timeString, 50);
s[5] = '\0';
int spaces = 31-strlen(s);
for (int i=0; i<spaces; i++)
printf(" ");
printf("%s\n", s);
//tm *timeInfo = localTime(&rawTime);
}
}
return retval;
}
int totalCycles;
void runEmul()
{
for (;;)
{
totalCycles=0;
int cycles;
if (halt)
cycles = cyclesToEvent;
else
cycles = runOpcode(cyclesToEvent);
cycles += totalCycles;
cyclesToEvent = maxWaitCycles;
updateTimers(cycles);
updateSound(cycles);
updateLCD(cycles);
if (ime || halt)
handleInterrupts();
}
}
void initLCD()
{
// Pokemon Yellow hack: I need to intentionally SLOW DOWN emulation for
// Pikachu's pitch to sound right...
// The exact value of this will vary, so I'm going to leave it commented for
// now.
/*
if (strcmp(getRomTitle(), "POKEMON YELLOW") == 0)
maxWaitCycles = 100;
else
*/
maxWaitCycles = 400;
mode2Cycles = 456 - 80;
mode3Cycles = 456 - 172 - 80;
scanlineCounter = 456;
phaseCounter = 456*153;
timerCounter = 0;
dividerCounter = 256;
madeInterrupt = 0;
turboFrameSkip = 4;
turbo=0;
quit=0;
// Timer stuff
periods[0] = clockSpeed/4096;
periods[1] = clockSpeed/262144;
periods[2] = clockSpeed/65536;
periods[3] = clockSpeed/16384;
timerPeriod = periods[0];
}
bool screenOn = true;
void updateLCD(int cycles)
{
if (!(ioRam[0x40] & 0x80)) // If LCD is off
{
scanlineCounter = 456;
ioRam[0x44] = 0;
ioRam[0x41] &= 0xF8;
// Normally timing is synchronized with gameboy's vblank. If the screen
// is off, this code kicks in. The "phaseCounter" is a counter until the
// ds should check for input and whatnot.
phaseCounter -= cycles;
if (phaseCounter <= 0) {
swiIntrWait(interruptWaitMode, IRQ_VCOUNT);
updateTiles();
updateInput();
fps++;
phaseCounter += 456*153*(doubleSpeed?2:1);
if (screenOn) {
disableScreen();
screenOn = false;
}
return;
}
return;
}
u8 stat = ioRam[0x41];
int lcdState = stat&3;
scanlineCounter -= cycles;
switch(lcdState)
{
case 2:
{
if (scanlineCounter <= mode2Cycles) {
stat++;
setEventCycles(scanlineCounter-mode3Cycles);
}
else
setEventCycles(scanlineCounter-mode2Cycles);
}
break;
case 3:
{
if (scanlineCounter <= mode3Cycles) {
stat &= ~3;
if (stat&0x8)
{
requestInterrupt(LCD);
}
drawScanline(ioRam[0x44]);
if (updateHblankDMA()) {
// Extra 50 cycles aren't added when hblank dma is
// performed. I still need a good way to implement that.
}
setEventCycles(scanlineCounter);
}
else
setEventCycles(scanlineCounter-mode3Cycles);
}
break;
case 0:
{
// fall through to next case
}
case 1:
if (scanlineCounter <= 0)
{
scanlineCounter += 456*(doubleSpeed?2:1);
ioRam[0x44]++;
if (ioRam[0x44] < 144 || ioRam[0x44] >= 153) {
setEventCycles(scanlineCounter-mode2Cycles);
stat &= ~3;
stat |= 2;
if (stat&0x20)
{
requestInterrupt(LCD);
}
if (ioRam[0x44] >= 153)
{
ioRam[0x44] = 0;
}
}
else if (ioRam[0x44] == 144)
{
stat &= ~3;
stat |= 1;
requestInterrupt(VBLANK);
if (stat&0x10)
{
requestInterrupt(LCD);
}
fps++;
drawScreen();
if (!screenOn) {
enableScreen();
screenOn = true;
}
if (updateInput())
return;
}
if (ioRam[0x44] >= 144) {
setEventCycles(scanlineCounter);
}
// LYC check
if (ioRam[0x44] == ioRam[0x45])
{
stat |= 4;
if (stat&0x40)
requestInterrupt(LCD);
}
else
stat &= ~4;
}
else {
setEventCycles(scanlineCounter);
}
break;
}
ioRam[0x41] = stat;
return;
}
inline void updateTimers(int cycles)
{
if (ioRam[0x07] & 0x4)
{
timerCounter -= cycles;
if (timerCounter <= 0)
{
timerCounter = timerPeriod + timerCounter;
if ((++ioRam[0x05]) == 0)
{
requestInterrupt(TIMER);
ioRam[0x05] = ioRam[0x06];
}
}
setEventCycles(timerCounter);
}
dividerCounter -= cycles;
if (dividerCounter <= 0)
{
dividerCounter = 256+dividerCounter;
ioRam[0x04]++;
}
//setEventCycles(dividerCounter);
}
void requestInterrupt(int id)
{
ioRam[0x0F] |= id;
if (ioRam[0x0F] & ioRam[0xFF])
cyclesToExecute = 0;
}
<file_sep>/arm9/source/mmu.cpp
#include <stdio.h>
#include <cstdlib>
#include "mmu.h"
#include "gbcpu.h"
#include "gameboy.h"
#include "gbgfx.h"
#include "gbsnd.h"
#include "inputhelper.h"
#include "main.h"
#define refreshRomBank() { \
loadRomBank(); \
memory[0x4] = rom[currentRomBank]; \
memory[0x5] = rom[currentRomBank]+0x1000; \
memory[0x6] = rom[currentRomBank]+0x2000; \
memory[0x7] = rom[currentRomBank]+0x3000; }
#define refreshVramBank() { \
memory[0x8] = vram[vramBank]; \
memory[0x9] = vram[vramBank]+0x1000; }
#define refreshRamBank() { \
memory[0xa] = externRam[currentRamBank]; \
memory[0xb] = externRam[currentRamBank]+0x1000; }
#define refreshWramBank() { \
memory[0xd] = wram[wramBank]; }
int watchAddr=-1;
int readWatchAddr=-1;
int bankWatchAddr=-1;
clockStruct gbClock;
int numRomBanks=0;
int numRamBanks=0;
u8 bios[0x900];
bool biosExists = false;
bool biosEnabled = false;
bool biosOn = false;
u8* memory[0x10];
u8* rom[MAX_ROM_BANKS];
u8 vram[2][0x2000];
u8** externRam = NULL;
u8 wram[8][0x1000];
u8 hram[0x200];
u8* highram = hram-0xe00;
u8* ioRam = &hram[0x100];
u8 spriteData[0xA0];
int wramBank;
int vramBank;
int MBC;
int memoryModel;
bool hasClock=false;
int currentRomBank;
int currentRamBank;
u16 dmaSource;
u16 dmaDest;
u16 dmaLength;
int dmaMode;
extern int dmaLine;
void initMMU()
{
wramBank = 1;
vramBank = 0;
currentRomBank = 1;
currentRamBank = 0;
memoryModel = 1;
if (biosEnabled)
memory[0x0] = bios;
else
memory[0x0] = rom[0];
memory[0x1] = rom[0]+0x1000;
memory[0x2] = rom[0]+0x2000;
memory[0x3] = rom[0]+0x3000;
memory[0x4] = rom[currentRomBank];
memory[0x5] = rom[currentRomBank]+0x1000;
memory[0x6] = rom[currentRomBank]+0x2000;
memory[0x7] = rom[currentRomBank]+0x3000;
memory[0x8] = vram[vramBank];
memory[0x9] = vram[vramBank]+0x1000;
memory[0xa] = externRam[currentRamBank];
memory[0xb] = externRam[currentRamBank]+0x1000;
memory[0xc] = wram[0];
memory[0xd] = wram[wramBank];
memory[0xe] = wram[0];
memory[0xf] = highram;
}
void latchClock()
{
// +2h, the same as lameboy
time_t now = time(NULL)-120*60;
time_t difference = now - gbClock.clockLastTime;
int seconds = difference%60;
gbClock.clockSeconds += seconds;
if (gbClock.clockSeconds >= 60)
{
gbClock.clockMinutes++;
gbClock.clockSeconds -= 60;
}
difference /= 60;
int minutes = difference%60;
gbClock.clockMinutes += minutes;
if (gbClock.clockMinutes >= 60)
{
gbClock.clockHours++;
gbClock.clockMinutes -= 60;
}
difference /= 60;
gbClock.clockHours += difference%24;
if (gbClock.clockHours >= 24)
{
gbClock.clockDays++;
gbClock.clockHours -= 24;
}
difference /= 24;
gbClock.clockDays += difference;
if (gbClock.clockDays > 0x1FF)
{
gbClock.clockControl |= 0x80;
gbClock.clockDays -= 0x200;
}
gbClock.clockControl &= ~1;
gbClock.clockControl |= gbClock.clockDays>>8;
gbClock.clockLastTime = now;
gbClock.clockSecondsL = gbClock.clockSeconds;
gbClock.clockMinutesL = gbClock.clockMinutes;
gbClock.clockHoursL = gbClock.clockHours;
gbClock.clockDaysL = gbClock.clockDays;
gbClock.clockControlL = gbClock.clockControl;
}
void writeVram(u16 addr, u8 val) {
vram[vramBank][addr] = val;
if (addr < 0x1800) {
int tileNum = addr/16;
int scanline = ioRam[0x44];
if (scanline >= 128 && scanline < 144) {
if (!changedTileInFrame[vramBank][tileNum]) {
changedTileInFrame[vramBank][tileNum] = true;
changedTileInFrameQueue[changedTileInFrameQueueLength++] = tileNum|(vramBank<<9);
}
}
else {
if (!changedTile[vramBank][tileNum]) {
changedTile[vramBank][tileNum] = true;
changedTileQueue[changedTileQueueLength++] = tileNum|(vramBank<<9);
}
}
}
else {
int map = (addr-0x1800)/0x400;
if (map)
updateTileMap(map, addr-0x1c00, val);
else
updateTileMap(map, addr-0x1800, val);
}
}
void writeVram16(u16 dest, u16 src) {
for (int i=0; i<16; i++) {
vram[vramBank][dest++] = readMemory(src++);
}
dest -= 16;
src -= 16;
if (dest < 0x1800) {
int tileNum = dest/16;
if (ioRam[0x44] < 144) {
if (!changedTileInFrame[vramBank][tileNum]) {
changedTileInFrame[vramBank][tileNum] = true;
changedTileInFrameQueue[changedTileInFrameQueueLength++] = tileNum|(vramBank<<9);
}
}
else {
if (!changedTile[vramBank][tileNum]) {
changedTile[vramBank][tileNum] = true;
changedTileQueue[changedTileQueueLength++] = tileNum|(vramBank<<9);
}
}
}
else {
for (int i=0; i<16; i++) {
int addr = dest+i;
int map = (addr-0x1800)/0x400;
if (map)
updateTileMap(map, addr-0x1c00, vram[vramBank][src+i]);
else
updateTileMap(map, addr-0x1800, vram[vramBank][src+i]);
}
}
}
u8 readMemory(u16 addr)
{
switch (addr & 0xF000)
{
case 0x0000:
if (biosOn)
return bios[addr];
case 0x1000:
case 0x2000:
case 0x3000:
return rom[0][addr];
break;
case 0x4000:
case 0x5000:
case 0x6000:
case 0x7000:
return rom[currentRomBank][addr&0x3fff];
break;
case 0x8000:
case 0x9000:
return vram[vramBank][addr&0x1fff];
break;
case 0xA000:
// if (addr == 0xa080)
// return 1;
case 0xB000:
if (MBC == 3)
{
switch (currentRamBank)
{
case 0x8:
return gbClock.clockSecondsL;
case 0x9:
return gbClock.clockMinutesL;
case 0xA:
return gbClock.clockHoursL;
case 0xB:
return gbClock.clockDaysL&0xFF;
case 0xC:
return gbClock.clockControlL;
case 0:
case 1:
case 2:
case 3:
break;
default:
return 0;
}
}
return externRam[currentRamBank][addr&0x1fff];
break;
case 0xC000:
return wram[0][addr&0xFFF];
break;
case 0xD000:
return wram[wramBank][addr&0xFFF];
break;
case 0xE000:
return wram[0][addr&0xFFF];
break;
case 0xF000:
if (addr < 0xFE00)
return wram[wramBank][addr&0xFFF];
else
{
switch (addr)
{
case 0xFF00:
if (ioRam[0x00] & 0x20)
return (ioRam[0x00] & 0xF0) | ((buttonsPressed & 0xF0)>>4);
else
return (ioRam[0x00] & 0xF0) | (buttonsPressed & 0xF);
break;
case 0xFF26:
return ioRam[addr&0xff];
break;
case 0xFF69:
{
int index = ioRam[0x68] & 0x3F;
return bgPaletteData[index];
break;
}
case 0xFF6B:
{
int index = ioRam[0x6A] & 0x3F;
return sprPaletteData[index];
break;
}
case 0xFF6C:
case 0xFF72:
case 0xFF73:
case 0xFF74:
case 0xFF75:
case 0xFF76:
case 0xFF77:
return ioRam[addr&0xff];
break;
default:
return hram[addr&0x1ff];
}
}
break;
default:
//return memory[addr];
break;
}
return 0;
}
u16 readhword(u16 addr)
{
return (readMemory(addr))|(readMemory(addr+1)<<8);
}
void writeMemory(u16 addr, u8 val)
{
#ifndef DS
if (addr == watchAddr)
debugMode = 1;
#endif
switch (addr & 0xF000)
{
case 0x2000:
if (MBC == 5)
{
currentRomBank &= 0x100;
currentRomBank |= val;
if (currentRomBank >= numRomBanks)
{
currentRomBank = numRomBanks-1;
printLog("Game tried to access more rom than it has\n");
}
refreshRomBank();
return;
}
case 0x3000:
switch (MBC)
{
case 1:
currentRomBank &= 0xE0;
currentRomBank |= (val & 0x1F);
if (currentRomBank == 0)
currentRomBank = 1;
break;
case 3:
currentRomBank = (val & 0x7F);
if (currentRomBank == 0)
currentRomBank = 1;
break;
case 5:
currentRomBank &= 0xFF;
currentRomBank |= (val&1) << 8;
break;
default:
break;
}
if (currentRomBank >= numRomBanks)
{
currentRomBank = numRomBanks-1;
printLog("Game tried to access more rom than it has\n");
}
refreshRomBank();
return;
case 0x4000:
case 0x5000:
switch (MBC)
{
case 1:
if (memoryModel == 0)
{
currentRomBank &= 0x1F;
val &= 0xE0;
currentRomBank |= val;
if (currentRomBank == 0)
currentRomBank = 1;
if (currentRomBank >= numRomBanks)
{
currentRomBank = numRomBanks-1;
printLog("Game tried to access more rom than it has\n");
}
refreshRomBank();
}
else
{
currentRamBank = val & 0x3;
refreshRamBank();
}
break;
case 3:
case 5:
currentRamBank = val;
currentRamBank = val;
refreshRamBank();
break;
default:
break;
}
if (currentRamBank >= numRamBanks && MBC != 3)
{
if (numRamBanks == 0)
currentRamBank = 0;
else {
currentRamBank = numRamBanks-1;
printLog("Game tried to access more ram than it has\n");
refreshRamBank();
}
}
return;
case 0x6000:
case 0x7000:
if (MBC == 1)
{
memoryModel = val & 1;
}
else if (MBC == 3)
{
if (val == 1)
latchClock();
}
return;
case 0x8000:
case 0x9000:
writeVram(addr&0x1fff, val);
return;
case 0xA000:
case 0xB000:
if (MBC == 3)
{
switch (currentRamBank)
{
case 0x8:
gbClock.clockSeconds = val%60;
return;
case 0x9:
gbClock.clockMinutes = val%60;
return;
case 0xA:
gbClock.clockHours = val%24;
return;
case 0xB:
gbClock.clockDays &= 0x100;
gbClock.clockDays |= val;
return;
case 0xC:
gbClock.clockDays &= 0xFF;
gbClock.clockDays |= (val&1)<<8;
gbClock.clockControl = val;
return;
case 0:
case 1:
case 2:
case 3:
break;
default:
return;
}
}
externRam[currentRamBank][addr&0x1fff] = val;
return;
case 0xC000:
wram[0][addr&0xFFF] = val;
return;
case 0xD000:
wram[wramBank][addr&0xFFF] = val;
return;
case 0xE000:
return;
case 0xF000:
switch (addr)
{
case 0xFF04:
ioRam[0x04] = 0;
return;
case 0xFF05:
ioRam[0x05] = val;
break;
case 0xFF07:
timerPeriod = periods[val&0x3];
ioRam[0x07] = val;
break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
case 0xFF1A:
case 0xFF1B:
case 0xFF1C:
case 0xFF1D:
case 0xFF1E:
case 0xFF20:
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF30:
case 0xFF31:
case 0xFF32:
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
case 0xFF3B:
case 0xFF3C:
case 0xFF3D:
case 0xFF3E:
case 0xFF3F:
handleSoundRegister(addr, val);
return;
case 0xFF40: // LCDC
if ((val & 0x7F) != (ioRam[0x40] & 0x7F))
lineModified = true;
ioRam[0x40] = val;
return;
case 0xFF41:
ioRam[0x41] &= 0x7;
ioRam[0x41] |= val&0xF8;
return;
case 0xFF46: // DMA
{
u16 src = val << 8;
int i;
for (i=0; i<0xA0; i++) {
u8 val = readMemory(src+i);
hram[i] = val;
if (ioRam[0x44] >= 144 || ioRam[0x44] <= 1)
spriteData[i] = val;
}
totalCycles += 50;
dmaLine = ioRam[0x44];
//printLog("dma write %d\n", ioRam[0x44]);
return;
}
case 0xFF42:
case 0xFF43:
case 0xFF4B:
{
int dest = addr&0xff;
if (val != ioRam[dest]) {
ioRam[dest] = val;
lineModified = true;
}
}
break;
// winY
case 0xFF4A:
if (ioRam[0x44] >= 144 || val > ioRam[0x44])
winPosY = -1;
else {
// Signal that winPosY must be reset according to winY
winPosY = -2;
}
lineModified = true;
ioRam[0x4a] = val;
break;
case 0xFF44:
//ioRam[0x44] = 0;
return;
case 0xFF47: // BG Palette (GB classic only)
ioRam[0x47] = val;
if (gbMode == GB)
{
updateClassicBgPalette();
}
return;
case 0xFF48: // Spr Palette (GB classic only)
ioRam[0x48] = val;
if (gbMode == GB)
{
updateClassicSprPalette(0);
}
return;
case 0xFF49: // Spr Palette (GB classic only)
ioRam[0x49] = val;
if (gbMode == GB)
{
updateClassicSprPalette(1);
}
return;
case 0xFF68: // BG Palette Index (GBC only)
ioRam[0x68] = val;
return;
case 0xFF69: // BG Palette Data (GBC only)
{
int index = ioRam[0x68] & 0x3F;
bgPaletteData[index] = val;
if (index%8 == 7)
updateBgPalette(index/8);
if (ioRam[0x68] & 0x80)
ioRam[0x68]++;
return;
}
case 0xFF6B: // Sprite Palette Data (GBC only)
{
int index = ioRam[0x6A] & 0x3F;
sprPaletteData[index] = val;
if (index%8 == 7)
updateSprPalette(index/8);
if (ioRam[0x6A] & 0x80)
ioRam[0x6A]++;
return;
}
case 0xFF4D:
ioRam[0x4D] &= ~1;
ioRam[0x4D] |= (val&1);
return;
case 0xFF4F:
if (gbMode == CGB)
{
vramBank = val & 1;
refreshVramBank();
}
ioRam[0x4F] = val&1;
return;
// Special register, used by the gameboy bios
case 0xFF50:
biosOn = 0;
memory[0x0] = rom[0];
if (rom[0][0x143] == 0x80 || rom[0][0x143] == 0xC0)
gbMode = CGB;
else
gbMode = GB;
return;
case 0xFF55: // CGB DMA
if (gbMode == CGB)
{
if (dmaLength > 0)
{
if ((val&0x80) == 0)
{
ioRam[0x55] |= 0x80;
dmaLength = 0;
}
return;
}
int i;
dmaLength = ((val & 0x7F)+1);
int length = dmaLength*0x10;
int source = (ioRam[0x51]<<8) | (ioRam[0x52]);
source &= 0xFFF0;
int dest = (ioRam[0x53]<<8) | (ioRam[0x54]);
dest &= 0x1FF0;
dmaSource = source;
dmaDest = dest;
dmaMode = val&0x80;
ioRam[0x55] = dmaLength-1;
if (dmaMode == 0)
{
int i;
for (i=0; i<dmaLength; i++)
{
writeVram16(dest, source);
dest += 0x10;
source += 0x10;
}
totalCycles += dmaLength*8*(doubleSpeed+1);
dmaLength = 0;
ioRam[0x55] = 0xFF;
}
}
else
ioRam[0x55] = val;
return;
case 0xFF6C:
case 0xFF72:
case 0xFF73:
case 0xFF74:
case 0xFF75:
case 0xFF76:
case 0xFF77:
ioRam[addr&0xff] = val;
return;
case 0xFF70: // WRAM bank, for CGB only
if (gbMode == CGB)
{
wramBank = val & 0x7;
if (wramBank == 0)
wramBank = 1;
refreshWramBank();
}
ioRam[0x70] = val&0x7;
return;
case 0xFF0F:
ioRam[0x0f] = val;
if (val & ioRam[0xff])
cyclesToExecute = 0;
break;
case 0xFFFF:
ioRam[0xff] = val;
if (val & ioRam[0x0f])
cyclesToExecute = 0;
break;
default:
if (addr >= 0xfe00 && addr < 0xfea0) {
}
hram[addr&0x1ff] = val;
return;
}
return;
default:
return;
//memory[addr] = val;
}
}
void writehword(u16 addr, u16 val)
{
writeMemory(addr, val&0xFF);
writeMemory(addr+1, val>>8);
}
bool updateHblankDMA()
{
static int dmaCycles;
if (dmaLength > 0)
{
int i;
for (i=0; i<0x10; i++)
{
writeVram((dmaDest++)&0x1fff, readMemory(dmaSource++));
}
dmaLength --;
if (dmaLength == 0)
{
ioRam[0x55] = 0xFF;
}
else
ioRam[0x55] = dmaLength-1;
return true;
}
else
return false;
}
<file_sep>/arm9/include/console.h
#include <stdarg.h>
void initConsole();
void enterConsole();
void exitConsole();
bool isConsoleEnabled();
int displayConsole();
void addToLog(const char *format, va_list args);
<file_sep>/arm9/include/gbgfx.h
#pragma once
#include "global.h"
extern int scale;
extern bool changedTile[2][0x180];
extern int changedTileQueueLength;
extern u16 changedTileQueue[];
extern bool changedTileInFrame[2][0x180];
extern int changedTileInFrameQueueLength;
extern u16 changedTileInFrameQueue[];
extern u32 gbColors[4];
extern u8 bgPaletteData[0x40]; // The raw palette data, used by the gameboy
extern u8 sprPaletteData[0x40]; // The raw palette data, used by the gameboy
extern bool bgPaletteChanged[];
extern bool sprPaletteChanged[];
extern bool lineModified;
extern int winPosY;
extern int interruptWaitMode;
/*extern int tileAddr;
extern int BGMapAddr;
extern int winMapAddr;
extern int winOn;
extern int scale;*/
// Render scanline to pixels[]
void drawScanline(int scanline);
// Copy pixels[] to the screen
void drawScreen();
void initGFX();
void disableScreen();
void enableScreen();
void drawTile(int tile, int bank);
void drawBgTile(int tile, int bank);
void drawSprTile(int tile, int bank);
void updateTiles();
void updateTileMap(int map, int i, u8 val);
void updateLCDC(u8 val);
void updateHofs(u8 val);
void updateVofs(u8 val);
void updateSprPalette(int paletteid);
void updateBgPalette(int paletteid);
void updateClassicBgPalette();
void updateClassicSprPalette(int paletteid);
void drawClassicBgPalette(int val);
void drawClassicSprPalette(int paletteid, int val);
void drawBgPalette(int paletteid, int val);
void drawSprPalette(int paletteid, int val);
<file_sep>/arm9/source/gbgfx.cpp
#include <nds.h>
#include <stdio.h>
#include <math.h>
#include "gbgfx.h"
#include "mmu.h"
#include "gbcpu.h"
#include "main.h"
const int spr_priority = 2;
const int spr_priority_low = 3;
const int map_base[] = {28, 29};
const int blank_map_base[] = {30, 31};
const int overlay_map_base[] = {26,27};
const int off_map_base = 25;
const int win_blank_priority = 3;
const int win_priority = 2;
const int bg_blank_priority = 3;
const int bg_priority = 2;
const int bg_overlay_priority = 1;
const int win_overlay_priority = 1;
u16* map[2];
u16* blankMap[2];
u16* overlayMap[2];
u16* offMap;
u16 mapBuf[2][0x400];
u16 blankMapBuf[2][0x400];
u16 overlayMapBuf[2][0x400];
int screenOffsX = 48;
int screenOffsY = 24;
int colors[4];
int tileSize;
u16 pixels[256*144];
int tileSigned = 0;
int tileAddr = 0x8000;
int BGMapAddr = 0x9800;
int winMapAddr = 0x9800;
int BGOn = 1;
int winOn = 0;
int frameSkip = 2;
int frameSkipCnt;
// Frame counter. Incremented each vblank.
u8 frame=0;
bool changedTile[2][0x180];
int changedTileQueueLength=0;
u16 changedTileQueue[0x300];
bool changedTileInFrame[2][0x180];
int changedTileInFrameQueueLength=0;
u16 changedTileInFrameQueue[0x300];
bool bgPaletteModified[8];
bool spritePaletteModified[8];
u8 bgPaletteData[0x40];
u8 sprPaletteData[0x40];
int winPosY=0;
bool lineModified = false;
// Whether to wait for vblank if emulation is running behind schedule
int interruptWaitMode=0;
bool windowDisabled = false;
bool hblankDisabled = false;
int dmaLine;
void drawSprites();
typedef struct {
bool modified;
u8 hofs;
u8 vofs;
u8 winX;
u8 winY;
u8 winPosY;
u8 winOn;
u16 bgBlankCnt;
u16 bgCnt;
u16 bgOverlayCnt;
u16 winBlankCnt;
u16 winCnt;
u16 winOverlayCnt;
bool spritesOn;
bool map0;
bool tileSigned;
int spriteMaps[40];
} ScanlineStruct;
ScanlineStruct scanlineBuffers[2][144];
ScanlineStruct *drawingState = scanlineBuffers[0];
ScanlineStruct *renderingState = scanlineBuffers[1];
typedef struct
{
u16 attr0;
u16 attr1;
u16 attr2;
u16 affine_data;
} spriteEntry;
#define sprites ((spriteEntry*)OAM)
#define spriteEntries ((SpriteEntry*)OAM);
// The graphics are drawn with the DS's native hardware.
// Games tend to modify the graphics in the middle of being drawn.
// These changes are recorded and applied during DS hblank.
inline void drawLine(int gbLine) {
ScanlineStruct state = drawingState[gbLine];
if (state.spritesOn)
REG_DISPCNT |= DISPLAY_SPR_ACTIVE;
else
REG_DISPCNT &= ~DISPLAY_SPR_ACTIVE;
int hofs = state.hofs-screenOffsX;
int vofs = state.vofs-screenOffsY;
REG_BG3HOFS = hofs;
REG_BG3VOFS = vofs;
REG_BG3CNT = state.bgCnt;
REG_BG2CNT = state.bgBlankCnt;
REG_BG2HOFS = hofs;
REG_BG2VOFS = vofs;
if (!state.winOn || windowDisabled) {
REG_DISPCNT &= ~DISPLAY_WIN0_ON;
WIN_IN |= 1<<8;
WIN_IN &= ~4;
REG_BG0CNT = state.bgOverlayCnt;
REG_BG0HOFS = hofs;
REG_BG0VOFS = vofs;
}
else {
REG_DISPCNT |= DISPLAY_WIN0_ON;
WIN_IN &= ~(1<<8);
int winX = state.winX;
if (winX <= 7)
WIN0_X0 = screenOffsX;
else
WIN0_X0 = winX-7+screenOffsX;
WIN0_Y0 = state.winY+screenOffsY;
int whofs = -(winX-7)-screenOffsX;
int wvofs = -(gbLine-state.winPosY)-screenOffsY;
REG_BG0HOFS = whofs;
REG_BG0VOFS = wvofs;
REG_BG0CNT = state.winBlankCnt;
REG_BG1HOFS = whofs;
REG_BG1VOFS = wvofs;
REG_BG1CNT = state.winCnt;
// If window fills whole scanline, give it one of the background layers
// for "tile priority" (overlay).
if (winX <= 7) {
WIN_IN |= 4;
REG_BG2HOFS = whofs;
REG_BG2VOFS = wvofs;
REG_BG2CNT = state.winOverlayCnt;
}
}
}
void hblankHandler()
{
int line = REG_VCOUNT+1;
int gbLine = line-screenOffsY;
if (!(gbLine >= 0 && gbLine < 144))
return;
if (!drawingState[gbLine].modified)
return;
drawLine(gbLine);
}
void vblankHandler()
{
frame++;
}
void initGFX()
{
tileSize = 8;
vramSetBankA(VRAM_A_MAIN_BG);
vramSetBankB(VRAM_B_MAIN_BG);
vramSetBankE(VRAM_E_MAIN_SPRITE);
// Backdrop
BG_PALETTE[0] = RGB8(0,0,0);
map[0] = BG_MAP_RAM(map_base[0]);
map[1] = BG_MAP_RAM(map_base[1]);
blankMap[0] = BG_MAP_RAM(blank_map_base[0]);
blankMap[1] = BG_MAP_RAM(blank_map_base[1]);
overlayMap[0] = BG_MAP_RAM(overlay_map_base[0]);
overlayMap[1] = BG_MAP_RAM(overlay_map_base[1]);
offMap = BG_MAP_RAM(off_map_base);
// Tile for "Blank maps", which contain only the gameboy's color 0.
for (int i=0; i<16; i++) {
BG_GFX[i] = 1 | (1<<4) | (1<<8) | (1<<12);
}
// Initialize the "off map", for when the gameboy screen is disabled.
// Uses the "Blank map" tile because, why not.
for (int i=0; i<32*32; i++) {
offMap[i] = 8<<12;
}
// Off map palette
BG_PALETTE[8*16+1] = RGB8(255,255,255);
int i=0;
for (i=40; i<128; i++)
sprites[i].attr0 = ATTR0_DISABLED;
colors[0] = 255;
colors[1] = 192;
colors[2] = 94;
colors[3] = 0;
sprPaletteData[0] = 0xff;
sprPaletteData[1] = 0xff;
sprPaletteData[2] = 0x15|((0x15&7)<<5);
sprPaletteData[3] = (0x15>>3)|(0x15<<2);
sprPaletteData[4] = 0xa|((0xa&7)<<5);
sprPaletteData[5] = (0xa>>3)|(0xa<<2);
sprPaletteData[6] = 0;
sprPaletteData[7] = 0;
sprPaletteData[8] = 0xff;
sprPaletteData[9] = 0xff;
sprPaletteData[10] = 0x15|((0x15&7)<<5);
sprPaletteData[11] = (0x15>>3)|(0x15<<2);
sprPaletteData[12] = 0xa|((0xa&7)<<5);
sprPaletteData[13] = (0xa>>3)|(0xa<<2);
sprPaletteData[14] = 0;
sprPaletteData[15] = 0;
bgPaletteData[0] = 0xff;
bgPaletteData[1] = 0xff;
bgPaletteData[2] = 0x15|((0x15&7)<<5);
bgPaletteData[3] = (0x15>>3)|(0x15<<2);
bgPaletteData[4] = 0xa|((0xa&7)<<5);
bgPaletteData[5] = (0xa>>3)|(0xa<<2);
bgPaletteData[6] = 0;
bgPaletteData[7] = 0;
WIN_IN = (0x7) | (1<<4) | (0xc<<8) | (1<<12); // enable backgrounds and sprites
WIN_OUT = 0;
WIN1_X0 = screenOffsX;
WIN1_X1 = screenOffsX+160;
WIN1_Y0 = screenOffsY;
WIN1_Y1 = screenOffsY+144;
WIN0_X0 = screenOffsX;
WIN0_Y0 = screenOffsY;
WIN0_X1 = screenOffsX+160;
WIN0_Y1 = screenOffsY+144;
videoSetMode(MODE_0_2D | DISPLAY_BG0_ACTIVE | DISPLAY_BG1_ACTIVE | DISPLAY_BG2_ACTIVE | DISPLAY_BG3_ACTIVE | DISPLAY_WIN0_ON | DISPLAY_WIN1_ON | DISPLAY_SPR_ACTIVE | DISPLAY_SPR_1D);
REG_DISPSTAT &= 0xFF;
REG_DISPSTAT |= (144+screenOffsY)<<8;
irqEnable(IRQ_VCOUNT);
irqEnable(IRQ_HBLANK);
irqEnable(IRQ_VBLANK);
irqSet(IRQ_VBLANK, &vblankHandler);
irqSet(IRQ_HBLANK, &hblankHandler);
for (i=0; i<0x180; i++)
{
drawTile(i, 0);
drawTile(i, 1);
}
}
void disableScreen() {
videoBgDisable(0);
videoBgDisable(1);
REG_BG2CNT = BG_MAP_BASE(off_map_base);
videoBgDisable(3);
REG_DISPCNT &= ~(DISPLAY_SPR_ACTIVE | DISPLAY_WIN0_ON);
irqClear(IRQ_HBLANK);
}
void enableScreen() {
videoBgEnable(0);
videoBgEnable(1);
videoBgEnable(2);
videoBgEnable(3);
REG_DISPCNT |= DISPLAY_SPR_ACTIVE | DISPLAY_WIN0_ON;
if (!hblankDisabled) {
irqEnable(IRQ_HBLANK);
}
irqSet(IRQ_HBLANK, hblankHandler);
}
void updateTileMap(int m, int i, u8 val) {
int mapAddr = (m ? 0x1c00+i : 0x1800+i);
int tileNum = vram[0][mapAddr];
int bank=0;
int flipX = 0, flipY = 0;
int paletteid = 0;
int priority = 0;
if (gbMode == CGB)
{
flipX = !!(vram[1][mapAddr] & 0x20);
flipY = !!(vram[1][mapAddr] & 0x40);
bank = !!(vram[1][mapAddr] & 0x8);
paletteid = vram[1][mapAddr] & 0x7;
priority = !!(vram[1][mapAddr] & 0x80);
}
if (priority)
overlayMapBuf[m][i] = (tileNum+(bank*0x100)) | (paletteid<<12) | (flipX<<10) | (flipY<<11);
else {
overlayMapBuf[m][i] = 0x300;
}
mapBuf[m][i] = (tileNum+(bank*0x100)) | (paletteid<<12) | (flipX<<10) | (flipY<<11);
blankMapBuf[m][i] = paletteid<<12;
}
void drawTile(int tileNum, int bank) {
int x,y;
int index = (tileNum<<4)+(bank*0x100*16);
int signedIndex;
if (tileNum < 0x100)
signedIndex = (tileNum<<4)+(bank*0x100*16);
else
signedIndex = ((tileNum-0x100)<<4)+(bank*0x100*16);
bool unsign = tileNum < 0x100;
bool sign = tileNum >= 0x80;
for (y=0; y<8; y++) {
u8 b1=vram[bank][(tileNum<<4)+(y<<1)];
u8 b2=vram[bank][(tileNum<<4)+(y<<1)+1];
int bb[] = {0,0};
int sb[] = {0,0};
for (x=0; x<8; x++) {
int colorid;
colorid = !!(b1&0x80);
colorid |= !!(b2&0x80)<<1;
b1 <<= 1;
b2 <<= 1;
if (colorid != 0)
bb[x/4] |= ((colorid+1)<<((x%4)*4));
if (unsign)
sb[x/4] |= (colorid<<((x%4)*4));
}
if (unsign) {
BG_GFX[0x8000+index] = bb[0];
BG_GFX[0x8000+index+1] = bb[1];
SPRITE_GFX[index] = sb[0];
SPRITE_GFX[index+1] = sb[1];
}
if (sign) {
BG_GFX[0x10000+signedIndex] = bb[0];
BG_GFX[0x10000+signedIndex+1] = bb[1];
}
index += 2;
signedIndex += 2;
}
}
// Currently not actually used
void copyTile(u8 *src,u16 *dest) {
for (int y=0; y<8; y++) {
dest[y*2] = 0;
dest[y*2+1] = 0;
int index = y*2;
for (int x=0; x<8; x++) {
int colorid;
colorid = !!(src[index] & (0x80>>x));
colorid |= !!(src[index+1] & (0x80>>x))<<1;
int orValue = (colorid<<((x%4)*4));
dest[y*2+x/4] |= orValue;
}
}
}
void drawScreen()
{
DC_FlushRange(mapBuf[0], 0x400*2);
DC_FlushRange(mapBuf[1], 0x400*2);
DC_FlushRange(blankMapBuf[0], 0x400*2);
DC_FlushRange(blankMapBuf[1], 0x400*2);
DC_FlushRange(overlayMapBuf[0], 0x400*2);
DC_FlushRange(overlayMapBuf[1], 0x400*2);
swiIntrWait(interruptWaitMode, IRQ_VCOUNT);
dmaCopy(mapBuf[0], map[0], 0x400*2);
dmaCopy(mapBuf[1], map[1], 0x400*2);
dmaCopy(blankMapBuf[0], blankMap[0], 0x400*2);
dmaCopy(blankMapBuf[1], blankMap[1], 0x400*2);
dmaCopy(overlayMapBuf[0], overlayMap[0], 0x400*2);
dmaCopy(overlayMapBuf[1], overlayMap[1], 0x400*2);
int currentFrame = frame;
ScanlineStruct* tmp = renderingState;
renderingState = drawingState;
drawingState = tmp;
winPosY = -1;
/*
if (drawingState[0].spritesOn)
REG_DISPCNT |= DISPLAY_SPR_ACTIVE;
*/
// Check we're actually done drawing the screen.
if (REG_VCOUNT >= screenOffsY+144) {
REG_DISPCNT |= DISPLAY_SPR_ACTIVE;
}
// Palettes
for (int paletteid=0; paletteid<8; paletteid++) {
const int multiplier = 3;
if (spritePaletteModified[paletteid]) {
spritePaletteModified[paletteid] = false;
for (int i=0; i<4; i++) {
int id;
if (gbMode == GB)
id = (ioRam[0x48+paletteid]>>(i*2))&3;
else
id = i;
int red = (sprPaletteData[(paletteid*8)+(id*2)]&0x1F);
int green = (((sprPaletteData[(paletteid*8)+(id*2)]&0xE0) >> 5) |
((sprPaletteData[(paletteid*8)+(id*2)+1]) & 0x3) << 3);
int blue = ((sprPaletteData[(paletteid*8)+(id*2)+1] >> 2) & 0x1F);
SPRITE_PALETTE[((paletteid)*16)+i] = RGB8(red<<multiplier, green<<multiplier, blue<<multiplier);
}
}
if (bgPaletteModified[paletteid]) {
bgPaletteModified[paletteid] = false;
for (int i=0; i<4; i++) {
int id;
if (gbMode == GB)
id = (ioRam[0x47]>>(i*2))&3;
else
id = i;
int red = (bgPaletteData[(paletteid*8)+(id*2)]&0x1F);
int green = (((bgPaletteData[(paletteid*8)+(id*2)]&0xE0) >> 5) |
((bgPaletteData[(paletteid*8)+(id*2)+1]) & 0x3) << 3);
int blue = ((bgPaletteData[(paletteid*8)+(id*2)+1] >> 2) & 0x1F);
BG_PALETTE[((paletteid)*16)+i+1] = RGB8(red<<multiplier, green<<multiplier, blue<<multiplier);
}
}
}
updateTiles();
drawSprites();
if (interruptWaitMode == 1 && !(currentFrame+1 == frame && REG_VCOUNT >= 192) && (currentFrame != frame || REG_VCOUNT < 144+screenOffsY))
printLog("badv %d-%d, %d\n", currentFrame, frame, REG_VCOUNT);
}
void drawSprites() {
for (int i=0; i<40; i++)
{
int spriteNum = i*4;
if (spriteData[spriteNum] == 0)
sprites[i].attr0 = ATTR0_DISABLED;
else
{
int y = spriteData[spriteNum]-16;
int tall = !!(ioRam[0x40]&0x4);
int tileNum = spriteData[spriteNum+2];
if (tall)
tileNum &= ~1;
int x = (spriteData[spriteNum+1]-8)&0x1FF;
int bank = 0;
int flipX = !!(spriteData[spriteNum+3] & 0x20);
int flipY = !!(spriteData[spriteNum+3] & 0x40);
int priority = !!(spriteData[spriteNum+3] & 0x80);
int paletteid;
if (gbMode == CGB)
{
bank = !!(spriteData[spriteNum+3]&0x8);
paletteid = spriteData[spriteNum+3] & 0x7;
}
else
{
paletteid = !!(spriteData[spriteNum+3] & 0x10);
}
int priorityVal = (priority ? spr_priority_low : spr_priority);
sprites[i].attr0 = (y+screenOffsY) | (tall<<15);
sprites[i].attr1 = (x+screenOffsX) | (flipX<<12) | (flipY<<13);
sprites[i].attr2 = (tileNum+(bank*0x100)) | (priorityVal<<10) | (paletteid<<12);
}
}
for (int i=0; i<0xa0; i++)
spriteData[i] = hram[i];
}
void drawScanline(int scanline)
{
if (hblankDisabled || scanline >= 144)
return;
int winX = ioRam[0x4b];
if (winPosY == -2)
winPosY = ioRam[0x44]-ioRam[0x4a];
else if (winX < 167 && ioRam[0x4a] <= scanline)
winPosY++;
if (scanline == 0 || (scanline == 1 || (renderingState[scanline-1].modified && !renderingState[scanline-2].modified)) || scanline == ioRam[0x4a])
lineModified = true;
if (!lineModified) {
renderingState[scanline].modified = false;
return;
}
bool winOn = (ioRam[0x40] & 0x20) && winX < 167 && ioRam[0x4a] < 144 && ioRam[0x4a] <= scanline;
renderingState[scanline].modified = true;
lineModified = false;
renderingState[scanline].hofs = ioRam[0x43];
renderingState[scanline].vofs = ioRam[0x42];
renderingState[scanline].winX = winX;
renderingState[scanline].winPosY = winPosY;
renderingState[scanline].winY = ioRam[0x4a];
if (ioRam[0x40] & 0x10)
tileSigned = 0;
else
tileSigned = 1;
if (ioRam[0x40] & 0x40)
winMapAddr = 1;
else
winMapAddr = 0;
if (ioRam[0x40] & 0x8)
BGMapAddr = 1;
else
BGMapAddr = 0;
renderingState[scanline].winOn = winOn;
renderingState[scanline].spritesOn = ioRam[0x40] & 0x2;
int winMapBase = map_base[winMapAddr];
int bgMapBase = map_base[BGMapAddr];
renderingState[scanline].map0 = !BGMapAddr;
renderingState[scanline].tileSigned = tileSigned;
if (tileSigned) {
renderingState[scanline].winBlankCnt = (BG_MAP_BASE(blank_map_base[winMapAddr]) | BG_TILE_BASE(0) | win_blank_priority);
renderingState[scanline].winCnt = (BG_MAP_BASE(winMapBase) | BG_TILE_BASE(8) | win_priority);
renderingState[scanline].winOverlayCnt = (BG_MAP_BASE(overlay_map_base[winMapAddr]) | BG_TILE_BASE(8) | win_overlay_priority);
renderingState[scanline].bgBlankCnt = (BG_MAP_BASE(blank_map_base[BGMapAddr]) | BG_TILE_BASE(0) | bg_blank_priority);
renderingState[scanline].bgCnt = (BG_MAP_BASE(bgMapBase) | BG_TILE_BASE(8) | bg_priority);
renderingState[scanline].bgOverlayCnt = (BG_MAP_BASE(overlay_map_base[BGMapAddr]) | BG_TILE_BASE(8) | bg_overlay_priority);
}
else {
renderingState[scanline].winBlankCnt = (BG_MAP_BASE(blank_map_base[winMapAddr]) | BG_TILE_BASE(0) | win_blank_priority);
renderingState[scanline].winCnt = (BG_MAP_BASE(winMapBase) | BG_TILE_BASE(4) | win_priority);
renderingState[scanline].winOverlayCnt = (BG_MAP_BASE(overlay_map_base[winMapAddr]) | BG_TILE_BASE(4) | win_overlay_priority);
renderingState[scanline].bgBlankCnt = (BG_MAP_BASE(blank_map_base[BGMapAddr]) | BG_TILE_BASE(0) | bg_blank_priority);
renderingState[scanline].bgCnt = (BG_MAP_BASE(bgMapBase) | BG_TILE_BASE(4) | bg_priority);
renderingState[scanline].bgOverlayCnt = (BG_MAP_BASE(overlay_map_base[BGMapAddr]) | BG_TILE_BASE(4) | bg_overlay_priority);
}
return;
}
void updateTiles() {
while (changedTileQueueLength > 0) {
int val = changedTileQueue[--changedTileQueueLength];
int bank = val>>9,tile=val&0x1ff;
drawTile(tile, bank);
changedTile[bank][tile] = false;
}
// copy "changedTileInFrame" to "changedTile", where they'll be applied next
// frame.
while (changedTileInFrameQueueLength > 0) {
int val = changedTileInFrameQueue[--changedTileInFrameQueueLength];
int bank = val>>9, tile = val&0x1ff;
changedTileInFrame[bank][tile] = false;
changedTile[bank][tile] = true;
changedTileQueue[changedTileQueueLength++] = val;
}
}
void updateSprPalette(int paletteid)
{
spritePaletteModified[paletteid] = true;
}
void updateBgPalette(int paletteid)
{
bgPaletteModified[paletteid] = true;
}
void updateClassicBgPalette()
{
bgPaletteModified[0] = true;
}
void updateClassicSprPalette(int paletteid)
{
spritePaletteModified[paletteid] = true;
}
<file_sep>/arm9/source/console.cpp
#include <nds.h>
#include "console.h"
#include "inputhelper.h"
#include "gbsnd.h"
#include "main.h"
#include "gameboy.h"
#include "mmu.h"
const int screenTileWidth = 32;
bool consoleDebugOutput = false;
bool quitConsole = false;
bool consoleOn = false;
int displayConsoleRetval=0;
extern int interruptWaitMode;
extern bool advanceFrame;
extern bool windowDisabled;
extern bool hblankDisabled;
extern int frameskip;
extern int halt;
void selectRomFunc(int value) {
saveGame();
loadProgram(startFileChooser());
initializeGameboy();
quitConsole = true;
displayConsoleRetval = 1;
}
void setScreenFunc(int value) {
if (value)
lcdMainOnBottom();
else
lcdMainOnTop();
}
void buttonModeFunc(int value) {
if (value == 0) {
GB_KEY_A = KEY_A;
GB_KEY_B = KEY_B;
}
else {
GB_KEY_A = KEY_B;
GB_KEY_B = KEY_Y;
}
}
void consoleOutputFunc(int value) {
if (value == 0) {
fpsOutput = false;
timeOutput = false;
consoleDebugOutput = false;
}
else if (value == 1) {
fpsOutput = true;
timeOutput = false;
consoleDebugOutput = false;
}
else if (value == 2) {
fpsOutput = true;
timeOutput = true;
consoleDebugOutput = false;
}
else if (value == 3) {
fpsOutput = false;
timeOutput = false;
consoleDebugOutput = true;
}
}
void biosEnableFunc(int value) {
if (biosExists)
biosEnabled = value;
else
biosEnabled = 0;
}
void frameskipFunc(int value) {
frameskip = value;
}
void vblankWaitFunc(int value) {
interruptWaitMode = value;
}
void hblankEnableFunc(int value) {
hblankDisabled = !value;
if (value) {
irqEnable(IRQ_HBLANK);
}
else
irqDisable(IRQ_HBLANK);
}
void windowEnableFunc(int value) {
windowDisabled = !value;
if (windowDisabled)
REG_DISPCNT &= ~DISPLAY_WIN0_ON;
else
REG_DISPCNT |= DISPLAY_WIN0_ON;
}
void soundEnableFunc(int value) {
soundDisabled = !value;
soundDisable();
}
void advanceFrameFunc(int value) {
advanceFrame = true;
quitConsole = true;
}
void logViewFunc(int value) {
}
void resetFunc(int value) {
initializeGameboy();
quitConsole = true;
displayConsoleRetval = 1;
}
void returnFunc(int value) {
quitConsole = true;
}
void setChanEnabled(int chan, int value) {
if (value == 0)
disableChannel(chan);
else
enableChannel(chan);
}
void chan1Func(int value) {
setChanEnabled(0, value);
}
void chan2Func(int value) {
setChanEnabled(1, value);
}
void chan3Func(int value) {
setChanEnabled(2, value);
}
void chan4Func(int value) {
setChanEnabled(3, value);
}
struct ConsoleSubMenu {
char *name;
int numOptions;
int numSelections[10];
char *options[10];
char *optionValues[10][5];
void (*optionFunctions[10])(int);
int defaultOptionSelections[10];
int optionSelections[10];
};
ConsoleSubMenu menuList[] = {
{
"Options",
7,
{0,2,2,4,2,0,0},
{"Load ROM", "Game Screen", "A & B Buttons", "Console Output", "GBC Bios", "Reset", "Return to game"},
{{},{"Top","Bottom"},{"A/B", "B/Y"},{"Off","FPS","FPS+Time","Debug"},{"Off","On"},{},{}},
{selectRomFunc, setScreenFunc, buttonModeFunc, consoleOutputFunc, biosEnableFunc, resetFunc, returnFunc},
{0,0,0,2,1,0,0}
},
{
"Debug",
5,
{2,2,2,2,0},
{"Wait for Vblank", "Hblank", "Window", "Sound", "Advance Frame" },
{{"Off", "On"}, {"Off", "On"}, {"Off", "On"}, {"Off", "On"}, {}},
{vblankWaitFunc, hblankEnableFunc, windowEnableFunc, soundEnableFunc, advanceFrameFunc},
{0,1,1,1,0}
},
{
"Sound Channels",
4,
{2,2,2,2},
{"Channel 1", "Channel 2", "Channel 3", "Channel 4"},
{{"Off", "On"}, {"Off", "On"}, {"Off", "On"}, {"Off", "On"}},
{chan1Func, chan2Func, chan3Func, chan4Func},
{1,1,1,1}
}
};
int numMenus = sizeof(menuList)/sizeof(ConsoleSubMenu);
void initConsole() {
for (int i=0; i<numMenus; i++) {
for (int j=0; j<menuList[i].numOptions; j++) {
menuList[i].optionSelections[j] = menuList[i].defaultOptionSelections[j];
if (menuList[i].numSelections[j] != 0) {
menuList[i].optionFunctions[j](menuList[i].defaultOptionSelections[j]);
}
}
}
}
void enterConsole() {
if (!consoleOn)
advanceFrame = true;
}
void exitConsole() {
quitConsole = true;
}
bool isConsoleEnabled() {
return consoleOn;
}
int displayConsole() {
static int menu=0;
static int option = -1;
advanceFrame = 0;
displayConsoleRetval=0;
consoleOn = true;
quitConsole = false;
soundDisable();
while (!quitConsole) {
consoleClear();
int nameStart = (32-strlen(menuList[menu].name)-2)/2;
if (option == -1)
nameStart-=2;
for (int i=0; i<nameStart; i++)
printf(" ");
if (option == -1)
printf("* ");
printf("[");
printf(menuList[menu].name);
printf("]");
if (option == -1)
printf(" *");
printf("\n\n");
for (int i=0; i<menuList[menu].numOptions; i++) {
if (menuList[menu].numSelections[i] == 0) {
for (int j=0; j<(32-strlen(menuList[menu].options[i]))/2-2; j++)
printf(" ");
if (i == option)
printf("* %s *\n\n", menuList[menu].options[i]);
else
printf(" %s \n\n", menuList[menu].options[i]);
}
else {
for (int j=0; j<18-strlen(menuList[menu].options[i]); j++)
printf(" ");
printf("%s ", menuList[menu].options[i]);
if (i == option)
printf("* ");
else
printf(" ");
printf("%s", menuList[menu].optionValues[i][menuList[menu].optionSelections[i]]);
if (i == option)
printf(" *");
printf("\n\n");
}
}
// get input
while (!quitConsole) {
swiWaitForVBlank();
readKeys();
if (keyPressedAutoRepeat(KEY_UP)) {
option--;
if (option < -1)
option = menuList[menu].numOptions-1;
break;
}
else if (keyPressedAutoRepeat(KEY_DOWN)) {
option++;
if (option >= menuList[menu].numOptions)
option = -1;
break;
}
else if (keyPressedAutoRepeat(KEY_LEFT)) {
if (option == -1) {
menu--;
if (menu < 0)
menu = numMenus-1;
break;
}
else if (menuList[menu].optionValues[option][0] != 0) {
int selection = menuList[menu].optionSelections[option]-1;
if (selection < 0)
selection = menuList[menu].numSelections[option]-1;
menuList[menu].optionSelections[option] = selection;
menuList[menu].optionFunctions[option](selection);
break;
}
}
else if (keyPressedAutoRepeat(KEY_RIGHT)) {
if (option == -1) {
menu++;
if (menu >= numMenus)
menu = 0;
break;
}
else if (menuList[menu].optionValues[option][0] != 0) {
int selection = menuList[menu].optionSelections[option]+1;
if (selection >= menuList[menu].numSelections[option])
selection = 0;
menuList[menu].optionSelections[option] = selection;
menuList[menu].optionFunctions[option](selection);
break;
}
}
else if (keyPressedAutoRepeat(KEY_A)) {
if (option >= 0 && menuList[menu].numSelections[option] == 0) {
menuList[menu].optionFunctions[option](menuList[menu].optionSelections[option]);
forceReleaseKey(KEY_A);
break;
}
}
else if (keyJustPressed(KEY_B)) {
forceReleaseKey(KEY_B);
goto end;
}
else if (keyJustPressed(KEY_L)) {
menu--;
if (menu < 0)
menu = numMenus-1;
if (option >= menuList[menu].numOptions)
option = menuList[menu].numOptions-1;
break;
}
else if (keyJustPressed(KEY_R)) {
menu++;
if (menu >= numMenus)
menu = 0;
if (option >= menuList[menu].numOptions)
option = menuList[menu].numOptions-1;
break;
}
}
}
end:
if (!soundDisabled)
soundEnable();
consoleClear();
consoleOn = false;
return displayConsoleRetval;
}
void addToLog(const char *format, va_list args) {
if (consoleDebugOutput)
vprintf(format, args);
}
<file_sep>/arm9/source/inputhelper.cpp
#include <nds.h>
#include <fat.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include "inputhelper.h"
#include "mmu.h"
#include "gameboy.h"
#include "main.h"
#include "console.h"
FILE* romFile=NULL;
char filename[100];
char savename[100];
char romTitle[20];
int keysPressed=0;
int lastKeysPressed=0;
int keysForceReleased=0;
int repeatStartTimer=0;
int repeatTimer=0;
int GB_KEY_A, GB_KEY_B;
bool advanceFrame;
u8 romBankSlots[0x80][0x4000];
int bankSlotIDs[MAX_ROM_BANKS];
std::vector<int> lastBanksUsed;
void initInput()
{
fatInitDefault();
advanceFrame=false;
}
// File chooser variables
const int filesPerPage = 23;
const int MAX_FILENAME_LEN = 100;
int numFiles;
int scrollY=0;
int fileSelection=0;
void updateScrollDown() {
if (fileSelection >= numFiles)
fileSelection = numFiles-1;
if (fileSelection == numFiles-1 && numFiles > filesPerPage)
scrollY = fileSelection-filesPerPage+1;
else if (fileSelection-scrollY >= filesPerPage-1)
scrollY = fileSelection-filesPerPage+2;
}
void updateScrollUp() {
if (fileSelection < 0)
fileSelection = 0;
if (fileSelection == 0)
scrollY = 0;
else if (fileSelection == scrollY)
scrollY--;
else if (fileSelection < scrollY)
scrollY = fileSelection-1;
}
char* startFileChooser() {
char* retval;
char cwd[256];
getcwd(cwd, 256);
DIR* dp = opendir(cwd);
struct dirent *entry;
if (dp == NULL) {
printf("Error opening directory.\n");
return 0;
}
while (true) {
numFiles=0;
std::vector<char*> filenames;
std::vector<bool> directory;
while ((entry = readdir(dp)) != NULL) {
char* ext = strrchr(entry->d_name, '.')+1;
if (entry->d_type & DT_DIR || strcmpi(ext, "cgb") == 0 || strcmpi(ext, "gbc") == 0 || strcmpi(ext, "gb") == 0 || strcmpi(ext, "sgb") == 0) {
if (!(strcmp(".", entry->d_name) == 0)) {
directory.push_back(entry->d_type & DT_DIR);
char *name = (char*)malloc(sizeof(char)*256);
strcpy(name, entry->d_name);
filenames.push_back(name);
numFiles++;
}
}
}
// start sorting
for (int i=1; i<numFiles; i++) {
int j;
for (j=0; j<i; j++) {
if (strcmp(filenames[i], filenames[j]) <= 0) {
break;
}
}
char name[MAX_FILENAME_LEN];
strcpy(name, filenames[i]);
bool dir = directory[i];
for (int k=i; k>j; k--) {
strcpy(filenames[k], filenames[k-1]);
directory[k] = directory[k-1];
}
strcpy(filenames[j], name);
directory[j] = dir;
}
// sorting done
scrollY=0;
updateScrollDown();
bool readDirectory = false;
while (!readDirectory) {
consoleClear();
for (int i=scrollY; i<scrollY+filesPerPage && i<numFiles; i++) {
if (i == fileSelection)
printf("* ");
else if (i == scrollY && i != 0)
printf("^ ");
else if (i == scrollY+filesPerPage-1 && scrollY+filesPerPage-1 != numFiles-1)
printf("v ");
else
printf(" ");
char outBuffer[32];
int maxLen = 29;
if (directory[i])
maxLen--;
strncpy(outBuffer, filenames[i], maxLen);
outBuffer[maxLen] = '\0';
if (directory[i])
printf("%s/\n", outBuffer);
else
printf("%s\n", outBuffer);
}
while (true) {
swiWaitForVBlank();
readKeys();
if (keyJustPressed(KEY_A)) {
if (directory[fileSelection]) {
closedir(dp);
dp = opendir(filenames[fileSelection]);
chdir(filenames[fileSelection]);
readDirectory = true;
break;
}
else {
retval = filenames[fileSelection];
goto end;
}
}
else if (keyJustPressed(KEY_B)) {
if (numFiles >= 1 && strcmp(filenames[0], "..") == 0) {
closedir(dp);
dp = opendir("..");
chdir("..");
readDirectory = true;
break;
}
}
else if (keyPressedAutoRepeat(KEY_UP)) {
if (fileSelection > 0) {
fileSelection--;
updateScrollUp();
break;
}
}
else if (keyPressedAutoRepeat(KEY_DOWN)) {
if (fileSelection < numFiles-1) {
fileSelection++;
updateScrollDown();
break;
}
}
else if (keyJustPressed(KEY_RIGHT)) {
fileSelection += filesPerPage/2;
updateScrollDown();
break;
}
else if (keyJustPressed(KEY_LEFT)) {
fileSelection -= filesPerPage/2;
updateScrollUp();
break;
}
}
}
// free memory used for filenames
for (int i=0; i<numFiles; i++) {
free(filenames[i]);
}
fileSelection = 0;
}
end:
closedir(dp);
consoleClear();
return retval;
}
int loadProgram(char* f)
{
if (romFile != NULL)
fclose(romFile);
strcpy(filename, f);
romFile = fopen(filename, "rb");
if (romFile == NULL)
{
printLog("Error opening %s.\n", filename);
return 1;
}
// First calculate the size
fseek(romFile, 0, SEEK_END);
numRomBanks = ftell(romFile)/0x4000;
rewind(romFile);
for (int i=0; i<numRomBanks; i++) {
bankSlotIDs[i] = -1;
}
int banksToLoad = numRomBanks;
if (numRomBanks > 0x80)
banksToLoad = 0x80;
lastBanksUsed = std::vector<int>();
int i;
for (i=0; i<banksToLoad; i++)
{
rom[i] = romBankSlots[i];
bankSlotIDs[i] = i;
fread(rom[i], 1, 0x4000, romFile);
if (i != 0)
lastBanksUsed.push_back(i);
}
strcpy(savename, filename);
*(strrchr(savename, '.')) = '\0';
strcat(savename, ".sav");
for (int i=0; i<0xe; i++) {
romTitle[i] = (char)rom[0][i+0x134];
}
romTitle[0xe] = '\0';
loadSave();
// Little hack to preserve "quickread" from gbcpu.cpp.
if (biosEnabled) {
for (int i=0x100; i<0x150; i++)
bios[i] = rom[0][i];
}
return 0;
}
void loadRomBank() {
if (numRomBanks <= 0x80 || bankSlotIDs[currentRomBank] != -1)
return;
int bankToUnload = lastBanksUsed.back();
lastBanksUsed.pop_back();
int slot = bankSlotIDs[bankToUnload];
bankSlotIDs[bankToUnload] = -1;
bankSlotIDs[currentRomBank] = slot;
rom[currentRomBank] = romBankSlots[slot];
fseek(romFile, 0x4000*currentRomBank, SEEK_SET);
fread(rom[currentRomBank], 1, 0x4000, romFile);
lastBanksUsed.insert(lastBanksUsed.begin(), currentRomBank);
}
int loadSave()
{
// unload previous save
if (externRam != NULL) {
for (int i=0; i<numRamBanks; i++) {
free(externRam[i]);
}
free(externRam);
}
externRam = NULL;
// Get the game's external memory size and allocate the memory
numRamBanks = readMemory(0x149);
switch(numRamBanks)
{
case 0:
numRamBanks = 0;
break;
case 1:
case 2:
numRamBanks = 1;
break;
case 3:
numRamBanks = 4;
break;
case 4:
numRamBanks = 16;
break;
default:
printLog("Invalid RAM bank number: %d\nDefaulting to 4 banks\n", numRamBanks);
numRamBanks = 4;
break;
}
if (numRamBanks == 0)
return 0;
externRam = (u8**)malloc(numRamBanks*sizeof(u8*));
int i;
for (i=0; i<numRamBanks; i++)
{
externRam[i] = (u8*)malloc(0x2000*sizeof(u8));
}
// Now load the data.
FILE* file;
file = fopen(savename, "r");
if (file != NULL)
{
for (i=0; i<numRamBanks; i++)
fread(externRam[i], 1, 0x2000, file);
u8 mapper = readMemory(0x147);
if (mapper == 0x10 || mapper == 0x12 || mapper == 0x13)
{
fread(&gbClock.clockSeconds, 1, sizeof(int)*10+sizeof(time_t), file);
}
fclose(file);
}
else
{
printLog("Couldn't open file \"%s\".\n", savename);
return 1;
}
return 0;
}
int saveGame()
{
if (numRamBanks == 0)
return 0;
FILE* file;
file = fopen(savename, "w");
if (file != NULL)
{
int i;
for (i=0; i<numRamBanks; i++)
fwrite(externRam[i], 1, 0x2000, file);
if (MBC == 3)
{
fwrite(&gbClock.clockSeconds, 1, sizeof(int)*10+sizeof(time_t), file);
}
fclose(file);
}
else
{
fprintf(stderr, "Error saving to file.\n");
return 1;
}
return 0;
}
bool keyPressed(int key) {
return keysPressed&key;
}
bool keyPressedAutoRepeat(int key) {
if (keyJustPressed(key)) {
repeatStartTimer = 14;
return true;
}
if (keyPressed(key) && repeatStartTimer == 0 && repeatTimer == 0) {
repeatTimer = 2;
return true;
}
return false;
}
bool keyJustPressed(int key) {
return ((keysPressed^lastKeysPressed)&keysPressed) & key;
}
void readKeys() {
scanKeys();
lastKeysPressed = keysPressed;
keysPressed = keysHeld();
for (int i=0; i<16; i++) {
if (keysForceReleased & (1<<i)) {
if (!(keysPressed & (1<<i)))
keysForceReleased &= ~(1<<i);
}
}
keysPressed &= ~keysForceReleased;
if (repeatStartTimer > 0)
repeatStartTimer--;
if (repeatTimer > 0)
repeatTimer--;
}
void forceReleaseKey(int key) {
keysForceReleased |= key;
keysPressed &= ~key;
}
char* getRomTitle() {
return romTitle;
}
int handleEvents()
{
int keys = keysPressed;
if (keys & KEY_UP)
{
buttonsPressed &= (0xFF ^ UP);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= UP;
}
if (keys & KEY_DOWN)
{
buttonsPressed &= (0xFF ^ DOWN);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= DOWN;
}
if (keys & KEY_LEFT)
{
buttonsPressed &= (0xFF ^ LEFT);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= LEFT;
}
if (keys & KEY_RIGHT)
{
buttonsPressed &= (0xFF ^ RIGHT);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= RIGHT;
}
if (keys & GB_KEY_A)
{
buttonsPressed &= (0xFF ^ BUTTONA);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= BUTTONA;
}
if (keys & GB_KEY_B)
{
buttonsPressed &= (0xFF ^ BUTTONB);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= BUTTONB;
}
if (keys & KEY_START)
{
buttonsPressed &= (0xFF ^ START);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= START;
}
if (keys & KEY_SELECT)
{
buttonsPressed &= (0xFF ^ SELECT);
requestInterrupt(JOYPAD);
}
else
{
buttonsPressed |= SELECT;
}
if (keyJustPressed(KEY_X))
saveGame();
if (advanceFrame || keyJustPressed(KEY_R)) {
advanceFrame = 0;
return displayConsole();
}
return 0;
}
<file_sep>/arm9/include/opcodetimings.h
// TODO: Use brace initialization instead?
opCycles[0x06]=8;
opCycles[0x0e]=8;
opCycles[0x16]=8;
opCycles[0x1e]=8;
opCycles[0x26]=8;
opCycles[0x2e]=8;
opCycles[0x7f]=4;
opCycles[0x78]=4;
opCycles[0x79]=4;
opCycles[0x7a]=4;
opCycles[0x7b]=4;
opCycles[0x7c]=4;
opCycles[0x7d]=4;
opCycles[0x7e]=8;
opCycles[0x40]=4;
opCycles[0x41]=4;
opCycles[0x42]=4;
opCycles[0x43]=4;
opCycles[0x44]=4;
opCycles[0x45]=4;
opCycles[0x46]=8;
opCycles[0x48]=4;
opCycles[0x49]=4;
opCycles[0x4a]=4;
opCycles[0x4b]=4;
opCycles[0x4c]=4;
opCycles[0x4d]=4;
opCycles[0x4e]=8;
opCycles[0x50]=4;
opCycles[0x51]=4;
opCycles[0x52]=4;
opCycles[0x53]=4;
opCycles[0x54]=4;
opCycles[0x55]=4;
opCycles[0x56]=8;
opCycles[0x58]=4;
opCycles[0x59]=4;
opCycles[0x58]=4;
opCycles[0x59]=4;
opCycles[0x5a]=4;
opCycles[0x5b]=4;
opCycles[0x5c]=4;
opCycles[0x5d]=4;
opCycles[0x5e]=8;
opCycles[0x60]=4;
opCycles[0x61]=4;
opCycles[0x62]=4;
opCycles[0x63]=4;
opCycles[0x64]=4;
opCycles[0x65]=4;
opCycles[0x66]=8;
opCycles[0x68]=4;
opCycles[0x69]=4;
opCycles[0x6a]=4;
opCycles[0x6b]=4;
opCycles[0x6c]=4;
opCycles[0x6d]=4;
opCycles[0x6e]=8;
opCycles[0x70]=8;
opCycles[0x71]=8;
opCycles[0x72]=8;
opCycles[0x73]=8;
opCycles[0x74]=8;
opCycles[0x75]=8;
opCycles[0x36]=12;
opCycles[0x0a]=8;
opCycles[0x1a]=8;
opCycles[0xfa]=16;
opCycles[0x3e]=8;
opCycles[0x47]=4;
opCycles[0x4f]=4;
opCycles[0x57]=4;
opCycles[0x5f]=4;
opCycles[0x67]=4;
opCycles[0x6f]=4;
opCycles[0x02]=8;
opCycles[0x12]=8;
opCycles[0x77]=8;
opCycles[0xea]=16;
opCycles[0xf2]=8;
opCycles[0xe2]=8;
opCycles[0x3a]=8;
opCycles[0x32]=8;
opCycles[0x2a]=8;
opCycles[0x22]=8;
opCycles[0xe0]=12;
opCycles[0xf0]=12;
opCycles[0x01]=12;
opCycles[0x11]=12;
opCycles[0x21]=12;
opCycles[0x31]=12;
opCycles[0xf9]=8;
opCycles[0xf8]=12;
opCycles[0x08]=20;
opCycles[0xf5]=16;
opCycles[0xc5]=16;
opCycles[0xd5]=16;
opCycles[0xe5]=16;
opCycles[0xf1]=12;
opCycles[0xc1]=12;
opCycles[0xd1]=12;
opCycles[0xe1]=12;
opCycles[0x87]=4;
opCycles[0x80]=4;
opCycles[0x81]=4;
opCycles[0x82]=4;
opCycles[0x83]=4;
opCycles[0x84]=4;
opCycles[0x85]=4;
opCycles[0x86]=8;
opCycles[0xc6]=8;
opCycles[0x8f]=4;
opCycles[0x88]=4;
opCycles[0x89]=4;
opCycles[0x8a]=4;
opCycles[0x8b]=4;
opCycles[0x8c]=4;
opCycles[0x8d]=4;
opCycles[0x8e]=8;
opCycles[0xce]=8;
opCycles[0x97]=4;
opCycles[0x90]=4;
opCycles[0x91]=4;
opCycles[0x92]=4;
opCycles[0x93]=4;
opCycles[0x94]=4;
opCycles[0x95]=4;
opCycles[0x96]=8;
opCycles[0xd6]=8;
opCycles[0x9f]=4;
opCycles[0x98]=4;
opCycles[0x99]=4;
opCycles[0x9a]=4;
opCycles[0x9b]=4;
opCycles[0x9c]=4;
opCycles[0x9d]=4;
opCycles[0x9e]=8;
opCycles[0xde]=8;
opCycles[0xa7]=4;
opCycles[0xa0]=4;
opCycles[0xa1]=4;
opCycles[0xa2]=4;
opCycles[0xa3]=4;
opCycles[0xa4]=4;
opCycles[0xa5]=4;
opCycles[0xa6]=8;
opCycles[0xe6]=8;
opCycles[0xb7]=4;
opCycles[0xb0]=4;
opCycles[0xb1]=4;
opCycles[0xb2]=4;
opCycles[0xb3]=4;
opCycles[0xb4]=4;
opCycles[0xb5]=4;
opCycles[0xb6]=8;
opCycles[0xf6]=8;
opCycles[0xaf]=4;
opCycles[0xa8]=4;
opCycles[0xa9]=4;
opCycles[0xaa]=4;
opCycles[0xab]=4;
opCycles[0xac]=4;
opCycles[0xad]=4;
opCycles[0xae]=8;
opCycles[0xee]=8;
opCycles[0xbf]=4;
opCycles[0xb8]=4;
opCycles[0xb9]=4;
opCycles[0xba]=4;
opCycles[0xbb]=4;
opCycles[0xbc]=4;
opCycles[0xbd]=4;
opCycles[0xbe]=8;
opCycles[0xfe]=8;
opCycles[0x3c]=4;
opCycles[0x04]=4;
opCycles[0x0c]=4;
opCycles[0x14]=4;
opCycles[0x1c]=4;
opCycles[0x24]=4;
opCycles[0x2c]=4;
opCycles[0x34]=12;
opCycles[0x3d]=4;
opCycles[0x05]=4;
opCycles[0x0d]=4;
opCycles[0x15]=4;
opCycles[0x1d]=4;
opCycles[0x25]=4;
opCycles[0x2d]=4;
opCycles[0x35]=12;
opCycles[0x09]=8;
opCycles[0x19]=8;
opCycles[0x29]=8;
opCycles[0x39]=8;
opCycles[0xe8]=16;
opCycles[0x03]=8;
opCycles[0x13]=8;
opCycles[0x23]=8;
opCycles[0x33]=8;
opCycles[0x0b]=8;
opCycles[0x1b]=8;
opCycles[0x2b]=8;
opCycles[0x3b]=8;
opCycles[0x27]=4;
opCycles[0x2f]=4;
opCycles[0x3f]=4;
opCycles[0x37]=4;
opCycles[0x00]=4;
opCycles[0x76]=4;
opCycles[0x10]=4;
opCycles[0xf3]=4;
opCycles[0xfb]=4;
opCycles[0x07]=4;
opCycles[0x17]=4;
opCycles[0x0f]=4;
opCycles[0x1f]=4;
opCycles[0xc3]=16;
opCycles[0xc2]=16;
opCycles[0xca]=16;
opCycles[0xd2]=16;
opCycles[0xda]=16;
opCycles[0xe9]=4;
opCycles[0x18]=12;
opCycles[0x20]=12;
opCycles[0x28]=12;
opCycles[0x30]=12;
opCycles[0x38]=12;
opCycles[0xcd]=24;
opCycles[0xc4]=24;
opCycles[0xcc]=24;
opCycles[0xd4]=24;
opCycles[0xdc]=24;
opCycles[0xc7]=16;
opCycles[0xcf]=16;
opCycles[0xd7]=16;
opCycles[0xdf]=16;
opCycles[0xe7]=16;
opCycles[0xef]=16;
opCycles[0xf7]=16;
opCycles[0xff]=16;
opCycles[0xc9]=16;
opCycles[0xc0]=16;
opCycles[0xc8]=16;
opCycles[0xd0]=16;
opCycles[0xd8]=16;
opCycles[0xd9]=16;
opCycles[0xcb]=0;
// 08
CBopCycles[0x37]=8;
CBopCycles[0x30]=8;
CBopCycles[0x31]=8;
CBopCycles[0x32]=8;
CBopCycles[0x33]=8;
CBopCycles[0x34]=8;
CBopCycles[0x35]=8;
CBopCycles[0x36]=16;
CBopCycles[0x07]=8;
CBopCycles[0x00]=8;
CBopCycles[0x01]=8;
CBopCycles[0x02]=8;
CBopCycles[0x03]=8;
CBopCycles[0x04]=8;
CBopCycles[0x05]=8;
CBopCycles[0x06]=16;
CBopCycles[0x17]=8;
CBopCycles[0x10]=8;
CBopCycles[0x11]=8;
CBopCycles[0x12]=8;
CBopCycles[0x13]=8;
CBopCycles[0x14]=8;
CBopCycles[0x15]=8;
CBopCycles[0x16]=16;
CBopCycles[0x0f]=8;
CBopCycles[0x08]=8;
CBopCycles[0x09]=8;
CBopCycles[0x0a]=8;
CBopCycles[0x0b]=8;
CBopCycles[0x0c]=8;
CBopCycles[0x0d]=8;
CBopCycles[0x0e]=16;
CBopCycles[0x1f]=8;
CBopCycles[0x18]=8;
CBopCycles[0x19]=8;
CBopCycles[0x1a]=8;
CBopCycles[0x1b]=8;
CBopCycles[0x1c]=8;
CBopCycles[0x1d]=8;
CBopCycles[0x1e]=16;
CBopCycles[0x27]=8;
CBopCycles[0x20]=8;
CBopCycles[0x21]=8;
CBopCycles[0x22]=8;
CBopCycles[0x23]=8;
CBopCycles[0x24]=8;
CBopCycles[0x25]=8;
CBopCycles[0x26]=16;
CBopCycles[0x2f]=8;
CBopCycles[0x28]=8;
CBopCycles[0x29]=8;
CBopCycles[0x2a]=8;
CBopCycles[0x2b]=8;
CBopCycles[0x2c]=8;
CBopCycles[0x2d]=8;
CBopCycles[0x2e]=16;
CBopCycles[0x3f]=8;
CBopCycles[0x38]=8;
CBopCycles[0x39]=8;
CBopCycles[0x3a]=8;
CBopCycles[0x3b]=8;
CBopCycles[0x3c]=8;
CBopCycles[0x3d]=8;
CBopCycles[0x3e]=16;
CBopCycles[0x40]=8;
CBopCycles[0x41]=8;
CBopCycles[0x42]=8;
CBopCycles[0x43]=8;
CBopCycles[0x44]=8;
CBopCycles[0x45]=8;
CBopCycles[0x46]=12;
CBopCycles[0x47]=8;
CBopCycles[0x48]=8;
CBopCycles[0x49]=8;
CBopCycles[0x4a]=8;
CBopCycles[0x4b]=8;
CBopCycles[0x4c]=8;
CBopCycles[0x4d]=8;
CBopCycles[0x4e]=12;
CBopCycles[0x4f]=8;
CBopCycles[0x50]=8;
CBopCycles[0x51]=8;
CBopCycles[0x52]=8;
CBopCycles[0x53]=8;
CBopCycles[0x54]=8;
CBopCycles[0x55]=8;
CBopCycles[0x56]=12;
CBopCycles[0x57]=8;
CBopCycles[0x58]=8;
CBopCycles[0x59]=8;
CBopCycles[0x5a]=8;
CBopCycles[0x5b]=8;
CBopCycles[0x5c]=8;
CBopCycles[0x5d]=8;
CBopCycles[0x5e]=12;
CBopCycles[0x5f]=8;
CBopCycles[0x60]=8;
CBopCycles[0x61]=8;
CBopCycles[0x62]=8;
CBopCycles[0x63]=8;
CBopCycles[0x64]=8;
CBopCycles[0x65]=8;
CBopCycles[0x66]=12;
CBopCycles[0x67]=8;
CBopCycles[0x68]=8;
CBopCycles[0x69]=8;
CBopCycles[0x6a]=8;
CBopCycles[0x6b]=8;
CBopCycles[0x6c]=8;
CBopCycles[0x6d]=8;
CBopCycles[0x6e]=12;
CBopCycles[0x6f]=8;
CBopCycles[0x70]=8;
CBopCycles[0x71]=8;
CBopCycles[0x72]=8;
CBopCycles[0x73]=8;
CBopCycles[0x74]=8;
CBopCycles[0x75]=8;
CBopCycles[0x76]=12;
CBopCycles[0x77]=8;
CBopCycles[0x78]=8;
CBopCycles[0x79]=8;
CBopCycles[0x7a]=8;
CBopCycles[0x7b]=8;
CBopCycles[0x7c]=8;
CBopCycles[0x7d]=8;
CBopCycles[0x7e]=12;
CBopCycles[0x7f]=8;
CBopCycles[0xc0]=8;
CBopCycles[0xc1]=8;
CBopCycles[0xc2]=8;
CBopCycles[0xc3]=8;
CBopCycles[0xc4]=8;
CBopCycles[0xc5]=8;
CBopCycles[0xc6]=16;
CBopCycles[0xc7]=8;
CBopCycles[0xc8]=8;
CBopCycles[0xc9]=8;
CBopCycles[0xca]=8;
CBopCycles[0xcb]=8;
CBopCycles[0xcc]=8;
CBopCycles[0xcd]=8;
CBopCycles[0xce]=16;
CBopCycles[0xcf]=8;
CBopCycles[0xd0]=8;
CBopCycles[0xd1]=8;
CBopCycles[0xd2]=8;
CBopCycles[0xd3]=8;
CBopCycles[0xd4]=8;
CBopCycles[0xd5]=8;
CBopCycles[0xd6]=16;
CBopCycles[0xd7]=8;
CBopCycles[0xd8]=8;
CBopCycles[0xd9]=8;
CBopCycles[0xda]=8;
CBopCycles[0xdb]=8;
CBopCycles[0xdc]=8;
CBopCycles[0xdd]=8;
CBopCycles[0xde]=16;
CBopCycles[0xdf]=8;
CBopCycles[0xe0]=8;
CBopCycles[0xe1]=8;
CBopCycles[0xe2]=8;
CBopCycles[0xe3]=8;
CBopCycles[0xe4]=8;
CBopCycles[0xe5]=8;
CBopCycles[0xe6]=16;
CBopCycles[0xe7]=8;
CBopCycles[0xe8]=8;
CBopCycles[0xe9]=8;
CBopCycles[0xea]=8;
CBopCycles[0xeb]=8;
CBopCycles[0xec]=8;
CBopCycles[0xed]=8;
CBopCycles[0xee]=16;
CBopCycles[0xef]=8;
CBopCycles[0xf0]=8;
CBopCycles[0xf1]=8;
CBopCycles[0xf2]=8;
CBopCycles[0xf3]=8;
CBopCycles[0xf4]=8;
CBopCycles[0xf5]=8;
CBopCycles[0xf6]=16;
CBopCycles[0xf7]=8;
CBopCycles[0xf8]=8;
CBopCycles[0xf9]=8;
CBopCycles[0xfa]=8;
CBopCycles[0xfb]=8;
CBopCycles[0xfc]=8;
CBopCycles[0xfd]=8;
CBopCycles[0xfe]=16;
CBopCycles[0xff]=8;
CBopCycles[0x80]=8;
CBopCycles[0x81]=8;
CBopCycles[0x82]=8;
CBopCycles[0x83]=8;
CBopCycles[0x84]=8;
CBopCycles[0x85]=8;
CBopCycles[0x86]=16;
CBopCycles[0x87]=8;
CBopCycles[0x88]=8;
CBopCycles[0x89]=8;
CBopCycles[0x8a]=8;
CBopCycles[0x8b]=8;
CBopCycles[0x8c]=8;
CBopCycles[0x8d]=8;
CBopCycles[0x8e]=16;
CBopCycles[0x8f]=8;
CBopCycles[0x90]=8;
CBopCycles[0x91]=8;
CBopCycles[0x92]=8;
CBopCycles[0x93]=8;
CBopCycles[0x94]=8;
CBopCycles[0x95]=8;
CBopCycles[0x96]=16;
CBopCycles[0x97]=8;
CBopCycles[0x98]=8;
CBopCycles[0x99]=8;
CBopCycles[0x9a]=8;
CBopCycles[0x9b]=8;
CBopCycles[0x9c]=8;
CBopCycles[0x9d]=8;
CBopCycles[0x9e]=16;
CBopCycles[0x9f]=8;
CBopCycles[0xa0]=8;
CBopCycles[0xa1]=8;
CBopCycles[0xa2]=8;
CBopCycles[0xa3]=8;
CBopCycles[0xa4]=8;
CBopCycles[0xa5]=8;
CBopCycles[0xa6]=16;
CBopCycles[0xa7]=8;
CBopCycles[0xa8]=8;
CBopCycles[0xa9]=8;
CBopCycles[0xaa]=8;
CBopCycles[0xab]=8;
CBopCycles[0xac]=8;
CBopCycles[0xad]=8;
CBopCycles[0xae]=16;
CBopCycles[0xaf]=8;
CBopCycles[0xb0]=8;
CBopCycles[0xb1]=8;
CBopCycles[0xb2]=8;
CBopCycles[0xb3]=8;
CBopCycles[0xb4]=8;
CBopCycles[0xb5]=8;
CBopCycles[0xb6]=16;
CBopCycles[0xb7]=8;
CBopCycles[0xb8]=8;
CBopCycles[0xb9]=8;
CBopCycles[0xba]=8;
CBopCycles[0xbb]=8;
CBopCycles[0xbc]=8;
CBopCycles[0xbd]=8;
CBopCycles[0xbe]=16;
CBopCycles[0xbf]=8;
<file_sep>/arm9/include/gbcpu.h
#pragma once
#include "global.h"
#define GB 0
#define CGB 1
typedef union
{
u16 w;
struct B
{
u8 l;
u8 h;
} b;
} Register;
//extern Register af,bc,de,hl;
extern u16 gbSP,gbPC;
extern int fps;
extern int halt;
extern int ime;
extern int gbMode;
extern int totalCycles;
extern int cyclesToExecute;
void initCPU();
void enableInterrupts();
void disableInterrupts();
void handleInterrupts();
int runOpcode(int cycles);
<file_sep>/arm9/include/gbsnd.h
#include "global.h"
#define FREQUENCY 44100
#define BUFFERSIZE 1024
extern float updateBufferLimit;
extern bool soundDisabled;
extern bool soundDisabledLid;
void initSND();
void enableChannel(int i);
void disableChannel(int i);
void updateSound(int cycles);
void handleSoundRegister(u16 addr, u8 val);
void updateSoundSample();
void handleSDLCallback(void* userdata, u8* buffer, int len);
<file_sep>/arm9/include/gameboy.h
#pragma once
#include "global.h"
#define min(a,b) (a<b?a:b)
//#define LOG
extern int timerPeriod;
extern long periods[4];
extern int timerCounter;
extern int mode2Cycles;
extern int mode3Cycles;
extern int doubleSpeed;
extern int cycles;
extern bool screenOn;
extern int turbo;
extern bool fpsOutput;
extern bool timeOutput;
void runEmul();
int haltWait(int cycles);
void initLCD();
void updateLCD(int cycles);
void updateTimers(int cycles);
void handleInterrupts();
void requestInterrupt(int id);
|
bbae71a45ae2d6d9caba9a23a18f9a8418c19f56
|
[
"C",
"C++"
] | 11 |
C++
|
Normmatt/GameYob
|
9ea7c2632293e57b4143f07538ee11b5fd8c5787
|
d549eb4771ceb4f79c0643d445a1a92e81994291
|
refs/heads/master
|
<file_sep> //python -m http.server
//http://localhost:8000
// Step 1: Set up our chart
//= ================================
var svgWidth = 960;
var svgHeight = 500;
var margin = {
top: 20,
right: 40,
bottom: 60,
left: 50
};
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
// Step 2: Create an SVG wrapper,
// append an SVG group that will hold our chart,
// and shift the latter by left and top margins.
// =================================
var svg = d3
.select("body")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
var chartGroup = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
//id,state,abbr,poverty,povertyMoe,age,ageMoe,income,incomeMoe,
//healthcare,healthcareLow,healthcareHigh,obesity,obesityLow,
//obesityHigh,smokes,smokesLow,smokesHigh
//need state abbr
// console.log(demoData);
//data
d3.csv('assets/data/data.csv', function(error, demoData) {
if (error) return console.warn(error);
var dStateAbb = demoData.map(data => data.abbr);
console.log(dStateAbb);
demoData.forEach(function(data){
demo
})
//if (error) throw error;
console.log(demoData);
console.log("hello");
// log a list of names
// var names = demoData.map(data => data.name);
//console.log("state", dStateAbb);
// Cast each hours value in tvData as a number using the unary + operator
// demoData.forEach(function(data) {
// data.hours = +data.hours;
// console.log("Name:", data.name);
// console.log("Hours:", data.hours);
// });
});
//svg -
// @TODO: YOUR CODE HERE!
|
d0ea9c8f9ba6d5fb1921632caa34cf51f970f916
|
[
"JavaScript"
] | 1 |
JavaScript
|
Cgorbas/16HWcrg
|
4769448271eabfae7f6aeeace43f2cb955affcfa
|
8c7dcfb52d7e4dff49feb1dc836fa3f8080411a4
|
refs/heads/master
|
<repo_name>Blodjer/DarkScreens<file_sep>/DarkScreens/Control.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Principal;
namespace DarkScreens
{
public partial class Control : Form
{
private readonly String version = "1.1.1";
private List<Dimmer> dimmerList = new List<Dimmer>();
private List<RadioButton> modeButtonList = new List<RadioButton>();
private ContextMenu notifyContextMenu;
private Boolean dimEnabled = true;
public Control()
{
InitializeComponent();
this.label_version.Text = "v" + version;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
if (Properties.Settings.Default.windowY == -1)
{
this.StartPosition = FormStartPosition.WindowsDefaultLocation;
}
else
{
this.SetDesktopLocation(Properties.Settings.Default.windowX, Properties.Settings.Default.windowY);
}
modeButtonList.Add(this.radioButton_multiple);
modeButtonList.Add(this.radioButton_single);
modeButtonList.Add(this.radioButton_all);
this.opacityTrackBar.Value = (int)(Properties.Settings.Default.opacity * 20);
this.label_opacity.Text = (int)(Properties.Settings.Default.opacity * 100) + "%";
notifyContextMenu = new ContextMenu();
notifyContextMenu.MenuItems.Add("Open", notifyIcon_Click);
notifyContextMenu.MenuItems.Add("Deactivate", toggleClick);
notifyContextMenu.MenuItems.Add("Exit", exitClick);
notifyIcon.ContextMenu = notifyContextMenu;
notifyIcon.DoubleClick += notifyIcon_Click;
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
this.screenComboBox.Items.Add("Display " + (i + 1));
}
if (Screen.AllScreens.Length == 2 && Properties.Settings.Default.screen == -1)
{
this.screenComboBox.SelectedIndex = 1;
Properties.Settings.Default.screen = 1;
Properties.Settings.Default.Save();
}
else if(Properties.Settings.Default.screen == -1)
{
this.screenComboBox.SelectedIndex = 0;
Properties.Settings.Default.screen = 0;
Properties.Settings.Default.Save();
}
else
{
this.screenComboBox.SelectedIndex = Properties.Settings.Default.screen;
}
foreach (Screen screen in Screen.AllScreens)
{
dimmerList.Add(new Dimmer(screen, Properties.Settings.Default.opacity));
}
setMode(Properties.Settings.Default.mode);
checkBoxLock.Checked = Properties.Settings.Default.singleLock;
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
if(principal.IsInRole(WindowsBuiltInRole.Administrator))
{
checkBoxAutostart.Enabled = true;
}
RegistryKey AutostartReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
object RegPath = AutostartReg.GetValue("DarkScreens");
if (RegPath != null && AutostartReg.GetValue("DarkScreens").ToString() == "\"" + Application.ExecutablePath.Replace("/", "\\") + "\"")
{
checkBoxAutostart.Checked = true;
}
else
{
checkBoxAutostart.Checked = false;
}
AutostartReg.Close();
if (Properties.Settings.Default.firststartup == true)
{
show();
}
//processListenerSetup();
Application.ApplicationExit += applicationExit;
}
public void setMode(int mode)
{
this.screenComboBox.Enabled = false;
this.checkBoxLock.Enabled = false;
switch (mode)
{
case 0:
this.radioButton_multiple.Checked = true;
if (dimEnabled) MultipleMode();
break;
case 1:
this.radioButton_single.Checked = true;
this.screenComboBox.Enabled = true;
this.checkBoxLock.Enabled = true;
if (dimEnabled) SingleMode(checkBoxLock.Checked);
break;
case 2:
this.radioButton_all.Checked = true;
if (dimEnabled) AllMode();
break;
default:
this.radioButton_multiple.Checked = true;
break;
}
Properties.Settings.Default.mode = mode;
Properties.Settings.Default.Save();
}
private void MultipleMode()
{
foreach (Dimmer dimmer in dimmerList)
{
dimmer.activate(true);
}
}
private void SingleMode(bool locking = false)
{
foreach (Dimmer dimmer in dimmerList)
{
if (screenComboBox.SelectedIndex == dimmerList.IndexOf(dimmer))
{
if (!locking) dimmer.activate(true);
else if (locking) dimmer.activate(false);
}
else
{
dimmer.deactivate();
}
}
}
private void AllMode()
{
foreach (Dimmer dimmer in dimmerList)
{
dimmer.activate(false);
}
}
private void setSingeleScreen(Screen screen)
{
Dimmer findeddimmer = dimmerList.Find(x => x.getScreen() == screen);
foreach (Dimmer dimmer in dimmerList)
{
if (dimmer == findeddimmer && dimEnabled == true)
{
dimmer.activate(true);
}
else
{
dimmer.deactivate();
}
}
}
private void activate()
{
notifyIcon.ContextMenu.MenuItems[1].Text = "Deactivate";
button_activate.Enabled = false;
button_deactivate.Enabled = true;
dimEnabled = true;
setMode(modeButtonList.FindIndex(x => x.Checked == true));
}
private void deactivate()
{
notifyIcon.ContextMenu.MenuItems[1].Text = "Activate";
button_activate.Enabled = true;
button_deactivate.Enabled = false;
dimEnabled = false;
foreach (Dimmer dimmer in dimmerList)
{
dimmer.deactivate();
}
}
private void opacityTrackBar_scroll(object sender, EventArgs e)
{
TrackBar trackBar = (TrackBar)sender;
double opacity = trackBar.Value / 20.0;
this.label_opacity.Text = (int)(opacity*100) + "%";
Properties.Settings.Default.opacity = opacity;
Properties.Settings.Default.Save();
foreach (Dimmer dimmer in dimmerList)
{
dimmer.setOpacity(opacity);
}
}
private void screenComboBox_indexChanged(object sender, EventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
Properties.Settings.Default.screen = comboBox.SelectedIndex;
Properties.Settings.Default.Save();
setSingeleScreen(Screen.AllScreens[comboBox.SelectedIndex]);
}
private void radiobutton_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
foreach (RadioButton rB in modeButtonList)
{
if (rB != radioButton)
{
rB.Checked = false;
}
}
}
setMode(modeButtonList.FindIndex(x => x.Checked == true));
}
private void checkBoxLock_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (CheckBox)sender;
if (checkBox.Enabled && dimEnabled) SingleMode(checkBox.Checked);
Properties.Settings.Default.singleLock = checkBox.Checked;
Properties.Settings.Default.Save();
}
private void checkBoxAutostart_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (CheckBox)sender;
if (checkBox.Enabled)
{
RegistryKey AutostartReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (checkBox.Checked) AutostartReg.SetValue("DarkScreens", "\"" + Application.ExecutablePath.Replace("/", "\\") + "\"");
else if (!checkBox.Checked) AutostartReg.DeleteValue("DarkScreens");
AutostartReg.Close();
}
}
private void show()
{
this.Show();
this.Activate();
this.WindowState = FormWindowState.Normal;
this.BringToFront();
}
private void hide()
{
this.Hide();
if (Properties.Settings.Default.firststartup == true)
{
notifyIcon.ShowBalloonTip(3000, "DarkScreens", "Application closed to tray", ToolTipIcon.None);
Properties.Settings.Default.firststartup = false;
Properties.Settings.Default.Save();
}
}
private void locationChanged(object sender, EventArgs e)
{
Properties.Settings.Default.windowX = this.Location.X;
Properties.Settings.Default.windowY = this.Location.Y;
Properties.Settings.Default.Save();
}
private void formClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.WindowsShutDown)
{
e.Cancel = true;
hide();
}
}
private void applicationExit(object sender, EventArgs e)
{
notifyIcon.Dispose();
}
private void notifyIcon_Click(object sender, EventArgs e)
{
if (this.Visible)
{
hide();
}
else if (!this.Visible)
{
show();
}
}
private void toggleClick(object sender, EventArgs e)
{
if (dimEnabled)
{
deactivate();
}
else if (!dimEnabled)
{
activate();
}
}
private void exitClick(object sender, EventArgs e)
{
Application.ExitThread();
}
/*--------------------------------------------------------- following is not in use yet
private List<String> processListenList;
private void processListenerSetup()
{
if(Properties.Settings.Default.processList == null)
{
Properties.Settings.Default.processList = new List<String>();
Properties.Settings.Default.Save();
}
processListenList = Properties.Settings.Default.processList;
Timer processTimer = new Timer();
processTimer.Interval = 1500;
processTimer.Tick += processTimerTick;
processTimer.Start();
}
private void processTimerTick(object sender, EventArgs e)
{
Console.WriteLine("tick");
Process[] processes = Process.GetProcesses();
int count = 0;
foreach (Process selectedProcess in processes)
{
if (processListenList.Contains(selectedProcess.ProcessName))
{
Console.WriteLine(selectedProcess.ProcessName + " is running");
activate();
count++;
}
}
if (count == 0)
{
deactivate();
}
}
private void process_Exited(object sender, EventArgs e)
{
Process senderProcess = (Process)sender;
senderProcess.Exited -= process_Exited;
Console.WriteLine(senderProcess.ProcessName + " has exit");
deactivate();
}
private void addProgram()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "exe files (*.exe)|*.exe";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Console.WriteLine(Path.GetFileNameWithoutExtension(openFileDialog.FileName));
processListenList.Add(Path.GetFileNameWithoutExtension(openFileDialog.FileName));
Properties.Settings.Default.processList = processListenList;
Properties.Settings.Default.Save();
}
}
private void addProgram_Click(object sender, EventArgs e)
{
addProgram();
}
*/
}
}
<file_sep>/DarkScreens/Dimmer.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace DarkScreens
{
public partial class Dimmer : Form
{
private Screen dimScreen;
private Timer dimTimer = new Timer();
private Boolean active;
private Boolean dimmed;
[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "SetWindowLong")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetLayeredWindowAttributes")]
public static extern bool SetLayeredWindowAttributes(IntPtr hWnd, int crKey, byte alpha, int Flags);
public Dimmer(Screen screen, double opacity)
{
InitializeComponent();
int wl = GetWindowLong(this.Handle, -20);
wl = wl | 0x80000 | 0x20;
SetWindowLong(this.Handle, -20, wl);
SetLayeredWindowAttributes(this.Handle, 0, 128, 0x2);
dimScreen = screen;
tempOpacity = opacity;
this.Location = dimScreen.Bounds.Location;
this.Size = dimScreen.Bounds.Size;
dimTimer.Interval = 25;
dimTimer.Tick += new EventHandler(tick);
dimTimer.Enabled = false;
}
//http://www.csharp411.com/hide-form-from-alttab/
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x80;
return cp;
}
}
private void tick(object sender, EventArgs e)
{
checkDimPermission();
}
private void checkDimPermission()
{
if (Cursor.Position.X < dimScreen.Bounds.Right && Cursor.Position.X >= dimScreen.Bounds.Left)
{
undim();
}
if (Cursor.Position.X >= dimScreen.Bounds.Right || Cursor.Position.X < dimScreen.Bounds.Left)
{
dim();
}
}
public void activate(Boolean cursorDependent)
{
if (cursorDependent)
{
dimTimer.Start();
checkDimPermission();
}
else if (!cursorDependent)
{
dimTimer.Stop();
dim();
}
active = true;
}
public void deactivate()
{
dimTimer.Stop();
undim();
active = false;
}
public Boolean isActive()
{
return active;
}
private void dim()
{
if (dimmed == false)
{
this.Show();
fadeIn();
dimmed = true;
}
}
private void undim()
{
if (dimmed == true)
{
fadeOut();
dimmed = false;
}
}
private double tempOpacity;
private Timer fadeTimer;
private void fadeIn()
{
if (fadeTimer != null && fadeTimer.Enabled == true)
{
fadeTimer.Dispose();
}
fadeTimer = new Timer();
fadeTimer.Interval = 2;
fadeTimer.Tick += new EventHandler(fadeInTick);
fadeTimer.Start();
}
private void fadeOut()
{
if (fadeTimer != null && fadeTimer.Enabled == true)
{
fadeTimer.Dispose();
}
fadeTimer = new Timer();
fadeTimer.Interval = 2;
fadeTimer.Tick += new EventHandler(fadeOutTick);
fadeTimer.Start();
}
private void fadeInTick(object sender, EventArgs e)
{
Timer t = (Timer)sender;
if (this.Opacity < tempOpacity)
{
this.Opacity += 0.02;
}
else
{
t.Dispose();
}
}
private void fadeOutTick(object sender, EventArgs e)
{
Timer t = (Timer)sender;
if (this.Opacity > 0.0)
{
this.Opacity -= 0.02;
}
else
{
this.Hide();
t.Dispose();
}
}
public void setOpacity(double opacity)
{
tempOpacity = opacity;
if(dimmed == true)
{
this.Opacity = opacity;
}
}
public void setScreen(Screen screen)
{
dimScreen = screen;
this.Location = dimScreen.Bounds.Location;
this.Size = dimScreen.Bounds.Size;
}
public double getOpacity()
{
return this.Opacity;
}
public Screen getScreen()
{
return this.dimScreen;
}
}
}
<file_sep>/DarkScreens/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DarkScreens
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
//http://stackoverflow.com/a/6392077
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
Application.SetCompatibleTextRenderingDefault(false);
Control control = new Control();
Application.Run();
}
}
}
|
6c09e6ceff08d22ae1cbdeaf4101bddb5efb317e
|
[
"C#"
] | 3 |
C#
|
Blodjer/DarkScreens
|
f9258d79087d45b9791cdae0a3db0ab0d24a5b5d
|
905f9f071e9189b569932cd1f076aee9f98c9afd
|
refs/heads/master
|
<file_sep># Bayesian A/B testing
### Bayesian A/B testing in Shiny App.
- [Shiny App](https://khg423.shinyapps.io/A_B_Testing/)에서 사용해 볼 수 있습니다.
- 이 shiny app의 아이디어는 [<NAME>의 포스팅](http://varianceexplained.org/r/bayesian_ab_baseball/)과 [COUNT BAYESIE의 포스팅] (https://www.countbayesie.com/blog/2015/4/25/bayesian-ab-testing)에 기반하였습니다.
- 일반적으로 광고의 CTR(Click through rate)이나 CVR(Conversion rate)를 비교할 때, 한 경우의 케이스가 다른 경우보다 사건횟수가 적어서 비교하기 모호한 경우가 있습니다.
- 예를 들어, A케이스는 클릭 100번에 인스톨이 5번이라 인스톨 CVR이 5%고, B케이스는 클릭 1,000번에 40번 인스톨이라 인스톨 CVR이 4%인 경우가 있습니다. 그렇다면 사건 발생이 상대적으로 적었던 A케이스의 CVR 5%가 사건 발생이 많았던 B케이스의 CVR 4%보다 정말 좋은 성과를 나타낸 것일까요?
- 이런 상황에서 베이지안 분석을 적용하면, 사용자가 사전 Beta를 정의해 주고 비교하고 싶은 사건 (ex. 인스톨/클릭, 클릭/노출)의 횟수를 입력하여 A/B 케이스를 비교할 수 있습니다.
- 위에서 언급한 케이스를 예시로 사용하면 아래와 같습니다.
- 먼저, 사전 확률을 입력합니다. 일반적으로 광고운영에서 클릭대비 인스톨이 10%를 넘어가는 경우는 거의 없기 때문에, prior beta에서 beta1은 1, beta2는 9로 입력하였습니다 (보통 bata0, alpha0로 표기합니다.). 그러므로 prior beta는 Beta(1,9)입니다. 나머지 클릭 수와 인스톨 수는 위의 예시 대로 입력하였습니다.
- 그러면 아래와 같이 A가 B보다 CVR이 높을 확률을 계산해 줍니다.
- 결과 값이 50%면 높을 확률 반 낮을 확률 반이기 때문에 거의 유사하다는 의미입니다. 실제 분석 결과를 살펴보면, A의 CVR이 B보다 높을 확률이 71.3%로 나타났습니다. 이는 그다지 높은 확률은 아닙니다. 즉, 케이스 A의 CVR 5%가 B의 4%보다 명백히 더 좋다고 말하기 어렵습니다.
```
$Result
[1] "71.2%"
$A
[1] "5%"
$B
[1] "4%"
```
- 아래는 위에서 계산된 A/B 케이스의 CVR을 Beta distribution에 따라 그린 분포입니다. 이를 통해 시각적으로 두 CVR의 차이를 확인할 수 있습니다.
- 아래 그림을 보면, 사건횟수 적었던 A가 사건횟수가 많았던 B보다 더 넓은 분포를 나타내는걸 확인할 수 있습니다. 그리고 두케이스의 분포가 겹치는 부분도 많습니다. 이를 통해 차이가 크지 않다는 걸 시각적으로 확인할 수 있습니다.
- 베이지안 접근의 장점중 하나는 효과의 유의성 뿐 아니라, 그 크기를 확인할 수 있다는 점입니다.
- 두 케이스의 CVR을 Beta distribution에 따라 시뮬레이션한 값을 비교하여 그 크기를 확인할 수 있습니다.
- 아래 결과를 보면, 40% 값이 대략 1.151정도 입니다. 이는 A가 B보다 1.15배 좋을 확율이 60%라는 의미입니다. 60% 값은 1.434정도인데 이는 A가 B보다 1.4배 좋을 확률이 40%라는 의미입니다.
```
Impact
10% 0.7035792
20% 0.8753253
30% 1.0170273
40% 1.1512797
50% 1.2875144
60% 1.4342028
70% 1.6055581
80% 1.8238089
90% 2.1618528
100% 7.3409547
```
- 위의 결과를 종합해보면, 광고 A가 B보다 CVR이 높다고 평가할 수 있는 확률도 낮지만, 그 차이의 크기 역시 상당히 낮은 것을 확인 할 수 있습니다.
<file_sep>library(shiny)
library(scales)
library(broom)
library(ggplot2)
library(dplyr)
theme_set(theme_bw())
shinyServer(
function(input, output) {
# 본 A/B 테스트는 시도 횟수대비 성공 확률(성공/시도)을 비교하기 위함.
# Beta prior를 사용한 Binomial Distribution 모델링.
# 이 경우는 광고 클릭 대비 앱 인스톨(Install CVR) 상황을 가정.
# A의 경우가 B경우 보다 성공확률(CVR)이 높을 확률을 계산.
# 추가적으로 각각의 CVR도 표기.
test.result <- reactive({
beta1 <- as.numeric(input$beta1)
beta2 <- as.numeric(input$beta2)
clicks_A <- as.numeric(input$clicks_A)
clicks_B <- as.numeric(input$clicks_B)
installs_A <- as.numeric(input$installs_A)
installs_B <- as.numeric(input$installs_B)
if(is.na(beta1)|is.na(beta2)|is.na(clicks_A)|is.na(clicks_B)|is.na(installs_A)|is.na(installs_B)){
test.result<-NA
} else {
ver.A <- rbeta(1000000,beta1+installs_A,beta2+(clicks_A-installs_A))
ver.B <- rbeta(1000000,beta1+installs_B,beta2+(clicks_B-installs_B))
test.result <- sum(ver.A > ver.B)/1000000
test <- list()
test$Result <- percent(test.result)
test$A <- percent(installs_A/clicks_A)
test$B <- percent(installs_B/clicks_B)
test
}
})
# 베이지안 접근의 장점중 하나는 효과의 유의성 뿐 아니라, 효과의 크기를 확인할 수 있음.
# 두 케이스(A/B)의 Beta distribution에 따른 시뮬레이션 결과값을 비교하여 그 크기를 확인.
quan <- reactive({
beta1 <- as.numeric(input$beta1)
beta2 <- as.numeric(input$beta2)
clicks_A <- as.numeric(input$clicks_A)
clicks_B <- as.numeric(input$clicks_B)
installs_A <- as.numeric(input$installs_A)
installs_B <- as.numeric(input$installs_B)
if(is.na(beta1)|is.na(beta2)|is.na(clicks_A)|is.na(clicks_B)|is.na(installs_A)|is.na(installs_B)){
quan <- NA
} else {
ver.A <- rbeta(1000000,beta1+installs_A,beta2+(clicks_A-installs_A))
ver.B <- rbeta(1000000,beta1+installs_B,beta2+(clicks_B-installs_B))
ecdf <- ver.A/ver.B
quan <- quantile(ecdf, c(1:10*.1))
quan
}
})
# A/B 케이스 CVR의 Beta distribution에 따른 Density plot를 그리기 위한 데이터 전처리 과정.
graph <- reactive({
beta1 <- as.numeric(input$beta1)
beta2 <- as.numeric(input$beta2)
clicks_A <- as.numeric(input$clicks_A)
clicks_B <- as.numeric(input$clicks_B)
installs_A <- as.numeric(input$installs_A)
installs_B <- as.numeric(input$installs_B)
if(is.na(beta1)|is.na(beta2)|is.na(clicks_A)|is.na(clicks_B)|is.na(installs_A)|is.na(installs_B)){
graph <- NA
} else {
ver.A.beta1 <- beta1+installs_A
ver.A.beta2 <- beta2+(clicks_A-installs_A)
ver.B.beta1 <- beta1+installs_B
ver.B.beta2 <- beta2+(clicks_B-installs_B)
graph <- data.frame(id=c('A','B'),beta1=c(ver.A.beta1,ver.B.beta1),beta2=c(ver.A.beta2,ver.B.beta2),CVR=c(installs_A/clicks_A,installs_B/clicks_B))
graph
}
})
output$test.result <- renderPrint({
test.result<-test.result()
test.result
})
output$quan <- renderPrint({
quan <- quan()
quan <- data.frame(Impact=quan)
quan
})
# A/B 케이스 CVR의 Beta distribution에 따른 Density plot.
# 사건 시도 횟수가 적으면 사건 시도 횟수가 많은 경우보다 더 넓은 분포를 보이는 걸 시각적으로 확인할 수 있음.
# 또한, 두 케이스의 차이가 적으면, 분포가 겹치는 것을 확인할 수 있음. 반면, 두 케이스의 차이가 크면 분포가 떨어져 있는걸 확인할 수 있음.
output$graph_plot <- renderPlot({
graph<-graph()
if(is.na(graph)){
plot.new()
} else {
graph_plot<-graph %>%
inflate(x = seq(0, with(graph, max(CVR)*2), with(graph, min(CVR)/100))) %>%
mutate(density = dbeta(x, beta1, beta2)) %>%
ggplot(aes(x, density, color = id)) +
geom_line() +
labs(x = "CVR", color = "")
print(graph_plot)
}
})
})
<file_sep>library(shiny)
library(broom)
library(dplyr)
library(ggplot2)
theme_set(theme_bw())
shinyUI(fluidPage(
titlePanel("Bayesian A/B Testing"),
mainPanel(
h6("- beta1, beta2는 사전 확률을 의미합니다."),
h6("- 예를들어 CVR이 보통 10%면, beta1은 1 beta2는 9를 입력하면 됩니다. 1%면 beta1은 0.1 beta2는 0.9를 입력하면 됩니다."),
column(2, textInput("beta1", label = h6("beta1"), value = ""),
textInput("beta2", label = h6("beta2"), value = "")),
column(2, textInput("clicks_A", label = h6("clicks_A"), value = ""),
textInput("clicks_B", label = h6("clicks_B"), value = "")),
column(2, textInput("installs_A", label = h6("installs_A"), value = ""),
textInput("installs_B", label = h6("installs_B"), value = ""),submitButton("Update View")),
column(10, h4("Result"),
h6("- Result는 A보다 B의 CVR이 높을 확률을 의미합니다."),
h6("- A는 A의 CVR을 의미합니다."),
h6("- B는 B의 CVR을 의미합니다."),
verbatimTextOutput("test.result"),
h4(""),
h4("Result Density"),
plotOutput("graph_plot"),
h4(""),
h4("Impact"),
h6("- 효과의 크기를 의미합니다."),
h6("- 예를들어 10%의 해당값이 1.20이면 A가 B보다 120% 향상될 확률이 90%라는 의미입니다."),
verbatimTextOutput("quan"))
)
))
|
25a908a4713a32f4721bd9f8fcb0af52dd62c458
|
[
"Markdown",
"R"
] | 3 |
Markdown
|
kmangyo/Bayesian_A-B_Testing
|
479bdb1e52e35414825dac5f72b7b476b6f35b68
|
7e700e8b8910dbb66c5670cc2a8336ca642e928d
|
refs/heads/main
|
<repo_name>Project-Catwalk/Wallace-Corporation<file_sep>/client/src/components/overview/OverviewExpandedModal.jsx
import React, { useState, useEffect, useRef } from 'react';
import styles from '../../styleComponents/Overview.module.css';
const OverviewExpandedModal = (props) => {
// STILL TO DO:
// Need to make thumbnail icons instead of images show up on expanded view (pagination)
// Need to have parallax/scroll effect on zoomed in view of main image
const { children, open, close, } = props;
const [height, setHeight] = useState(null);
const [width, setWidth] = useState(null);
const [isZoomed, setIsZoomed] = useState(false);
const [cursorString, setcursorString] = useState('crosshair');
// const [move, setMove] = useState({ x: 0, y: 0 });
const imgRef = useRef();
if (!open) {
return null;
}
const zoom = (event) => {
event.preventDefault();
if (event.key === 'Enter' || event.key === 'Space bar') {
const currentHeight = imgRef.current.clientHeight;
const currentWidth = imgRef.current.clientWidth;
if (isZoomed === false) {
setIsZoomed(true);
setHeight(currentHeight * 2.5);
setWidth(currentWidth * 2.5);
setcursorString('zoom-out');
} else {
setIsZoomed(false);
setHeight(currentHeight / 2.5);
setWidth(currentWidth / 2.5);
setcursorString('crosshair');
}
}
const currentHeight = imgRef.current.clientHeight;
const currentWidth = imgRef.current.clientWidth;
if (isZoomed === false) {
setIsZoomed(true);
setHeight(currentHeight * 2.5);
setWidth(currentWidth * 2.5);
setcursorString('zoom-out');
} else {
setIsZoomed(false);
setHeight(currentHeight / 2.5);
setWidth(currentWidth / 2.5);
setcursorString('crosshair');
}
};
// const mouseMove = (event) => {
// if (isZoomed) {
// setMove({ x: event.clientX, y: event.clientY });
// // console.log('event: ', event);
// // console.log('event.clientX: ', event.clilentX);
// // console.log('event.clientY: ', event.clientY);
// }
// };
return (
<>
<div className={styles.modalOverlay} />
<div
role="button"
tabIndex={0}
onKeyDown={zoom}
className={styles.modal}
ref={imgRef}
onClick={zoom}
// onMouseMove={mouseMove}
style={{ height, width, cursor: cursorString }}
>
<div className={styles.expandedImgAndX}>
<div role="button" tabIndex={0} className={styles.mainModalXToClose} onClick={close} onKeyDown={close}>X</div>
{children}
</div>
</div>
</>
);
};
export default OverviewExpandedModal;
<file_sep>/client/src/components/reviews/RatingBreakdown.jsx
import React, { useState, useEffect } from 'react';
import StarRating from '../StarRating';
import styles from '../../styleComponents/Reviews.module.css';
const RatingBreakdown = ({
reviews, metaReviews, handleStarFilters, handleReviewAverage, charObject
}) => {
const { ratings, recommended, characteristics } = metaReviews;
const [average, setAverage] = useState();
const [starFilters, setStarFilters] = useState([]);
const [starBreakdown, setStarBreakdown] = useState({
1: '',
2: '',
3: '',
4: '',
5: '',
});
const [total, setTotal] = useState(0);
const [recommend, setRecommend] = useState(0);
Object.assign(starBreakdown, ratings);
const getTotal = (obj) => {
if (obj) {
const ratingTotal = Object.values(obj).reduce((z, y) => {
return z += Number(y)},
0);
setTotal(ratingTotal);
}
};
const getRecommended = (obj) => {
if (obj) {
const percentRecommended =
Math.round((Number(obj.true) / (Number(obj.true) + Number(obj.false))) * 100);
setRecommend(percentRecommended);
}
};
const averageRating = () => {
const reducedRating = reviews.reduce((acc, review) => {
const total = acc + (review.rating / 5) * 100;
return total;
}, 0);
const temp = reducedRating / reviews.length;
const roundedAvg = (Math.round(temp));
const avg = Math.round(roundedAvg / 5) * 5;
setAverage(avg);
handleReviewAverage(avg);
};
const handleFilters = (star) => {
const currentFilters = starFilters;
currentFilters.push(star);
setStarFilters(currentFilters);
handleStarFilters(starFilters);
};
const removeFilters = () => {
setStarFilters([]);
handleStarFilters([]);
};
useEffect(() => {
averageRating();
Object.assign(starBreakdown, ratings);
getTotal(ratings);
getRecommended(recommended);
}, [metaReviews]);
return (
(metaReviews && average && characteristics)
? (
<div className={styles.breakdownGrid} data-testid="breakdown-render">
<p id="scrollTarget" style={{ fontSize: '18px' }} className={styles.breakdownHeader}>Ratings & Reviews</p>
<div className={styles.breakdownStars} style={{ justifySelf: 'left' }}>
<StarRating average={average} />
</div>
<h1 className={styles.breakdownTotal}>{`${(average / 20).toFixed(1)}` }</h1>
<p className={styles.breakdownRecommended}>
{recommend}
% of reviews recommend this product
</p>
<p className={styles.breakdownSubheader}>
Rating Breakdown: (
out of
{' '}
{total}
{' '}
)
</p>
<div className={styles.breakdownStarBreakdown}>
{Object.entries(starBreakdown).map((star) => {
const avg = (Number(star[1]) / 12) * 100;
return (
<div key={star[0]}>
<span
className={`${styles.starCount} ${styles.comment}`}
role="presentation"
onKeyDown={handleFilters}
onClick={() => {
handleFilters(star[0]);
}}
>
{star[0]}
{' '}
Star
</span>
<div className={styles.progressContainer}>
<div className={styles.progressbar} style={{ width: avg }} />
</div>
<span className={styles.comment} style={{ fontStyle: 'italic' }}>{star[1]}</span>
<br />
</div>
);
})}
{starFilters.length > 0
? (
<div className={styles.comment}>
<span>Current Filters:</span>
{starFilters.map((x) => (
<span
style={{ padding: '5px' }}
key={x}
>
{x}
{' '}
Stars
</span>
))}
<br />
<span
role="presentation"
onKeyDown={removeFilters}
className={styles.starCount}
onClick={removeFilters}
>
Remove all filters
</span>
</div>
)
: null}
</div>
<div className={styles.breakdownCharacteristics}>
{Object.entries(characteristics).map((char) => {
const value = (char[1].value / 5) * 100;
return (
<div key={char[0]} className={styles.breakdownCharacteristics} style={{ margin: '0' }}>
<div style={{ margin: '2px', paddingLeft: '13px' }}>{char[0]}</div>
<div className={styles.progressContainerChars}>
<div className={styles.progressbarChars} style={{ left: `${value}%` }} />
</div>
<div style={{ display: 'flex', width: '90%', justifyContent: 'space-between' }}>
<span className={styles.comment} style={{ marginLeft: '9%' }}>
(1)
{charObject[char[0]][1]}
</span>
<span className={styles.comment}>
(5)
{charObject[char[0]][5]}
</span>
</div>
<br />
</div>
);
})}
</div>
</div>
)
: null
);
};
export default RatingBreakdown;
<file_sep>/README.md
# Wallace Corporation
<p align="center">
<a href="https://github.com/Project-Catwalk">
<img src="./public/img/Wallace_Corporation_logo.png" width="90" height="90">
</a>
</p>
# Contributors
[<NAME>](https://github.com/lucipak "<NAME>")
[<NAME>](https://github.com/jessesmith-13 "<NAME>")
[<NAME>](https://github.com/emagdaeh "<NAME>")
# Introduction
Wallace Corporation is a front-end redesign for an e-commerce website specializing in clothing and apparel. The stated that the website needed to have a product overview, a questions & answers section, and a ratings & reviews section. The product overview section provides a main display with an image carousel of thumbnail images for the current style. Each product also comes with multiple styles and the user can select individual styles with thumbnail button images. Each product's important info is also displayed (i.e. name, price, style, description, etc.). Finally, the product overview includes a size and quantity selector and an add to cart button for the user to store products they intend to purchase.
The questions and answers section provides the user with the ability to post and read questions about a product as well as the ability to answer questions other users have posted. The user has the ability to add images to their questions to give context to the questions being asked. The company employees can also answer questions with a designation to let all users see that the question was answered by an employee of the companty. Questions and answers are also filterable to help the user get to the information most relevant to them.
The ratings and reviews section displays the average rating for each product, specific metrics used to rate a product (i.e. size, fit, length, etc.). The user is able to post their own reviews as well as photos of what they are reviewing. Ratings and reviews are also searchable similar to the questions and answers section.
# Tech Stack
<ul>
<li>React</li>
<li>Express</li>
<li>Node.js</li>
<li>Axios</li>
<li>CSS Modules</li>
<li>Bootstrap icons</li>
<li>Jest</li>
<li>React testing libraries</li>
<li>AWS</li>
<li>Brotli</li>
<li>Microsoft Azure</li>
<li>Babel</li>
<li>Webpack</li>
</ul>
# Technical Challenges and Research
<ul>
<li>Implementation of both a pagination and parallax effect</li>
<li>Accessibility features without using additional tech that has it built in (such as bootstrap for CSS)</li>
</ul>
# User Stories
<ul>
<li>As a user, I want to be able to see a large, clear image of the product I have searched for</li>
<li>As a user, I would like to see the average star rating for a product I am looking at</li>
<li>As a user, I would like to see all important information about a product such as the product category, the name, the price, and the description</li>
<li>As a user, I would like to have links to my favorite social media sites, so I can share my product if I so choose</li>
<li>As a user, I would like to be able to change styles for a product I am looking at quickly and easily</li>
<li>As a user, if I have found a product I like, I would like to be able to add it to my cart with my choice of size and how many items I would like to purchase</li>
<li>As a user, I would like to be able to expand the main display image and cycle through all images for that style</li>
<li>As a user, I would like to be able to zoom in on an image and scroll around the image to get more fine clarity on what the product will look like when I receive it</li>
<li>As a user, I would like to be able to be able to write a new review of a product I have purchased including the ability to add pictures that I can refer to in my review</li>
<li>As a user, I would like to be able to see a list of all reviews associated with a product and be able to sort through the list for the review types that are most important to me</li>
<li>As a user, I would like to see a product breakdown with each of the adjectives I can rate the product on (i.e. size, fit, length, etc)</li>
<li>As a user, I would like to see the average rating for a product</li>
<li>As a user, I would like to be able to ask questions about a product before I purchase it</li>
<li>As a user, I would like to be able to see what questions other users have asked</li>
<li>As a user, I would like to be able to search for questions with specific key words I am interested in</li>
<li>As a user, I would like to be able to answer questions other users have posted if I know the answer</li>
<li>As a user, I would like to be able to add pictures that I can reference in my question</li>
<li>As a user, I would like to be able to flag a question as helpful if I found it to be</li>
<li>As a user, I would like to be able to report questions if they are inappropriate or irrelevant</li>
<li>As an employee, I would like to be able to respond to user's questions and indicate that it is an official company response</li>
</ul>
# Minimum Viable Product (MVP)
The MVP per client expectations would include a product overview with an image carousel and style selector. There should also be an add to cart feature with a size and quantity selector.
The MVP also requires a questions and answers section for users to post questions and respond with answeres where appropriate. There should also be an indicator for whether the response is coming from a company employee or if it is another user. The questions should be searchable and filterable.
The MVP also needs to have a ratings and reviews section that includes an aggragate review score for a product with the product features breakdown. There should also be a list of reviews for the the current product that is searchable and filterable.
# Stretch Goals and Additional Features
<ul>
<li>Initial reviews display limited to 2, but have an expandable list with an infinite scroll feature - MET</li>
<li>Initial questions display limited to 2, but have an expandable list with an infinite scroll feature - MET</li>
<li>Ability to add pictures to a question that will be posted by a user - MET</li>
<li>Pagination on the expanded main display image with its thumbnails - NOT MET</li>
<li>Parallax effect on the zoomed in main display image - NOT MET</li>
<li>Dynamic text highlight of matching text when searching reviews for key words - NOT MET</li>
<li>Dynamic text highlight of matching text when searching questions for key words - NOT MET</li>
</ul>
# How does the app work?
Product Overview:
<br />
<img src="./public/img/Product Overview Thumbnails.gif">
Expanded and Zoomed View:
<br />
<img src="./public/img/Product Overview Expanded and Zoomed.gif">
Add to Cart:
<br />
<img src="./public/img/Add to Cart.gif">
Questions and Answers:
<br />
<img src="./public/img/Questions Display.gif">
Add a Question:
<br />
<img src="./public/img/Add a Question.gif">
Ratings and Reviews:
<br />
<img src="./public/img/Ratings Display.gif">
Add a Review:
<br />
<img src="./public/img/Add a Review.gif">
# Workflow and Key Lessons
Workflow was managed through GitHub and utilizing Agile workflow through a Trello ticketing system. The team also had daily standup meetings to make sure everyone was on the same page, and could communicate on areas where bugs existed or when combining the various sections into a complete website.
Styling with raw CSS was a significant challenge for us, and made us really appreciate tools that exist like Bootstrap. Making sure the page met accessibility guidlines was also a challenge without significantly impacting our CSS designs was an interesting learning experience as well.
<file_sep>/client/src/components/overview/OverviewSize.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import styles from '../../styleComponents/Overview.module.css';
import OverviewCartModal from './OverviewCartModal';
const OverviewSize = (props) => {
const { skuOfChoice, styleChoice, name } = props;
const [currentSize, setCurrentSize] = useState('');
const [currentQuantityAvailable, setCurrentQuantityAvailable] = useState(null);
const [singleSkuId, setSingleSkuId] = useState('');
const [allSizesAndQuantities, setAllSizesAndQuantities] = useState([]);
const [allSkuIds, setAllSkuIds] = useState([]);
const [quantityAvailable, setQuantityAvailable] = useState([]);
const [countChosen, setCountChosen] = useState(1);
const [sku_id, setSku_id] = useState(0);
const [isOpen, setIsOpen] = useState(false);
const [cartButtonClicked, setCartButtonClicked] = useState(false);
const [outOfStockState, setOutOfStockState] = useState(null);
useEffect(() => {
const skuWithoutNumber = Object.values(skuOfChoice);
const skuIdsOfChoice = Object.keys(skuOfChoice);
const sizesAndQuantities = [];
const skuIds = [];
if (skuWithoutNumber.length > 0) {
for (let i = 0; i < skuWithoutNumber.length; i++) {
sizesAndQuantities.push(skuWithoutNumber[i]);
}
}
if (skuIdsOfChoice.length > 0) {
for (let i = 0; i < skuIdsOfChoice.length; i++) {
skuIds.push(skuIdsOfChoice[i]);
}
}
setCartButtonClicked(false);
setCurrentSize('Select Size');
setAllSizesAndQuantities(sizesAndQuantities);
setAllSkuIds(skuIds);
}, [skuOfChoice, styleChoice]);
const selectedSizeHandler = (event) => {
event.preventDefault();
for (let i = 0; i < allSizesAndQuantities.length; i++) {
if (allSizesAndQuantities[i].quantity === 0) {
setCurrentSize('OUT OF STOCK');
setOutOfStockState('OUT OF STOCK');
} else if (event.target.value === allSizesAndQuantities[i].size) {
setCurrentSize('');
setCurrentQuantityAvailable(allSizesAndQuantities[i].quantity);
setSingleSkuId(allSkuIds[i]);
setOutOfStockState(null);
}
}
};
useEffect(() => {
const integers = [];
if (currentQuantityAvailable > 15) {
for (let i = 1; i <= 15; i++) {
integers.push(i);
}
} else {
for (let i = 1; i <= currentQuantityAvailable || i === 15; i++) {
integers.push(i);
}
}
setQuantityAvailable(integers);
}, [currentQuantityAvailable]);
const quantitySelected = (event) => {
event.preventDefault();
for (let i = 0; i < quantityAvailable.length; i++) {
if (parseInt(event.target.value) === quantityAvailable[i]) {
setCountChosen(parseInt(event.target.value));
}
}
};
useEffect(() => {
setSku_id(parseInt(singleSkuId));
}, [currentSize, countChosen, singleSkuId]);
const handleCart = (event) => {
event.preventDefault();
setCartButtonClicked(true);
if (currentSize !== 'Select Size') {
setIsOpen(true);
}
};
const onClose = (event) => {
event.preventDefault();
axios
.post('/cart', { sku_id: `${sku_id}`, count: `${countChosen}` })
.then((status) => {
console.log('Status: ', status);
})
.catch((error) => {
console.log('Error: ', error);
});
setIsOpen(false);
setCartButtonClicked(false);
};
const exitCart = (event) => {
event.preventDefault();
if (event.key === 'Enter' || event.key === 'Space bar') {
setIsOpen(false);
setCartButtonClicked(false);
}
setIsOpen(false);
setCartButtonClicked(false);
};
return (
<>
{(currentSize === 'Select Size' && cartButtonClicked === true)
? (
<div className={styles.hiddenCartSentence}>Please select a size</div>
)
: null}
<select role="tablist" aria-label="Select size" onChange={selectedSizeHandler} tabIndex={0} className={styles.sizeDropDown}>
<option style={{ paddingLeft: '5px' }}>Select Size</option>
{allSizesAndQuantities.map((productSize, index) => (
<option role="tab" tabIndex={0} key={index}>{productSize.size}</option>
))}
</select>
<select role="tablist" aria-label="Select quantity" onChange={quantitySelected} tabIndex={0} className={styles.quantityDropDown}>
<option role="tab" disabled>-</option>
{quantityAvailable.map((num, index) => <option role="tab" tabIndex={0} key={index}>{num}</option>)}
</select>
<p style={{ color: 'red' }}>{outOfStockState}</p>
<div role="tablist" className={styles.cart}>
{currentSize !== 'OUT OF STOCK' && (<button type="submit" aria-label="Add to cart" role="tab" tabIndex={0} onClick={handleCart}>Add to Cart</button>)}
<OverviewCartModal open={isOpen} close={onClose} exitCart={exitCart}>
<form>
Item:
<p>{name}</p>
<br />
Style:
<p>{styleChoice}</p>
<br />
Size:
<p>8</p>
<br />
Quantity:
<p>{countChosen}</p>
</form>
</OverviewCartModal>
</div>
</>
);
};
export default OverviewSize;
<file_sep>/client/src/components/overview/OverviewCartModal.jsx
import React from 'react';
import styles from '../../styleComponents/Overview.module.css';
const OverviewCartModal = (props) => {
const {
children, open, close, exitCart
} = props;
if (!open) {
return null;
}
return (
<div>
<div className={styles.cartOverlay} />
<div className={styles.cartModal}>
<div role="button" aria-label="Add to cart" tabIndex={0} onClick={exitCart} onKeyDown={exitCart} className={styles.cartXToClose}>X</div>
{children}
<br />
Is this correct?:
<br />
<button type="submit" aria-label="Confirm" tabIndex={0} onKeyDown={close} onClick={close}>Confirm</button>
</div>
</div>
);
};
export default OverviewCartModal;
<file_sep>/client/src/components/App.jsx
import React, { Suspense, lazy } from 'react';
import axios from 'axios';
import { Icon } from '@iconify/react';
import messageOutlined from '@iconify-icons/ant-design/message-outlined';
import facebookIcon from '@iconify-icons/gg/facebook';
import twitterIcon from '@iconify-icons/gg/twitter';
import instagramIcon from '@iconify-icons/gg/instagram';
import pinterestFill from '@iconify-icons/akar-icons/pinterest-fill';
import Overview from './overview/Overview';
import style from '../styleComponents/App.module.css';
const QA = lazy(() => import('./qa/QA'));
const Reviews = lazy(() => import('./reviews/Reviews'));
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
id: '',
name: '',
overview: [],
styles: [],
related: [],
reviewRating: 0,
lightMode: true,
};
this.defaultProduct = this.defaultProduct.bind(this);
this.getStyles = this.getStyles.bind(this);
this.getRelated = this.getRelated.bind(this);
this.handleReviewAverage = this.handleReviewAverage.bind(this);
this.lightMode = this.lightMode.bind(this);
this.darkMode = this.darkMode.bind(this);
}
componentDidMount() {
this.defaultProduct(20104);
this.getStyles(20104);
this.getRelated(20104);
}
handleReviewAverage(average) {
this.setState({ reviewRating: average });
}
getStyles(id) {
axios.get(`/products/${id}/styles`)
.then((results) => {
this.setState({
styles: results.data.results,
});
})
.catch(console.log);
}
getRelated(id) {
axios.get(`/products/${id}/related`)
.then((results) => {
this.setState({
related: results.data,
});
})
.catch(console.log);
}
defaultProduct(productId) {
axios
.get(`/products/${productId}`)
.then((results) => {
this.setState({
id: results.data.id,
name: results.data.name,
overview: results.data,
});
})
.catch((err) => {
console.log(err);
});
}
lightMode() {
this.setState({
lightMode: true,
});
}
darkMode() {
this.setState({
lightMode: false,
});
}
render() {
const {
id, overview, styles, name, related, reviewRating, lightMode,
} = this.state;
return (
(id, overview, styles, name, related)
? (
<>
<div className={lightMode ? style.lightMode : style.darkMode}>
<div className={style.headerSale}>
<p className={style.onSale}>FREE SHIPPING ON ORDERS OVER $75</p>
</div>
<div className={style.header}>
<h1 data-testid="logo" className={`${style.headerText} ${style.logo}`}>The Wallace Corporation</h1>
<p className={`${style.headerText} ${style.shopAll}`}>SHOP ALL</p>
<p className={`${style.headerText} ${style.apparel}`}>APPAREL</p>
<p className={`${style.headerText} ${style.community}`}>COMMUNITY</p>
<p className={`${style.headerText} ${style.about}`}>ABOUT</p>
</div>
<Overview
overview={overview}
productStyles={styles}
relatedProducts={related}
average={reviewRating}
/>
<Suspense fallback={<div>LOADING</div>}>
<QA
productId={id}
name={name}
/>
</Suspense>
<Suspense fallback={<div>LOADING</div>}>
<Reviews
productId={id}
name={name}
handleReviewAverage={this.handleReviewAverage}
average={reviewRating}
/>
</Suspense>
<div className={style.footer}>
<div className={style.emailSignUp}>
<h2 className={style.bottomEmailHeading}>Sign up for exclusive offers</h2>
<input type="text" className={style.bottomEmail} placeholder="Enter your email" />
<button type="submit" className={style.footerSubscribe}>SUBSCRIBE</button>
</div>
<div className={lightMode ? style.bottom : style.bottomDarkMode}>
<div className={style.social}>
<p className={style.bottomHeading}>SOCIAL</p>
<Icon className={style.icon} icon={facebookIcon} />
<Icon className={style.icon} icon={twitterIcon} />
<Icon className={style.icon} icon={instagramIcon} />
<Icon className={`${style.icon} ${style.pinterest}`} icon={pinterestFill} />
</div>
<div className={style.bottomButtons}>
<button type="submit" className={`${style.bottomButton} ${style.bottomButtonLight}`} onClick={this.lightMode}>LIGHT</button>
<button type="submit" className={`${style.bottomButton} ${style.bottomButtonDark}`} onClick={this.darkMode}>DARK</button>
</div>
<div className={style.customerCare}>
<p className={style.bottomHeading}>CUSTOMER CARE</p>
<p className={style.customerCareContent}>FAQ</p>
<p className={style.customerCareContent}>Shipping + Returns</p>
<p className={style.customerCareContent}>Shop Now, Pay Later</p>
<p className={style.customerCareContent}>Size Guide</p>
<p className={style.customerCareContent}>Privacy Policy</p>
<p className={style.customerCareContent}>Contact Us</p>
</div>
<div className={style.messageIconSection}>
<div className={style.messageIconWrapper}>
<Icon className={style.messageIcon} icon={messageOutlined} />
</div>
</div>
</div>
</div>
</div>
</>
)
: null
);
}
}
export default App;
<file_sep>/__tests__/Overview.test.jsx
import React from 'react';
import ReactDOM, { unmountComponentAtNode } from 'react-dom';
import Overview from '../client/src/components/overview/Overview';
import { render, screen } from '@testing-library/react';
let container = null;
beforeEach(() => {
// setup a DOM element as a render target
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
// cleanup on exiting
unmountComponentAtNode(container);
container.remove();
container = null;
});
// it("renders with or without a name", () => {
// render(<Overview />, container);
// expect(container.textContent).toBe("Hey, stranger");
// render(<Overview name="Jenny" />, container);
// expect(container.textContent).toBe("Hello, Jenny!");
// render(<Overview name="Margaret" />, container);
// expect(container.textContent).toBe("Hello, Margaret!");
// });
<file_sep>/client/src/components/overview/OverviewCheckmark.jsx
import React from 'react';
import styles from '../../styleComponents/Overview.module.css';
const OverviewCheckmark = (props) => {
const {
styleNamePic,
styleButtonHandler,
styleChoice,
styleImgSelected,
} = props;
const imgForButton = (
<input
tabIndex={0}
type="image"
role="tab"
className={styles.stylesButtonsImgs}
onClick={styleButtonHandler}
onKeyDown={styleButtonHandler}
src={styleNamePic[0].thumbnail_url}
alt={styleChoice}
/>
);
return (
<div>
{(styleImgSelected === styleNamePic[0].thumbnail_url)
? (
<svg className={styles.styleButtonsOverlay} width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
<path d="M10.97 4.97a.235.235 0 0 0-.02.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05z" />
</svg>
)
: null}
{imgForButton}
</div>
);
};
export default OverviewCheckmark;
<file_sep>/client/src/components/qa/QASearchBar.jsx
import React from 'react';
import { Icon } from '@iconify/react';
import magnifyingGlass from '@iconify-icons/entypo/magnifying-glass';
import qastyles from '../../styleComponents/QA.modules.css';
const QASearchBar = (props) => {
const {searchQuestions} = props;
return (
<>
<div className={qastyles.searchBarSection}>
<Icon className={qastyles.magnifyingGlass} icon={magnifyingGlass} />
<input
aria-label="Search questions"
data-testid="search-input"
type="search"
onChange={(e) => searchQuestions(e.target.value)}
className={qastyles.searchBar}
placeholder="Search Questions..."
/>
</div>
</>
);
};
export default QASearchBar;
<file_sep>/client/src/components/reviews/Characteristics.jsx
import React, { useState } from 'react';
const Characteristics = ({ characteristics, charObject, setReview, review }) => {
const [chars, setChars] = useState({});
const handleCharacteristics = (e) => {
const { value } = e.target;
const arr = value.split('-');
const rating = arr[0];
const id = arr[1];
const newCharacteristics = chars;
newCharacteristics[id] = Number(rating);
setReview({ ...review, characteristics: newCharacteristics });
};
return (
(characteristics)
? Object.entries(characteristics).map((x) => (
<div key={x[1].id} onChange={handleCharacteristics} data-testid="characteristic-map">
<p>{x[0]} *</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 25%)', fontSize: '10px' }}>
<div style={{ display: 'grid', gridTemplateRows: 'auto auto', gridColumn: '1/2' }}>
<label style={{ gridRow: '2/3', justifySelf: 'center' }} htmlFor="one">{charObject[x[0]][1]}</label>
<input
type="radio"
required="required"
name={x[0]}
value={`1-${x[1].id}`}
style={{ gridRow: '1/2', justifySelf: 'center' }}
/>
</div>
<div style={{ display: 'grid', gridTemplateRows: 'auto auto', gridColumn: '2/3' }}>
<label style={{ gridRow: '2/3', justifySelf: 'center' }} htmlFor="two">{charObject[x[0]][2]}</label>
<input
type="radio"
name={x[0]}
value={`2-${x[1].id}`}
style={{ gridRow: '1/2', justifySelf: 'center' }}
/>
</div>
<div style={{ display: 'grid', gridTemplateRows: 'auto auto', gridColumn: '3/4' }}>
<label style={{ gridRow: '2/3', justifySelf: 'center' }} htmlFor="three">{charObject[x[0]][3]}</label>
<input
type="radio"
name={x[0]}
value={`3-${x[1].id}`}
style={{ gridRow: '1/2', justifySelf: 'center' }}
/>
</div>
<div style={{ display: 'grid', gridTemplateRows: 'auto auto', gridColumn: '4/5' }}>
<label style={{ gridRow: '2/3', justifySelf: 'center' }} htmlFor="four">{charObject[x[0]][4]}</label>
<input
type="radio"
name={x[0]}
value={`4-${x[1].id}`}
style={{ gridRow: '1/2', justifySelf: 'center' }}
/>
</div>
<div style={{ display: 'grid', gridTemplateRows: 'auto auto', gridColumn: '5/6' }}>
<label style={{ gridRow: '2/3', justifySelf: 'center' }} htmlFor="five">{charObject[x[0]][5]}</label>
<input
type="radio"
name={x[0]}
value={`5-${x[1].id}`}
style={{ gridRow: '1/2', justifySelf: 'center' }}
/>
</div>
</div>
</div>
))
: null
);
};
export default Characteristics;
<file_sep>/__tests__/Reviews.test.jsx
import React from 'react';
import { render, screen, cleanup, fireEvent, queryByTestId, act, queryByPlaceholderText } from '@testing-library/react';
import { query } from 'express';
import axios from 'axios';
import Reviews from '../client/src/components/reviews/Reviews';
import Characteristics from '../client/src/components/reviews/Characteristics';
import ReviewModal from '../client/src/components/reviews/ReviewModal';
import RatingBreakdown from '../client/src/components/reviews/RatingBreakdown';
import InteractiveStars from '../client/src/components/reviews/InteractiveStars';
import ReviewTemplate from '../client/src/components/reviews/ReviewTemplate';
const exampleReviews = [
{
review_id: 288195,
rating: 4,
summary: 'I am liking these glasses',
recommend: false,
response: null,
body: 'They are very dark. But that\'s good because I\'m in very sunny spots',
helpfulness: 2,
reviewer_name: 'bigbrotherbenjamin',
date: '2021-03-05T00:00:00.000Z',
photos: [],
},
{
review_id: 248270,
rating: 4,
summary: 'I am liking these glasses',
recommend: true,
response: 'glad you like it',
body: 'Comfortable and practical.',
helpfulness: 2,
reviewer_name: 'shortandsweeet',
date: '2019-04-14T00:00:00.000Z',
photos: [
{
id: 417326,
url: 'https://images.unsplash.com/photo-1560570803-7474c…hcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=975&q=80'
},
{
id: 417327,
url: 'https://images.unsplash.com/photo-1561693532-9ff59…db?ixlib=rb-1.2.1&auto=format&fit=crop&w=975&q=80'
},
],
},
];
const exampleMetaReviews = {
product_id: '20101',
ratings: {
2: '1',
3: '3',
4: '2',
5: '6',
},
recommended: {
false: '5',
true: '7',
},
characteristics: {
Quality: {
id: 67501,
value: '3.5000000000000000',
},
},
};
describe('Reviews', () => {
it('renders to the page correctly', () => {
const { queryByText } = render(<Reviews />);
expect(queryByText('sort-on-dropdown')).toBeTruthy;
});
});
describe('Characteristics', () => {
it('renders to the page correctly', () => {
const { queryByText } = render(<Characteristics />);
expect(queryByText('characteristic-map')).toBeTruthy;
});
});
describe('Review Modal', () => {
it('renders to the page correctly', () => {
const { queryByText } = render(<ReviewModal />);
expect(queryByText('review-modal')).toBeTruthy;
});
});
describe('Rating Breakdown', () => {
it('renders to the page correctly', () => {
const { queryByText } = render(<RatingBreakdown
reviews={exampleReviews}
metaReviews={exampleMetaReviews}
handleReviewAverage={() => console.log('review average')}
charObject={{
quality: { 1: '1' },
}}
/>);
expect(queryByText('breakdown-render')).toBeTruthy;
});
});
describe('Interactive Stars', () => {
it('renders to the page correctly', () => {
const { getByText } = render(<InteractiveStars review={{ rating: 3 }} setReview={() => console.log('hi')} />);
expect(getByText('hi')).toBeTruthy;
});
});
describe('Review Template', () => {
it('renders to the page correctly', () => {
const { queryByText } = render(<ReviewTemplate review={exampleReviews[0]} />);
expect(queryByText('review-template')).toBeTruthy;
});
});
<file_sep>/client/src/components/qa/AnswerModal.jsx
import axios from 'axios';
import React, { useState } from 'react';
import styles from '../../styleComponents/App.module.css';
import qastyles from '../../styleComponents/QA.modules.css';
import ExpandedPhotos from '../ExpandedPhotos';
function AnswerModal({open, onClose, question_id, getQuestions, productId}) {
const [answer, setAnswer] = useState('');
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [thumbnails, setThumbnails] = useState([]);
const [photos, setPhotos] = useState([]);
const [error, setError] = useState('');
const validEmailRegex = RegExp(
/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i
);
const clearForm = (e) => {
setAnswer('');
setUsername('');
setEmail('');
setThumbnails([]);
setPhotos([]);
};
const toBase64 = (file) => new Promise((resolve, reject) => {
console.log(file);
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
const handleSubmit = (e) => {
e.preventDefault();
let answerInfo = {
body: answer,
name: username,
email: email,
photos: [],
};
if (!validEmailRegex.test(email)) {
setError('*You must enter a valid email');
return;
}
const promises = [];
for (const photo of photos) {
const payload = {
name: photo.name,
data: '',
}
const promise = toBase64(photo)
.then((result) => payload.data = result.split(',')[1])
.then(() => axios.post(`/upload_images`, payload))
.then(({data}) => {return data})
.catch(console.log);
promises.push(promise);
}
Promise.all(promises)
.then((results) => answerInfo.photos = results)
.then(() => {
return axios.post(`/qa/questions/${question_id}/answers`, answerInfo)
})
.then(() => getQuestions(20104))
.then(() => clearForm())
.catch(console.log);
};
const handleChange = (e) => {
console.log(e.target.files[0]);
if (photos.length < 5) {
setPhotos([
...photos,
e.target.files[0],
]);
setThumbnails([
...thumbnails,
URL.createObjectURL(e.target.files[0]),
]);
}
};
return (
<>
<div
onClick={() => {
onClose();
clearForm();
}}
className={open ? styles.overlay : ''}
/>
<div style={{
transform: open ? 'translate(-50%, -50%)' : 'translate(-50%, -150vh)'
}}
className={styles.modal}
>
<div className={styles.modalHeader}>
<h3>Add an Answer</h3>
<p
className={styles.closeModal}
onClick={() => {
onClose();
clearForm();
}}
>
x
</p>
</div>
<div className={styles.modalBody}>
<form encType="multipart/form-data" onSubmit={(e) => handleSubmit(e)} action="">
<p>Your Answer *</p>
<textarea data-testid="answer-input" value={answer} required="required" onChange={(e) => setAnswer(e.target.value)} className={styles.qInput} maxLength="1000" />
<p>What is your nickname? *</p>
<input data-testid="answer-username-input" value={username} required="required" onChange={(e) => setUsername(e.target.value)} className={qastyles.modalInput} type="text" placeholder="Example: jack543!" />
<p className={styles.finePrint}>{username.length > 0 ? 'For privacy reasons, do not use your full name or email address' : ''}</p>
<p>Your Email *</p>
<input data-testid="answer-email-input" value={email} required="required" onChange={(e) => setEmail(e.target.value)} className={qastyles.modalInput} type="text" placeholder="Example: <EMAIL>" />
<p className={styles.finePrint}>{email.length > 0 ? 'For authentication reasons, you will not be emailed' : ''}</p>
<div style={{ height: '60px', display: 'flex', alignItems: 'center' }}>
{photos.length < 5 ? <input data-testid="answer-photo-upload" value="" onChange={handleChange} type="file" /> : null}
{thumbnails.map((photo, idx) => <ExpandedPhotos key={idx} photo={photo} />)}
</div>
<button data-testid="answer-modal-submit-button" type="submit" className={styles.modalButton}>Submit Answer</button>
<p className={styles.finePrint}>{error}</p>
</form>
</div>
</div>
</>
);
}
export default AnswerModal;
<file_sep>/client/src/components/reviews/InteractiveStars.jsx
import React, { useState } from 'react';
import styles from '../../styleComponents/Reviews.module.css';
const InteractiveStars = ({ review, setReview }) => {
const [rating, setRating] = useState(0);
const [hover, setHover] = useState(0);
const [value, setValue] = useState('');
const descriptionObj = {
1: 'Poor',
2: 'Fair',
3: 'Average',
4: 'Good',
5: 'Great',
};
const handleValue = (index) => {
setValue(descriptionObj[index]);
};
return (
<div>
{[...Array(5)].map((star, index) => {
index += 1;
return (
<button
required="required"
name="star"
type="button"
key={index}
className={`${index <= (hover || rating) ? styles.on : styles.off} ${styles.button}`}
onClick={() => {
setRating(index);
handleValue(index);
}}
onMouseEnter={() => {
setRating(rating);
setReview({ ...review, rating: index });
}}
onMouseLeave={() => setHover(rating)}
>
<span data-testid="interactive-stars">★</span>
</button>
);
})}
<p className={styles.comment}>{value}</p>
</div>
);
};
export default InteractiveStars;
<file_sep>/client/src/components/reviews/Reviews.jsx
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import RatingBreakdown from './RatingBreakdown';
import ReviewTemplate from './ReviewTemplate';
import styles from '../../styleComponents/Reviews.module.css';
import ReviewsModal from './ReviewModal';
const Reviews = ({ productId, name, handleReviewAverage }) => {
const [reviews, setReviews] = useState([]);
const [displayedReviews, setDisplayedReviews] = useState([]);
const [metaReviews, setMetaReviews] = useState([]);
const [isOpen, setIsOpen] = useState(false);
const [expanded, setExpanded] = useState(false);
const [sort, setSort] = useState('relevant');
const [moreButton, setMoreButton] = useState('More Reviews');
const charObject = {
Size: {
1: 'A size too small',
2: '1/2 a size too small',
3: 'Perfect',
4: '1/2 a size too big',
5: 'A size too wide',
},
Width: {
1: 'Too narrow',
2: 'Slightly narrow',
3: 'Perfect',
4: 'Slightly wide',
5: 'Too wide',
},
Comfort: {
1: 'Uncomfortable',
2: 'Slightly uncomfortable',
3: 'Ok',
4: 'Comfortable',
5: 'Perfect',
},
Quality: {
1: 'Poor',
2: 'Below average',
3: 'What I expected',
4: 'Pretty great',
5: 'Perfect',
},
Length: {
1: 'Runs short',
2: 'Runs slightly short',
3: 'Perfect',
4: 'Runs slightly long',
5: 'Runs long',
},
Fit: {
1: 'Runs tight',
2: 'Runs slightly tight',
3: 'Perfect',
4: 'Runs slightly long',
5: 'Runs long',
},
};
const getReviews = (id) => {
const reviewsURL = `/reviews/sort/${id}/${sort}`;
axios.get(reviewsURL)
.then(({ data }) => {
setReviews(data);
if (expanded) {
setDisplayedReviews(data);
} else {
setDisplayedReviews(data.slice(0, 2));
}
})
.catch(console.log);
};
const getMetaReviews = (id) => {
const metaReviewsURL = `/reviews/meta/${id}`;
axios.get(metaReviewsURL)
.then(({ data }) => {
setMetaReviews(data);
})
.catch((err) => console.log(err));
};
useEffect(() => {
getReviews(20104);
setExpanded(expanded);
}, [sort]);
useEffect(() => {
getMetaReviews(20104);
getReviews(20104);
}, [productId]);
useEffect(() => {
(expanded)
? setDisplayedReviews(reviews)
: setDisplayedReviews(reviews.slice(0, 2))
}, [expanded]);
const handleStarFilters = (filters) => {
const reviewArray = [];
if (filters.length === 0) {
setDisplayedReviews(reviews.slice(0, 2));
} else {
filters.map((filter) => {
reviews.filter((review) => {
if (review.rating === Number(filter)) reviewArray.push(review);
});
});
setDisplayedReviews(reviewArray);
}
};
const handleMoreButton = () => {
(displayedReviews.length <= 2)
? setMoreButton('More Reviews')
: setMoreButton('Show Less Reviews');
};
useEffect(() => {
handleMoreButton();
}, [displayedReviews]);
return (
(metaReviews && reviews && productId)
? (
<div className={styles.parentContainer}>
<div className={styles.parentBreakdown}>
<RatingBreakdown
reviews={reviews}
metaReviews={metaReviews}
handleStarFilters={handleStarFilters}
handleReviewAverage={handleReviewAverage}
charObject={charObject}
/>
</div>
<div className={styles.parentHeader} style={{ display: 'flex' }}>
<div
style={{ alignSelf: 'center', paddingLeft: '20px' }}
data-testid="sort-on-dropdown"
>
Sort on:
{' '}
<select className={styles.selector} onChange={(e) => setSort(e.target.value)}>
<option>Relevant</option>
<option>Helpful</option>
<option>Newest</option>
</select>
</div>
</div>
<div style={{ maxHeight: '800px', overflowY: 'scroll' }} className={styles.parentIndividualReview}>
{(displayedReviews.length > 0)
? displayedReviews.map((review, id) => (
<ReviewTemplate review={review} key={id} />
))
: <div style={{ paddingLeft: '30px', fontSize: '20px' }}>No reviews for this product</div>}
</div>
<div className={styles.parentFooter}>
{reviews.length > 2
? (
<button
className={styles.footerButton}
type="submit"
onClick={() => {
setExpanded(!expanded);
}}
>
{moreButton}
</button>
)
: null}
<button className={styles.footerButton} type="submit" onClick={() => setIsOpen(true)}>Add Review + </button>
<ReviewsModal
productId={productId}
getReviews={getReviews}
onClose={() => setIsOpen(false)}
open={isOpen}
name={name}
metaReviews={metaReviews}
charObject={charObject}
/>
</div>
</div>
)
: null
);
};
export default Reviews;
<file_sep>/client/src/components/qa/Question.jsx
import React, { useState, useEffect } from 'react';
import Answer from './Answer';
import qastyles from '../../styleComponents/QA.modules.css';
import Helpful from '../Helpful';
import AnswerModal from './AnswerModal';
const Question = (props) => {
const { question, getQuestions, productId } = props;
const { question_body, answers, question_id, question_helpfulness } = question;
const [answerList, setAnswerList] = useState([]);
const [displayedAnswers, setDisplayedAnswers] = useState([]);
const [isOpen, setIsOpen] = useState(false);
const [expanded, setExpanded] = useState(false);
const [seeMoreAnswersText, setSeeMoreAnswersText] = useState('See More Answers');
const sortAnswersBySeller = (answerArr) => {
let sellerMessages = answerArr.filter(answer => answer.answerer_name === 'Seller');
let otherMessages = answerArr.filter(answer => answer.answerer_name !== 'Seller');
return sellerMessages.concat(otherMessages);
};
const sortAnswersByHelpfulness = (answerArr) => {
const length = answerArr.length;
let checked;
do {
checked = false;
for (let i = 0; i < length - 1; i++) {
if (answerArr[i].helpfulness < answerArr[i + 1].helpfulness) {
const tmp = answerArr[i];
answerArr[i] = answerArr[i + 1];
answerArr[i + 1] = tmp;
checked = true;
}
}
} while (checked);
return sortAnswersBySeller(answerArr);
};
useEffect(() => {
const sortedAnswers = sortAnswersByHelpfulness(Object.values(answers));
setAnswerList(sortedAnswers);
}, [question]);
useEffect(() => {
setDisplayedAnswers(answerList.slice(0, 2));
}, [answerList]);
useEffect(() => {
if (expanded) {
setDisplayedAnswers(answerList);
setSeeMoreAnswersText('Collapse Answers');
} else {
setDisplayedAnswers(answerList.slice(0, 2));
setSeeMoreAnswersText('See More Answers');
}
}, [expanded]);
const showMoreAnswers = () => {
setExpanded(!expanded);
};
return (
<div className={qastyles.questionAndAnswer}>
<div className={qastyles.questionGrid}>
<p className={qastyles.q}>Q:</p>
<div className={qastyles.question}>
<p className={qastyles.questionBody} >{question_body}</p>
</div>
<div className={qastyles.questionHelpful}>
<Helpful question_id={question_id} helpfulness={question_helpfulness} />
<button data-testid="add-answer-button" className={qastyles.addAnswerButton} onClick={() => setIsOpen(true)} type="button">Add Answer</button>
</div>
<AnswerModal
productId={productId}
getQuestions={getQuestions}
question_id={question_id}
onClose={() => setIsOpen(false)}
open={isOpen}
/>
</div>
<div className={qastyles.answerGrid}>
<p className={qastyles.a}>A:</p>
<div className={qastyles.answerList}>
{displayedAnswers.map((answer, idx) => <Answer key={idx} answer={answer} />)}
</div>
{answerList.length > 2 ? <button type="button" data-testid="show-more-answers-button" className={qastyles.showMoreAnswersButton} onClick={showMoreAnswers}>{seeMoreAnswersText}</button> : null}
</div>
</div>
);
};
export default Question;
<file_sep>/client/src/components/reviews/ReviewTemplate.jsx
import React, { useState, useEffect } from 'react';
import styles from '../../styleComponents/Reviews.module.css';
import Helpful from '../Helpful';
import ExpandedPhotos from '../ExpandedPhotos';
import StarRating from '../StarRating';
const ReviewTemplate = ({ review }) => {
const starPercentage = (review.rating / 5) * 100;
const roundedPercentage = (Math.round(starPercentage * 5) / 5);
return (
<div>
<div className={styles.reviewTemplate}>
<StarRating average={roundedPercentage} />
<div className={styles.templateSummary}>{review.summary}</div>
<div className={styles.templateBody} style={{ fontSize: '15px' }}>{review.body}</div>
<div className={styles.templateUserDateBar}>
<UserDateBar review={review} />
</div>
<div className={styles.templateHelpfulReportBar}>
<Helpful review_id={review.review_id} helpfulness={review.helpfulness} />
</div>
{(review.response)
? (
<div className={styles.templateResponseFromSeller}>
<p style={{
margin: '0px', fontWeight: 'bolder', padding: '10px 10px 0 10px', fontSize: '15px',
}}
>
Response from seller:
</p>
<p style={{ margin: '0px', padding: '10px', fontSize: '15px' }}>{review.response}</p>
</div>
)
: null}
<div className={styles.templateImages}>
{review.photos.map((photo, id) => <ExpandedPhotos photo={photo} key={id} />)}
</div>
{(review.recommend)
? (
<div className={styles.templateRecommendsBar} style={{ paddingRight: '10px', fontSize: '12px' }}>
✓ Yes, I recommend this product
</div>
)
: null}
</div>
</div>
);
};
const UserDateBar = ({ review }) => {
const getDate = (date) => {
const dateArr = date.slice(0, date.indexOf('T')).split('-');
const year = dateArr.shift();
dateArr.push(year);
return dateArr.join('-');
};
const date = getDate(review.date);
return (
<div className={styles.userDateBar}>
<span style={{ fontSize: 10, fontStyle: 'italic', paddingRight: '7px' }}>✓ Verified Purchaser</span>
<div className={styles.userDateBar}>
{review.reviewer_name}
{' '}
{date}
</div>
</div>
);
};
export default ReviewTemplate;
<file_sep>/client/src/components/overview/OverviewRatingsDisplay.jsx
import React from 'react';
import styles from '../../styleComponents/Overview.module.css';
import StarRating from '../StarRating';
const ReviewStars = (props) => {
const { average } = props;
const inputRef = document.getElementById('scrollTarget');
const handleClick = () => {
if (inputRef !== null) {
inputRef.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
}
};
return (
<>
<StarRating average={average} />
<button type="submit" className={styles.reviewsButton} ref={inputRef} onClick={handleClick}>Read all reviews</button>
</>
);
};
export default ReviewStars;
<file_sep>/client/src/components/Helpful.jsx
import React, { useState } from 'react';
import { Icon } from '@iconify/react';
import flagSolid from '@iconify-icons/clarity/flag-solid';
import axios from 'axios';
import styles from '../styleComponents/App.module.css';
const Helpful = (props) => {
const { helpfulness } = props;
const [count, setCount] = useState(helpfulness);
const [reported, setReported] = useState('Report');
const [isReported, setIsReported] = useState(false);
const handleCount = (e) => {
setCount(helpfulness + 1);
if (props.review_id) {
const { review_id } = props;
axios.put(`/reviews/${review_id}/helpful`)
.then((status) => console.log(status.status))
.catch((err) => console.log(err));
} else if (props.question_id) {
const { question_id } = props;
axios.put(`/qa/questions/${question_id}/helpful`)
.then((status) => console.log(status.status))
.catch((err) => console.log(err));
} else if (props.answer_id) {
const { answer_id } = props;
axios.put(`/qa/answers/${answer_id}/helpful`)
.then((status) => console.log(status.status))
.catch((err) => console.log(err));
}
};
const report = () => {
setReported('Reported');
setIsReported(true);
if (props.answer_id) {
axios.put(`/qa/answers/${props.answer_id}/report`)
.then(() => console.log(status.status))
.catch(console.log);
} else if (props.review_id) {
axios.put(`/reviews/${props.review_id}/report`)
.then(() => console.log(status.status))
.catch(console.log);
} else {
axios.put(`/qa/questions/${props.question_id}/report`)
.then(() => console.log(status.status))
.catch(console.log);
}
};
return (
<div className={styles.helpful}>
<div data-testid="helpfulText" className={styles.helpful}>Was this helpful?</div>
<button data-testid="helpful-button" type="submit" onClick={handleCount} className={styles.helpfulButton} value="yes">Yes</button>
<div data-testid="helpful-count" className={`${styles.helpful} ${styles.helpfulCount}`}>
(
{count}
)
{' '}
</div>
<button data-testid="report-button" className={isReported ? styles.reportedTrue : styles.reported} onClick={report} type="submit">{reported}</button>
{isReported ? <Icon className={styles.flag} icon={flagSolid} /> : null}
</div>
);
};
export default Helpful;
<file_sep>/client/src/components/qa/QA.jsx
import React, { useEffect, useState } from 'react';
import qastyles from '../../styleComponents/QA.modules.css';
import QASearchBar from './QASearchBar.jsx'
import Question from './Question';
import QuestionModal from './QuestionModal';
import axios from 'axios';
const QA = (props) => {
const [isOpen, setIsOpen] = useState(false);
const { productId, name } = props;
const [questions, setQuestions] = useState([]);
const [displayedQuestions, setDisplayedQuestions] = useState([]);
const [expanded, setExpanded] = useState(false);
const [searching, setSearching] = useState(false);
const [moreQuestionsButton, setMoreQuestionsButton] = useState('More Answered Questions');
const sortQuestions = (questionArr) => {
const length = questionArr.length;
let checked;
do {
checked = false;
for (let i = 0; i < length - 1; i++) {
if (questionArr[i].question_helpfulness < questionArr[i + 1].question_helpfulness) {
const tmp = questionArr[i];
questionArr[i] = questionArr[i + 1];
questionArr[i + 1] = tmp;
checked = true;
}
}
} while (checked);
return questionArr;
};
const getQuestions = (id) => {
axios.get(`/qa/questions/${id}`)
.then((results) => {
const sorted = sortQuestions(results.data);
setQuestions(sorted);
setMoreQuestionsButton('More Answered Questions');
setDisplayedQuestions(sorted.slice(0, 4));
})
.catch(console.log);
};
useEffect(() => {
getQuestions(20104);
}, []);
useEffect(() => {
if (expanded) {
setDisplayedQuestions(questions);
setMoreQuestionsButton('Show Less Questions');
} else {
setDisplayedQuestions(questions.slice(0, 4));
setMoreQuestionsButton('More Answered Questions');
}
}, [expanded]);
const increaseNumOfQuestions = () => {
setExpanded(!expanded);
};
const searchQuestions = (value) => {
if (value.length >= 3) {
setSearching(true);
const found = questions.filter(
(question) => question.question_body.toLowerCase().includes(value.toLowerCase())
);
setDisplayedQuestions(found);
} else if (expanded) {
setSearching(false);
setDisplayedQuestions(questions);
} else {
setSearching(false);
setDisplayedQuestions(questions.slice(0, 4));
}
};
return (
<div className={qastyles.border}>
<div className={qastyles.headerBox}>
<h2 data-testid="qa-heading" className={qastyles.qaheader}>Questions & Answers</h2>
</div>
<div className={qastyles.search}>
<QASearchBar searchQuestions={searchQuestions} />
{questions.length === 0 ? <button type="submit" data-testid="add-a-question-button" className={qastyles.footerButton} onClick={() => setIsOpen(true)}>Add A Question + </button> : null}
</div>
<div className={qastyles.qaSection}>
{displayedQuestions.map(
(question, idx) => (
<Question
key={idx}
productId={productId}
getQuestions={getQuestions}
question={question}
/>
),
)}
</div>
<div className={qastyles.buttons}>
{searching ? null : <button type="submit" data-testid="show-more-questions-button" className={qastyles.footerButton} onClick={increaseNumOfQuestions} >{moreQuestionsButton}</button>}
{questions.length > 0 ? <button type="submit" data-testid="add-a-question-button" className={qastyles.footerButton} onClick={() => setIsOpen(true)}>Add A Question + </button> : null}
<QuestionModal
name={name}
productId={productId}
getQuestions={getQuestions}
onClose={() => setIsOpen(false)}
open={isOpen}
/>
</div>
</div>
);
};
export default QA;
<file_sep>/client/src/components/reviews/ReviewModal.jsx
import axios from 'axios';
import React, { useState, useEffect } from 'react';
import Rstyles from '../../styleComponents/Reviews.module.css';
import styles from '../../styleComponents/App.module.css';
import Characteristics from './Characteristics';
import InteractiveStars from './InteractiveStars';
const ReviewsModal = ({
productId, onClose, open, getReviews, name, metaReviews, charObject
}) => {
const [review, setReview] = useState({
product_id: productId,
rating: '',
summary: '',
body: '',
recommend: '',
name: '',
email: '',
photos: [],
characteristics: {},
});
const [thumbnails, setThumbnails] = useState([]);
const [error, setError] = useState({
email: '',
photoSize: '',
missingFields: '',
});
const [characterCount, setCharacterCount] = useState(50);
const validEmailRegex = RegExp(
/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i
);
const toBase64 = (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
const handleSubmit = (e) => {
e.preventDefault();
const finalReview = { ...review };
if (!validEmailRegex.test(finalReview.email)) {
setError({ ...error, email: '*You must enter a valid email' });
setReview({ ...review, email: '' });
return;
}
if (finalReview.photos.length === 0) {
axios.post('/reviews', finalReview)
.then(() => getReviews(productId))
.then(() => onClose())
.catch((err) => console.log(err));
} else {
const promises = [];
finalReview.photos.map((photo) => {
if (photo.size > 100000) {
setError({ ...error, photoSize: '*The images selected are invalid or unable to be uploaded' });
return;
}
const payload = {
name: photo.name,
data: '',
};
const promise = toBase64(photo)
.then((result) => payload.data = result.split(',')[1])
.then(() => axios.post('/upload_images', payload))
.then(({ data }) => data)
.catch(console.log);
promises.push(promise);
});
Promise.all(promises)
.then((results) => {
finalReview.photos = results;
})
.then(() => axios.post('/reviews', finalReview))
.then(() => getReviews(productId))
.then(() => onClose())
.catch((err) => console.log(err));
}
};
const handleCountChange = (e) => {
const { value } = e.target;
setCharacterCount(50 - value.length);
};
const handleChange = (e) => {
if (review.photos.length < 5) {
setReview({
...review,
photos: [...review.photos, e.target.files[0]],
});
setThumbnails([
...thumbnails,
URL.createObjectURL(e.target.files[0]),
]);
}
};
return (
(metaReviews && review && review.photos)
? (
<>
<div
style={{ maxHeight: '100%' }}
role="presentation"
onClick={() => {
onClose();
}}
className={open ? styles.overlay : ''}
/>
<div
style={{
transform: open ? 'translate(-50%, -50%)' : 'translate(-50%, -150vh)',
}}
className={styles.modal}
>
<div className={styles.modalHeader}>
<p style={{ fontSize: '18px' }}>Write Your Review</p>
<p>
About the {name}
...
</p>
<p
data-testid="review-modal"
role="presentation"
className={styles.closeModal}
onClick={() => {
onClose();
}}
>
x
</p>
</div>
<div className={styles.modalBody}>
<form
onSubmit={(e) => {
handleSubmit(e);
}}
action=""
encType="multipart/form-data"
style={{ fontSize: '12px' }}
>
<p style={{ margin: '5px' }}>Overall Rating: *</p>
<span className={Rstyles.starRating}>
<InteractiveStars review={review} setReview={setReview} />
</span>
<p>Would you recommend this product? *</p>
<div>
<input type="radio" id="Yes" name="recommend" required="required" onClick={() => setReview({ ...review, recommend: true })} />
<label htmlFor="Yes">Yes</label>
<input type="radio" id="No" name="recommend" onClick={() => setReview({ ...review, recommend: false })} />
<label htmlFor="No">No</label>
</div>
<Characteristics
characteristics={metaReviews.characteristics}
charObject={charObject}
setReview={setReview}
review={review}
/>
<p>Review Title:</p>
<input
onChange={(e) => setReview({ ...review, summary: e.target.value })}
className={Rstyles.modalInput}
maxLength="60"
placeholder="Example: Best purchase ever!"
type="text"
style={{ fontSize: '12px' }}
/>
<p>Review Body: *</p>
<textarea
required="required"
onChange={(e) => {
setReview({ ...review, body: e.target.value });
handleCountChange(e);
}}
minLength="50"
maxLength="1000"
className={styles.qInput}
placeholder="Why did you like the product or not?"
type="text"
/>
<p
className={Rstyles.comment}
>
{characterCount <= 0 ? 'Minimum Characters Reached' : `Minimum required characters left: ${characterCount}`}
</p>
<p>What is your nickname? *</p>
<input
required="required"
onChange={(e) => setReview({ ...review, name: e.target.value })}
className={Rstyles.modalInput}
maxLength="60"
type="text"
placeholder="Example: jackson11!"
style={{ fontSize: '12px' }}
/>
<p className={styles.finePrint}>{review.name.length > 0 ? 'For privacy reasons, do not use your full name or email address' : ''}</p>
<p>What is your email? *</p>
<input
required="required"
onChange={(e) => setReview({ ...review, email: e.target.value })}
className={Rstyles.modalInput}
maxLength="60"
type="text"
placeholder="Example: <EMAIL>"
style={{ fontSize: '12px' }}
/>
<p className={styles.finePrint}>{review.email.length > 0 ? 'For authentication reasons, you will not be emailed' : ''}</p>
<div />
<div>
{review.photos.length < 5 ? <input value="" onChange={handleChange} type="file" /> : null}
{thumbnails.map((photo) => <img alt={photo} key={photo} className={`${Rstyles.imgThumbnail} ${Rstyles.reviewPhoto}`} src={photo} />)}
</div>
<p className={Rstyles.comment}>* Mandatory Fields</p>
<p className={styles.finePrint}>{error.email}</p>
<p className={styles.finePrint}>{error.photoSize}</p>
<button
type="submit"
className={styles.modalButton}
>
Submit Review
</button>
</form>
</div>
</div>
</>
)
: null
);
};
export default ReviewsModal;
<file_sep>/__tests__/QA.test.jsx
import React from 'react';
import { render, screen, cleanup, fireEvent, queryByTestId, act, queryByPlaceholderText } from '@testing-library/react';
import QA from '../client/src/components/qa/QA';
import Question from '../client/src/components/qa/Question';
import QASearchBar from '../client/src/components/qa/QASearchBar';
import Answer from '../client/src/components/qa/Answer';
import AnswerModal from '../client/src/components/qa/AnswerModal';
import QuestionModal from '../client/src/components/qa/QuestionModal';
import axios from 'axios';
const questions = [
{
question_body: 'First Question',
question_helpfulness: 33,
answers: {
first:
{
body: 'Answer 1',
photos: ["https://images.unsplash.com/photo-1542818212-9899bafcb9db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1526&q=80"],
date: "2020-11-13T00:00:00.000Z",
},
second:
{
body: 'Answer 2',
photos: [],
date: "2020-11-13T00:00:00.000Z",
},
third:
{
body: 'Answer 3',
photos: [],
date: "2020-11-13T00:00:00.000Z",
},
},
},
{
question_body: 'Second Question',
question_helpfulness: 7,
answers: {},
},
];
beforeEach(() => {
axios.get = jest.fn(() =>
Promise.resolve({
data: Promise.resolve(questions),
}),
);
});
describe('QA Section', () => {
it('renders to the page properly', () => {
const { queryByText } = render(<QA />);
expect(queryByText('qa-heading')).toBeTruthy;
});
it('Should trigger a modal popup', () => {
const { queryByTestId, queryByPlaceholderText } = render(<QA questions={questions} />);
const addAQuestion = queryByTestId('add-a-question-button');
fireEvent.click(addAQuestion);
expect(queryByPlaceholderText('Example: jack543!')).toBeTruthy;
});
it('Should show more questions when clicking the "show more questions" button', () => {
const { queryByTestId } = render(<QA questions={questions} />);
const showMoreQuestions = queryByTestId('show-more-questions-button');
fireEvent.click(showMoreQuestions);
expect(showMoreQuestions.textContent).toBe('Show Less Questions');
});
});
describe('Search Bar', () => {
it('Should properly change the input value', () => {
const { queryByTestId } = render(<QASearchBar searchQuestions={() => console.log('Searching!')} />);
const searchBar = queryByTestId('search-input');
fireEvent.change(searchBar, { target: { value: 'I am a question' } });
expect(searchBar.value).toBe('I am a question');
});
it('Should search for a question', () => {
const { queryByTestId, queryByText } = render(<QA questions={questions} />);
const searchBar = queryByTestId('search-input');
fireEvent.change(searchBar, { target: { value: 'First Question' } });
expect(queryByText('First Question')).toBeTruthy;
});
});
describe('Question Section', () => {
it('renders to the page properly', () => {
const { queryByText } = render(<Question question={questions[0]} />);
expect(queryByText('add-answer-button')).toBeTruthy;
});
it('Should show more answers upon clicking the "show more answers button"', () => {
const { queryByTestId, queryByText } = render(<Question question={questions[0]} />);
const showMoreAnswersButton = queryByTestId('show-more-answers-button');
expect(queryByText('Answer 3')).toBeFalsy;
fireEvent.click(showMoreAnswersButton);
expect(queryByText('Answer 3')).toBeTruthy;
});
it('should open an answer modal', () => {
const { queryByTestId, queryByPlaceholderText } = render(<Question question={questions[0]} />);
const addAnswerButton = queryByTestId('show-more-answers-button');
fireEvent.click(addAnswerButton);
expect(queryByPlaceholderText('Example: jack543!')).toBeTruthy;
});
});
describe('Answer Section', () => {
it('Should properly render to the page', () => {
const { queryByText } = render(<Answer answer={questions[0].answers.first} />);
expect(queryByText('Answer 1')).toBeTruthy;
});
});
describe('Answer Modal', () => {
it('Should properly render to the page', () => {
const { queryByTestId, queryByText, queryByPlaceholderText } = render(<AnswerModal />);
const answerInput = queryByTestId('answer-input');
const answerUsernameInput = queryByTestId('answer-username-input');
const answerEmailInput = queryByTestId('answer-email-input');
const answerPhotoUpload = queryByTestId('answer-photo-upload');
const submit = queryByTestId('answer-modal-submit-button');
fireEvent.change(answerInput, { target: { value: 'I\'m a new answer!' } });
fireEvent.change(answerUsernameInput, { target: { value: 'tester' } });
fireEvent.change(answerEmailInput, { target: { value: '<EMAIL>' } });
// fireEvent.change(answerPhotoUpload, new File([{name: "blob:http://localhost:3000/59643764-7b4b-48f5-8ac1-61183a042cbe"}], 'foo.txt'));
fireEvent.click(submit);
expect(queryByText('I\'m a new answer!')).toBeTruthy;
});
});
describe('Question Modal', () => {
it('Should properly submit data and render it to the page', () => {
const { queryByTestId, queryByText, queryByPlaceholderText } = render(<QuestionModal productId={11111} />);
const questionInput = queryByTestId('question-input');
const questionUsernameInput = queryByTestId('question-username-input');
const questionEmailInput = queryByTestId('question-email-input');
const submit = queryByTestId('question-modal-submit-button');
fireEvent.change(questionInput, { target: { value: 'I\'m a new question!' } });
fireEvent.change(questionUsernameInput, { target: { value: 'tester' } });
fireEvent.change(questionEmailInput, { target: { value: '<EMAIL>' } });
// fireEvent.change(answerPhotoUpload, new File([{name: "blob:http://localhost:3000/59643764-7b4b-48f5-8ac1-61183a042cbe"}], 'foo.txt'));
fireEvent.click(submit);
expect(queryByText('I\'m a new question!')).toBeTruthy;
});
it('Should properly clear the form upon clicking away from the modal', () => {
const { queryByTestId } = render(<QuestionModal onClose={() => console.log('closed')} productId={11111} />);
const questionInput = queryByTestId('question-input');
const questionUsernameInput = queryByTestId('question-username-input');
const questionEmailInput = queryByTestId('question-email-input');
const overlay = queryByTestId('question-overlay');
// fireEvent.change(questionInput, { target: { value: 'I\'m a new question!' } });
fireEvent.change(questionUsernameInput, { target: { value: 'tester' } });
fireEvent.change(questionEmailInput, { target: { value: '<EMAIL>' } });
fireEvent.click(overlay);
// expect(questionInput.textContent).toBe('');
expect(questionUsernameInput.textContent).toBe('');
expect(questionEmailInput.textContent).toBe('');
});
});<file_sep>/client/src/components/overview/OverviewMainDisplay.jsx
import React, { useState, useEffect, useRef } from 'react';
import styles from '../../styleComponents/Overview.module.css';
import OverviewExpandedModal from './OverviewExpandedModal';
const MainDisplay = (props) => {
const { photos, styleChoice } = props;
const [mainGallery, setMainGallery] = useState([]);
const [thumbnailGallery, setThumbnailGallery] = useState([]);
const [imgIndex, setImgIndex] = useState(0);
const [displayedImg, setDisplayedImg] = useState('');
const [isOpen, setIsOpen] = useState(false);
const moveThumbnails = useRef();
useEffect(() => {
const thumbnails = [];
const normal = [];
for (let i = 0; i < photos.length; i++) {
thumbnails.push(photos[i].thumbnail_url);
normal.push(photos[i].url);
}
setMainGallery(normal);
setThumbnailGallery(thumbnails);
setDisplayedImg(normal[imgIndex]);
}, [photos]);
useEffect(() => {
setDisplayedImg(mainGallery[imgIndex]);
}, [imgIndex]);
const decrementImgIndex = (event) => {
event.preventDefault();
setImgIndex(imgIndex - 1);
};
const incrementImgIndex = (event) => {
event.preventDefault();
setImgIndex(imgIndex + 1);
};
const expandView = (event) => {
event.preventDefault();
if (event.key === 'Enter' || event.key === 'Space bar') {
setIsOpen(true);
setDisplayedImg(mainGallery[imgIndex]);
}
setIsOpen(true);
setDisplayedImg(mainGallery[imgIndex]);
};
const onClose = (event) => {
event.preventDefault();
if (event.key === 'Enter' || event.key === 'Space bar') {
setIsOpen(false);
}
setIsOpen(false);
};
const thumbnailClickHandler = (event) => {
event.preventDefault();
const displayedImgIndex = thumbnailGallery.indexOf(event.target.src);
setImgIndex(displayedImgIndex);
};
const slideDown = () => {
if (imgIndex > 5) {
const num = -56 * (imgIndex - 5);
const pixels = num + 'px';
moveThumbnails.current.style.top = pixels;
}
setImgIndex(imgIndex === thumbnailGallery.length - 1 ? 0 : imgIndex + 1);
};
const slideUp = () => {
if (imgIndex > 5) {
const num = -56 * (imgIndex - 6);
const pixels = num + 'px';
moveThumbnails.current.style.top = pixels;
}
setImgIndex(imgIndex === 0 ? thumbnailGallery.length - 1 : imgIndex - 1);
};
return (
<>
<div className={styles.photoGrid}>
{imgIndex !== 0 && (<button type="submit" aria-label="Previous image" className={styles.mainDisplayButtonLeft} onClick={decrementImgIndex}>‹</button>)}
<div className={styles.mainDisplay}>
<img
className={styles.img}
tabIndex={0}
role="tablist"
src={displayedImg}
onClick={expandView}
onKeyDown={expandView}
alt={styleChoice}
/>
<OverviewExpandedModal open={isOpen} close={onClose} displayedImg={displayedImg}>
<img role="tab" src={displayedImg} alt={styleChoice} />
</OverviewExpandedModal>
</div>
{imgIndex !== mainGallery.length - 1 && (<button type="submit" aria-label="Next image" className={styles.mainDisplayButtonRight} onClick={incrementImgIndex}>›</button>)}
</div>
{imgIndex !== 0 && (
<button type="submit" aria-label="Previous thumbnail" className={styles.upButton} onClick={slideUp}>
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
<path d="M7.247 4.86l-4.796 5.481c-.566.647-.106 1.659.753 1.659h9.592a1 1 0 0 0 .753-1.659l-4.796-5.48a1 1 0 0 0-1.506 0z" />
</svg>
</button>
)}
<div className={styles.slider}>
<div ref={moveThumbnails} className={styles.thumbnailContainer}>
{thumbnailGallery.map((img, index) => <input type="image" key={index} onClick={thumbnailClickHandler} src={img} className={styles.thumbnailImg} alt={styleChoice} />)}
</div>
</div>
{imgIndex !== mainGallery.length - 1 && (
<button type="submit" aria-label="Next thumbnail" className={styles.downButton} onClick={slideDown}>
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
<path d="M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z" />
</svg>
</button>
)}
</>
);
};
export default MainDisplay;
|
386aec3cfa111bef73648e0b5e34e9ae455a0bf8
|
[
"JavaScript",
"Markdown"
] | 22 |
JavaScript
|
Project-Catwalk/Wallace-Corporation
|
3195c9de9e8298906885db8aaec58a3c7adc6212
|
2818eb416c988c24f51416069aea9691a26581b2
|
refs/heads/master
|
<file_sep>import { HttpClient } from '@angular/common/http';
import { User } from './../user';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-form-demo',
templateUrl: './form-demo.component.html',
styleUrls: ['./form-demo.component.css'],
encapsulation: ViewEncapsulation.None,
})
export class FormDemoComponent implements OnInit {
userForm: FormGroup;
submitted = false;
websiteId = 1;
LanguageID= 2;
feedbackType= 1;
constructor(private formBuilder: FormBuilder, private user:User , private HttpClient:HttpClient) { }
ngOnInit() {
this.userForm = this.formBuilder.group({
'firstName': [this.user.firstName, [Validators.required]],
'lastName': [this.user.lastName, [Validators.required]],
'email': [this.user.email, [Validators.required, Validators.email]],
'age': [this.user.age, [Validators.required]],
'phone':[this.user.phone, [Validators.required]],
'Nationality': [this.user.Nationality, [Validators.required]],
'placeofResidency': [this.user.placeofResidency, [Validators.required]],
'Organization':[this.user.Organization, [Validators.required]],
'job':[this.user.job, [Validators.required]],
'type':[this.user.type, [Validators.required]],
'subject':[this.user.subject, [Validators.maxLength(20)]],
'message':[this.user.message, [Validators.maxLength(45)]]
});
}
get registerFormControl() {
return this.userForm.controls;
}
// onSubmit() {
// this.submitted = true;
// if (this.userForm.valid) {
// alert('Form Submitted succesfully!!!\n Check the values in browser console.');
// console.table(this.userForm.value);
// }
// }
submitFeedback() {
this.submitted = true;
if (this.userForm.valid) {
alert('Form Submitted succesfully!!!\n Check the values in browser console.');
console.table(this.userForm.value);
}
this.HttpClient.get("http://demoserver.tacme.net:3030/MOICDTacsoft/services/FeedbackRestService.svc/SubmitFeedback?"
+"WebsiteID=this.websiteId&LanguageID=this.LanguageID&Name=this.userForm.controls['firstNmae'].value&Email=this.userForm.controls['email'].value&PhoneNumber=this.userForm.controls['phone'].value&Age=this.userForm.controls['age'].value&Organization=this.userForm.controls['Organization'].value"+
"Nationality=this.userForm.controls['Nationality'].value&Residency=this.userForm.controls['placeofResidency'].value&Subject=this.userForm.controls['subject'].value&message=this.userForm.controls['message'].value&feedbackType=this.feedbackType" ).subscribe(
(res: any) => {
console.log(res);
},
err => {
console.log(err);
})
}
}
<file_sep>export class User {
firstName: string;
lastName: string;
email: string;
phone: string;
age: number;
Nationality: string;
placeofResidency: string;
Organization: string;
job: string;
type: string;
subject: string;
message: string
}<file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
apiUrl:"http://demoserver.tacme.net:3030/MOICDTacsoft/services/FeedbackRestService.svc/SubmitFeedback?WebsiteID=1&LanguageID=2&Name=%20&Email=&PhoneNumber=&Age=%20Years&Organization=&Occupation=&Nationality=292&Residency=292&Subject=fgjhfgjghjghjgh&message=gsdfgfjgxmkxgjcgfj&feedbackType=1"
constructor() { }
}
<file_sep>import { DataService } from './services/data.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { User } from './user';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateService } from "@ngx-translate/core";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormDemoComponent } from './form-demo/form-demo.component';
import { NavbarComponent } from './navbar/navbar.component';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatButtonModule} from '@angular/material/button';
@NgModule({
declarations: [
AppComponent,
FormDemoComponent,
NavbarComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatToolbarModule,
MatButtonModule,
ReactiveFormsModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [TranslateService, User,DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
|
fccdf5fb665d6590cca83f04bec8c64b11279256
|
[
"TypeScript"
] | 4 |
TypeScript
|
reemhosny/angularFormDemo
|
37e9859de81047a8dda7ffdf7a120902daaa864b
|
b2ef60dbba77727127e8cef6f4440e9254657be4
|
refs/heads/master
|
<repo_name>honghuixixi/aek-repair-service<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepRepairBillCheckFlowResponse.java
package com.aek.ebey.repair.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 维修单据流程详情实体类
*
* @author HongHui
* @date 2018年1月26日
*/
@ApiModel(value = "RepRepairBillCheckFlowResponse", description = "维修单据流程详情数据")
public class RepRepairBillCheckFlowResponse {
@ApiModelProperty(value="审批结果")
private String checkResult;
@ApiModelProperty(value="备注")
private String checkRemark;
public String getCheckResult() {
return checkResult;
}
public void setCheckResult(String checkResult) {
this.checkResult = checkResult;
}
public String getCheckRemark() {
return checkRemark;
}
public void setCheckRemark(String checkRemark) {
this.checkRemark = checkRemark;
}
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairMessageServiceImpl.java
package com.aek.ebey.repair.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aek.common.core.base.BaseServiceImpl;
import com.aek.ebey.repair.inter.MessageStatus;
import com.aek.ebey.repair.mapper.RepMessageReceiveMapper;
import com.aek.ebey.repair.mapper.RepRepairMessageMapper;
import com.aek.ebey.repair.model.RepMessageReceive;
import com.aek.ebey.repair.model.RepRepairMessage;
import com.aek.ebey.repair.request.SendMessage;
import com.aek.ebey.repair.service.RepRepairMessageService;
/**
* <p>
* 消息表 服务实现类
* </p>
*
* @author aek
* @since 2017-08-30
*/
@Service
@Transactional
public class RepRepairMessageServiceImpl extends BaseServiceImpl<RepRepairMessageMapper, RepRepairMessage> implements RepRepairMessageService {
@Autowired
private RepRepairMessageMapper repRepairMessageMapper;
@Autowired
private RepMessageReceiveMapper repMessageReceiveMapper;
@Override
public void save(SendMessage sendMessage) {
RepRepairMessage repRepairMessage = new RepRepairMessage();
repRepairMessage.setModuleId(sendMessage.getModuleId());
repRepairMessage.setMessageContent(sendMessage.getMessageContent());
repRepairMessage.setRemarks(sendMessage.getRemarks());
repRepairMessage.setStatus(sendMessage.getStatus());
repRepairMessageMapper.insert(repRepairMessage);
RepMessageReceive repMessageReceive = new RepMessageReceive();
repMessageReceive.setMessageId(repRepairMessage.getId());
repMessageReceive.setMessageStatus(MessageStatus.UNWATCH);
repMessageReceive.setUserId(sendMessage.getUserId());
repMessageReceiveMapper.insert(repMessageReceive);
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepRepairReportResponse.java
package com.aek.ebey.repair.request;
import java.util.List;
import com.aek.ebey.repair.model.RepPartsRecord;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepRepairReportResponse", description = "维修报告单Response")
public class RepRepairReportResponse {
@ApiModelProperty(value="维修方式")
private String modeStatusName;
/**
* 外修单位
*/
@ApiModelProperty(value="外修单位")
private String outsideCompany;
/**
* 外修电话
*/
@ApiModelProperty(value="外修电话")
private String outsidePhone;
/**
* 故障现象(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="故障现象(自定义单独拼接成串,格式1,2,3,电源问题)")
private List<String> faultPhenomenonList;
/**
* 故障原因(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="故障原因(自定义单独拼接成串,格式1,2,3,电源问题)")
private List<String> faultReasonList;
/**
* 工作内容(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="工作内容(自定义单独拼接成串,格式1,2,3,电源问题)")
private List<String> workContentList;
@ApiModelProperty(value="关联配件")
private List<RepPartsRecord> list;
public String getModeStatusName() {
return modeStatusName;
}
public void setModeStatusName(String modeStatusName) {
this.modeStatusName = modeStatusName;
}
public String getOutsideCompany() {
return outsideCompany;
}
public void setOutsideCompany(String outsideCompany) {
this.outsideCompany = outsideCompany;
}
public String getOutsidePhone() {
return outsidePhone;
}
public void setOutsidePhone(String outsidePhone) {
this.outsidePhone = outsidePhone;
}
public List<String> getFaultPhenomenonList() {
return faultPhenomenonList;
}
public void setFaultPhenomenonList(List<String> faultPhenomenonList) {
this.faultPhenomenonList = faultPhenomenonList;
}
public List<String> getFaultReasonList() {
return faultReasonList;
}
public void setFaultReasonList(List<String> faultReasonList) {
this.faultReasonList = faultReasonList;
}
public List<String> getWorkContentList() {
return workContentList;
}
public void setWorkContentList(List<String> workContentList) {
this.workContentList = workContentList;
}
public List<RepPartsRecord> getList() {
return list;
}
public void setList(List<RepPartsRecord> list) {
this.list = list;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/ribbon/UserPermissionService.java
package com.aek.ebey.repair.service.ribbon;
import java.util.List;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.aek.common.core.Result;
import com.aek.ebey.repair.model.vo.RepConfigDeptVo;
import com.aek.ebey.repair.model.vo.RepUserVo;
@FeignClient(value="${feign-sys.serviceId}",fallback = UserPermissionHystrix.class)
public interface UserPermissionService {
@RequestMapping(method = RequestMethod.GET,value = "/sys/invoke/user/tenant/{tenantId}/permission/{permissionCode}")
public Result<List<Long>> findByTenantAndCanPermiss(
@PathVariable(value = "tenantId", required = true) String tenantId,
@PathVariable(value = "permissionCode", required = true) String permissionCode,@RequestHeader("X-AEK56-Token") String token) ;
/**
* 根据部门id查询子部门集合
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/invoke/dept/{deptId}/sub")
public Result<String> findAllSubDeptById(@PathVariable(value = "deptId", required = true) Long deptId,
@RequestHeader("X-AEK56-Token") String token);
/**
* 校验是否有维修权限和是否停用
* @param id
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/checkIsRep")
public Result<Integer> checkIsRep(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 校验是否有审批单据权限和是否停用
* @param id
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/checkIsRepBill")
public Result<Integer> checkIsRepBill(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 校验是否有接单权限和是否停用
* @param id
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/checkIsRepHelp")
public Result<Integer> checkIsRepHelp(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 根据机构Id获取本机构具有接单权限的用户列表
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/getTakeOrderUserList")
public Result<List<RepUserVo>> getTakeOrderUserList(@RequestHeader("X-AEK56-Token") String token);
/**
* 根据机构Id获取本机构具有维修权限的用户列表
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/getRepairUserList")
public Result<List<RepUserVo>> getRepairUserList(@RequestHeader("X-AEK56-Token") String token);
/**
* 查询机构里启用未删除的部门
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/dept/getDeptList")
public Result<List<RepConfigDeptVo>> getDeptList(@RequestParam(value = "keyword", required = false) String keyword,@RequestHeader("X-AEK56-Token") String token);
/**
* 查询机构里启用未删除的部门
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/dept/getAllDeptList")
public Result<List<RepConfigDeptVo>> getAllDeptList(@RequestParam(value = "keyword", required = false) String keyword,@RequestHeader("X-AEK56-Token") String token);
/**
* 查询用户信息
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/invoke/user/getUser")
public Result<RepUserVo> getUser(@RequestParam(value = "id", required = true) Long id,@RequestParam(value = "tenantId", required = true) Long tenantId,@RequestHeader("X-AEK56-Token") String token);
/**
* 校验用户是否具有审核报损单权限
* @param id
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/checkIsDiscard")
public Result<Boolean> checkIsDiscard(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 校验用户是否具有审核转科单权限
* @param id
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/checkIsTransfer")
public Result<Boolean> checkIsTransfer(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 校验用户是否具有审核转科单权限
* @param id
* @param token
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/sys/user/checkIsRht")
public Result<Boolean> checkIsRht(@RequestParam(value = "id", required = true) Long id,@RequestParam(value = "rht", required = true) String rht,
@RequestHeader("X-AEK56-Token") String token);
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepTurnOrders.java
package com.aek.ebey.repair.model;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 转单表
* </p>
*
* @author aek
* @since 2018-01-11
*/
@TableName("rep_turn_orders")
public class RepTurnOrders extends BaseModel {
private static final long serialVersionUID = 1L;
/**
*
*/
private Long id;
/**
* 关联维修单id
*/
@TableField(value="apply_id")
private Long applyId;
/**
* 转单人id
*/
@TableField(value="from_id")
private Long fromId;
/**
* 转单人姓名
*/
@TableField(value="from_name")
private String fromName;
/**
* 接单人id
*/
@TableField(value="to_id")
private Long toId;
/**
* 接单人姓名
*/
@TableField(value="to_name")
private String toName;
/**
* 转单时间
*/
@TableField(value="turn_time")
private Date turnTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public Long getFromId() {
return fromId;
}
public void setFromId(Long fromId) {
this.fromId = fromId;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public Long getToId() {
return toId;
}
public void setToId(Long toId) {
this.toId = toId;
}
public String getToName() {
return toName;
}
public void setToName(String toName) {
this.toName = toName;
}
public Date getTurnTime() {
return turnTime;
}
public void setTurnTime(Date turnTime) {
this.turnTime = turnTime;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepRepairConfig.java
package com.aek.ebey.repair.model;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
/**
* <p>
* 维修配置表
* </p>
*
* @author cyl
* @since 2018-01-26
*/
@TableName("rep_repair_config")
public class RepRepairConfig extends BaseModel {
private static final long serialVersionUID = 1L;
/**
* 维修工程师id
*/
@TableField(value="repair_id")
private Long repairId;
/**
* 维修工程师姓名
*/
@TableField(value="repair_name")
private String repairName;
/**
* 手机号码
*/
private String mobile;
/**
* 所在科室id
*/
@TableField(value="dept_id")
private Long deptId;
/**
* 所在科室名称
*/
@TableField(value="dept_name")
private String deptName;
/**
* 职务ID
*/
@TableField(value="job_id")
private Integer jobId;
/**
* 职务名称
*/
@TableField(value="job_name")
private String jobName;
/**
* 所在机构id
*/
@TableField(value="tenant_id")
private Long tenantId;
/**
* 接单科室id
*/
@TableField(value="take_order_dept_id")
private Long takeOrderDeptId;
/**
* 接单科室名称
*/
@TableField(value="take_order_dept_name")
private String takeOrderDeptName;
/**
* 删除标志
*/
@TableField(value="del_flag")
private Boolean delFlag;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRepairId() {
return repairId;
}
public void setRepairId(Long repairId) {
this.repairId = repairId;
}
public String getRepairName() {
return repairName;
}
public void setRepairName(String repairName) {
this.repairName = repairName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Integer getJobId() {
return jobId;
}
public void setJobId(Integer jobId) {
this.jobId = jobId;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public Long getTakeOrderDeptId() {
return takeOrderDeptId;
}
public void setTakeOrderDeptId(Long takeOrderDeptId) {
this.takeOrderDeptId = takeOrderDeptId;
}
public String getTakeOrderDeptName() {
return takeOrderDeptName;
}
public void setTakeOrderDeptName(String takeOrderDeptName) {
this.takeOrderDeptName = takeOrderDeptName;
}
public Boolean isDelFlag() {
return delFlag;
}
public void setDelFlag(Boolean delFlag) {
this.delFlag = delFlag;
}
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairTakeOrdersServiceImpl.java
package com.aek.ebey.repair.service.impl;
import com.aek.ebey.repair.model.RepRepairTakeOrders;
import com.aek.ebey.repair.mapper.RepRepairTakeOrdersMapper;
import com.aek.ebey.repair.service.RepRepairTakeOrdersService;
import com.aek.common.core.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* 接单表 服务实现类
* </p>
*
* @author aek
* @since 2017-08-30
*/
@Service
@Transactional
public class RepRepairTakeOrdersServiceImpl extends BaseServiceImpl<RepRepairTakeOrdersMapper, RepRepairTakeOrders> implements RepRepairTakeOrdersService {
}
<file_sep>/aek-repair-web-api/src/main/resources/sql/rep_repair_apply2.sql
ALTER TABLE `rep_repair_apply` ADD COLUMN `dept_id` BIGINT (11) DEFAULT NULL COMMENT '部门id',
ADD COLUMN `assets_spec` VARCHAR (100) CHARACTER
SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '设备规格型号',
ADD COLUMN `factory_name` VARCHAR (100) CHARACTER
SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '生产商',
ADD COLUMN `factory_num` VARCHAR (100) CHARACTER
SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '出厂编号',
ADD COLUMN `start_use_date` datetime DEFAULT NULL COMMENT '启用日期',
ADD COLUMN `warranty_date` datetime DEFAULT NULL COMMENT '保修日期'<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepRepairBillCheckRequest.java
package com.aek.ebey.repair.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepRepairBillCheckRequest", description = "RepRepairBillCheckRequest")
public class RepRepairBillCheckRequest {
/**
* 维修单据ID
*/
@ApiModelProperty(value="维修单据ID")
private Long id;
/**
* 状态
*/
@ApiModelProperty(value = "状态(2=审批通过,3=审批未通过)")
private Integer status;
/**
* 审批备注
*/
@ApiModelProperty(value="审批备注")
private String remark;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/ribbon/QcClientService.java
package com.aek.ebey.repair.service.ribbon;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.aek.common.core.Result;
@FeignClient(value="${feign-qc.serviceId}",fallback = QcClientHystrix.class)
public interface QcClientService {
/**
* 查询QC待巡检待办
*/
@RequestMapping(method = RequestMethod.GET, value = "/qc/qcPlan/getQcImplementWaitToDo")
public Result<Integer> getQcImplementWaitToDo(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 查询PM待巡检待办
*/
@RequestMapping(method = RequestMethod.GET, value = "/pm/pmPlanImplementHelp/getPmImplementWaitToDo")
public Result<Integer> getPmImplementWaitToDo(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 查询QC验收待办
*/
@RequestMapping(method = RequestMethod.GET, value = "/qc/qcPlanCheck/getQcPlanCheckWaitToDo")
public Result<Integer> getQcCheckWaitToDo(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 查询PM验收待办
*/
@RequestMapping(method = RequestMethod.GET, value = "/pm/pmImplement/getPmCheckWaitToDo")
public Result<Integer> getPmCheckWaitToDo(@RequestParam(value = "id", required = true) Long id,
@RequestHeader("X-AEK56-Token") String token);
/**
* 查询MD待审核
*/
@RequestMapping(method = RequestMethod.GET, value = "/qc/mdReport/count")
public Result<Integer> getMdWaitToDo(@RequestParam(value = "tenantId", required = true) Long tenantId,
@RequestHeader("X-AEK56-Token") String token);
}<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/mapper/RepRepairBillFileMapper.java
package com.aek.ebey.repair.mapper;
import com.aek.common.core.base.BaseMapper;
import com.aek.ebey.repair.model.RepRepairBillFile;
/**
* 维修单据附件Mapper接口
*
* @author HongHui
* @date 2018年1月29日
*/
public interface RepRepairBillFileMapper extends BaseMapper<RepRepairBillFile>{
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/controller/RepPartsRecordController.java
package com.aek.ebey.repair.web.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aek.common.core.Result;
import com.aek.common.core.base.BaseController;
import com.aek.ebey.repair.model.RepPartsRecord;
import com.aek.ebey.repair.query.RepPartsRecordQuery;
import com.aek.ebey.repair.request.RepPartsRecordResponse;
import com.aek.ebey.repair.service.RepPartsRecordService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
/**
* <p>
* 配件操作记录表 前端控制器
* </p>
*
* @author aek
* @since 2017-08-30
*/
@RestController
@Api(value = "RepPartsRecordController", description = "配件操作记录")
@RequestMapping("/newrepair/repPartsRecord")
public class RepPartsRecordController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(RepPartsRecordController.class);
@Autowired
private RepPartsRecordService repPartsRecordService;
/**
* 根据申请单id搜索配件信息
*/
// @PreAuthorize("isAuthenticated()")
@GetMapping(value = "/search/{id}")
@ApiOperation(value = "根据申请单id搜索配件信息")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<List<RepPartsRecord>> search(@PathVariable(value = "id", required = true) Long id) {
logger.debug("<---------------------------------id="+id);
Wrapper<RepPartsRecord> wrapper = new EntityWrapper<RepPartsRecord>();
wrapper.eq("report_id", id);
wrapper.eq("del_flag", 0);
List<RepPartsRecord> list = repPartsRecordService.selectList(wrapper);
if (!CollectionUtils.isEmpty(list)) {
return response(list);
}
return response(null);
}
/**
* 查询操作记录列表(分页)
*/
@GetMapping(value = "/search")
@ApiOperation(value = "配件操作记录列表(分页)", httpMethod = "GET", produces = "application/json")
@ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "起始页 [默认1]", paramType = "query", required = false),
@ApiImplicitParam(name = "pageSize", value = "分页大小[默认10]", paramType = "query", required = false),
@ApiImplicitParam(name = "status", value = "操作类型(1入库 2 出库)", paramType = "query", required = false),
@ApiImplicitParam(name = "partName", value = "配件名称", paramType = "query", required = false),
@ApiImplicitParam(name = "orderByField", value = "排序列(operation_time)", paramType = "query", required = false),
@ApiImplicitParam(name = "isAsc", value = "true,false", paramType = "query", required = false)})
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<Page<RepPartsRecord>> search(RepPartsRecordQuery query) {
logger.debug("<---------------------------------"+JSON.toJSONString(query));
Page<RepPartsRecord> page = repPartsRecordService.search(query.getPage(),query);
return response(page);
}
}
<file_sep>/aek-repair-web-api/src/main/resources/sql/rep_parts.sql
/*
Navicat MySQL Data Transfer
Source Server : 6446
Source Server Version : 50718
Source Host : mysqlcluster.aek.com:6446
Source Database : repair_dev
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2017-07-19 13:56:50
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for rep_parts
-- ----------------------------
DROP TABLE IF EXISTS `rep_parts`;
CREATE TABLE `rep_parts` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`tenant_id` bigint(20) DEFAULT NULL COMMENT '机构id',
`kind_code` varchar(20) COLLATE utf8_bin DEFAULT NULL COMMENT '分类编码',
`kind_name` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '分类名称',
`update_man` varchar(20) COLLATE utf8_bin DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`status` tinyint(1) DEFAULT NULL COMMENT '启用状态(0未启用 1启用)',
`remarks` varchar(300) COLLATE utf8_bin DEFAULT NULL COMMENT '备注',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='配件分类表';
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairBillCheckFlowServiceImpl.java
package com.aek.ebey.repair.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aek.common.core.base.BaseServiceImpl;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.mapper.RepRepairBillCheckFlowMapper;
import com.aek.ebey.repair.model.RepRepairBillCheckFlow;
import com.aek.ebey.repair.query.RepRepairBillApproveQuery;
import com.aek.ebey.repair.request.RepRepairBillApproveResponse;
import com.aek.ebey.repair.service.RepRepairBillCheckFlowService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
/**
* 维修单据申请服务实现类
*
* @author HongHui
* @date 2018年1月29日
*/
@Service
@Transactional
public class RepRepairBillCheckFlowServiceImpl extends BaseServiceImpl<RepRepairBillCheckFlowMapper, RepRepairBillCheckFlow> implements RepRepairBillCheckFlowService {
private static final Logger logger = LoggerFactory.getLogger(RepRepairBillCheckFlowServiceImpl.class);
@Autowired
private RepRepairBillCheckFlowMapper repRepairBillCheckFlowMapper;
@Override
public List<RepRepairBillCheckFlow> getRepRepairBillCheckFlow(Long billId) {
Wrapper<RepRepairBillCheckFlow> wrapper=new EntityWrapper<RepRepairBillCheckFlow>();
wrapper.eq("bill_id", billId);
wrapper.orderBy("'index'", true);
List<RepRepairBillCheckFlow> list = repRepairBillCheckFlowMapper.selectList(wrapper);
return list;
}
@Override
public List<RepRepairBillApproveResponse> getRepairBillApprovePage(Page<RepRepairBillApproveResponse> page,
RepRepairBillApproveQuery query, AuthUser authUser) {
return repRepairBillCheckFlowMapper.getRepairBillApprovePage(page,query,authUser);
}
@Override
public List<RepRepairBillApproveResponse> getRepairBillApprovePage2(Page<RepRepairBillApproveResponse> page,
RepRepairBillApproveQuery query, AuthUser authUser) {
return repRepairBillCheckFlowMapper.getRepairBillApprovePage2(page,query,authUser);
}
@Override
public int getWaitToDo(Long id) {
return repRepairBillCheckFlowMapper.getWaitToDo(id);
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepairDictype.java
package com.aek.ebey.repair.model;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* <p>
*
* </p>
*
* @author aek
* @since 2017-08-30
*/
@ApiModel(value = "RepairDictype", description = "字典类型")
@TableName("repair_dictype")
public class RepairDictype extends BaseModel {
private static final long serialVersionUID = 1L;
/**
* 类型key
*/
@ApiModelProperty(value="类型key")
@TableField(value="type_key")
private String typeKey;
/**
* 类型名称
*/
@ApiModelProperty(value="类型名称")
private String name;
public String getTypeKey() {
return typeKey;
}
public void setTypeKey(String typeKey) {
this.typeKey = typeKey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepPartsRecordServiceImpl.java
package com.aek.ebey.repair.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aek.common.core.base.BaseServiceImpl;
import com.aek.common.core.exception.ExceptionFactory;
import com.aek.common.core.serurity.WebSecurityUtils;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.inter.Constants;
import com.aek.ebey.repair.mapper.RepPartsRecordMapper;
import com.aek.ebey.repair.model.RepPartsRecord;
import com.aek.ebey.repair.query.RepPartsRecordQuery;
import com.aek.ebey.repair.service.RepPartsRecordService;
import com.aek.ebey.repair.service.RepairDictionaryService;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 配件操作记录表 服务实现类
* </p>
*
* @author aek
* @since 2017-08-30
*/
@Service
@Transactional
public class RepPartsRecordServiceImpl extends BaseServiceImpl<RepPartsRecordMapper, RepPartsRecord> implements RepPartsRecordService {
@Autowired
private RepPartsRecordMapper repPartsRecordMapper;
@Autowired
private RepairDictionaryService repairDictionaryService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Override
public void add(RepPartsRecord data) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
if (authUser != null) {
// 设置机构
data.setTenantId(Long.parseLong(authUser.getTenantId() + ""));
repPartsRecordMapper.insert(data);
} else {
throw ExceptionFactory.create("W_001");
}
}
@Override
@Transactional(readOnly = true)
public Page<RepPartsRecord> search(Page<RepPartsRecord> page, RepPartsRecordQuery query) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
List<RepPartsRecord> list = repPartsRecordMapper.search(page, query, authUser);
if(list!=null&&list.size()>0){
for(RepPartsRecord repPartsRecord:list){
HashOperations<String, String, String> hash= redisTemplate.opsForHash();
getReportsRecord(hash,repPartsRecord);
}
}
page.setRecords(list);
return page;
}
private void getReportsRecord(HashOperations<String, String, String> hash, RepPartsRecord repPartsRecord) {
if(repPartsRecord.getUnit()!=null){
if(hash.get(Constants.REPAIR_DICTIONARY, repPartsRecord.getUnit())!=null){
repPartsRecord.setUnitName(hash.get(Constants.REPAIR_DICTIONARY, repPartsRecord.getUnit()));
}else{
String name= repairDictionaryService.getValue(repPartsRecord.getUnit());
if(name!=null){
hash.put(Constants.REPAIR_DICTIONARY,repPartsRecord.getUnit(), name);
repPartsRecord.setUnitName(name);
}
}
}
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepRepairBillParts.java
package com.aek.ebey.repair.model;
import java.math.BigDecimal;
import java.util.Date;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 维修单据配件实体类
*
* @author HongHui
* @date 2018年1月26日
*/
@ApiModel(value = "RepRepairBillParts", description = "维修单据配件信息")
@TableName("rep_repair_bill_parts")
public class RepRepairBillParts extends BaseModel {
private static final long serialVersionUID = -4621971544057285353L;
/**
* 维修单据ID
*/
@ApiModelProperty(value="维修单据ID")
@TableField(value="bill_id")
private Long billId;
/**
* 配件名称
*/
@ApiModelProperty(value="配件名称")
@TableField(value="part_name")
private String partName;
/**
* 规格型号
*/
@ApiModelProperty(value="规格型号")
@TableField(value="part_spec")
private String partSpec;
/**
* 配件生产商
*/
@ApiModelProperty(value="配件生产商")
@TableField(value="part_produce")
private String partProduce;
/**
* 配件单价
*/
@ApiModelProperty(value="配件单价")
@TableField(value="part_price")
private BigDecimal partPrice;
/**
* 计数单位
*/
@ApiModelProperty(value="计数单位")
@TableField(value="unit")
private String unit;
/**
* 操作数量
*/
@ApiModelProperty(value="操作数量")
@TableField(value="num")
private Integer num;
/**
* 添加时间
*/
@ApiModelProperty(value="添加时间")
@TableField(value="create_time")
private Date createTime;
public Long getBillId() {
return billId;
}
public void setBillId(Long billId) {
this.billId = billId;
}
public String getPartName() {
return partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public String getPartSpec() {
return partSpec;
}
public void setPartSpec(String partSpec) {
this.partSpec = partSpec;
}
public String getPartProduce() {
return partProduce;
}
public void setPartProduce(String partProduce) {
this.partProduce = partProduce;
}
public BigDecimal getPartPrice() {
return partPrice;
}
public void setPartPrice(BigDecimal partPrice) {
this.partPrice = partPrice;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((billId == null) ? 0 : billId.hashCode());
result = prime * result + ((createTime == null) ? 0 : createTime.hashCode());
result = prime * result + ((num == null) ? 0 : num.hashCode());
result = prime * result + ((partName == null) ? 0 : partName.hashCode());
result = prime * result + ((partPrice == null) ? 0 : partPrice.hashCode());
result = prime * result + ((partProduce == null) ? 0 : partProduce.hashCode());
result = prime * result + ((partSpec == null) ? 0 : partSpec.hashCode());
result = prime * result + ((unit == null) ? 0 : unit.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RepRepairBillParts other = (RepRepairBillParts) obj;
if (billId == null) {
if (other.billId != null)
return false;
} else if (!billId.equals(other.billId))
return false;
if (createTime == null) {
if (other.createTime != null)
return false;
} else if (!createTime.equals(other.createTime))
return false;
if (num == null) {
if (other.num != null)
return false;
} else if (!num.equals(other.num))
return false;
if (partName == null) {
if (other.partName != null)
return false;
} else if (!partName.equals(other.partName))
return false;
if (partPrice == null) {
if (other.partPrice != null)
return false;
} else if (!partPrice.equals(other.partPrice))
return false;
if (partProduce == null) {
if (other.partProduce != null)
return false;
} else if (!partProduce.equals(other.partProduce))
return false;
if (partSpec == null) {
if (other.partSpec != null)
return false;
} else if (!partSpec.equals(other.partSpec))
return false;
if (unit == null) {
if (other.unit != null)
return false;
} else if (!unit.equals(other.unit))
return false;
return true;
}
@Override
public String toString() {
return "RepRepairBillParts [billId=" + billId + ", partName=" + partName + ", partSpec=" + partSpec
+ ", partProduce=" + partProduce + ", partPrice=" + partPrice + ", unit=" + unit + ", num=" + num
+ ", createTime=" + createTime + "]";
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/RepTurnOrdersService.java
package com.aek.ebey.repair.service;
import com.aek.ebey.repair.model.RepTurnOrders;
import com.aek.common.core.base.BaseService;
/**
* <p>
* 服务类
* </p>
*
* @author aek
* @since 2018-01-11
*/
public interface RepTurnOrdersService extends BaseService<RepTurnOrders> {
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/RepRepairBillCheckFlowService.java
package com.aek.ebey.repair.service;
import java.util.List;
import com.aek.common.core.base.BaseService;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.model.RepRepairBillCheckFlow;
import com.aek.ebey.repair.query.RepRepairBillApproveQuery;
import com.aek.ebey.repair.request.RepRepairBillApproveResponse;
import com.baomidou.mybatisplus.plugins.Page;
/**
* 维修单据审核流程服务接口类
*
* @author HongHui
* @date 2018年1月29日
*/
public interface RepRepairBillCheckFlowService extends BaseService<RepRepairBillCheckFlow> {
/**
* 获取维修单据流程
* @param billId
* @return
*/
public List<RepRepairBillCheckFlow> getRepRepairBillCheckFlow(Long billId);
public List<RepRepairBillApproveResponse> getRepairBillApprovePage(Page<RepRepairBillApproveResponse> page,
RepRepairBillApproveQuery query, AuthUser authUser);
public List<RepRepairBillApproveResponse> getRepairBillApprovePage2(Page<RepRepairBillApproveResponse> page,
RepRepairBillApproveQuery query, AuthUser authUser);
public int getWaitToDo(Long id);
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/MessageResponse.java
package com.aek.ebey.repair.request;
import com.aek.ebey.repair.model.RepRepairMessage;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "MessageResponse", description = "消息信息")
public class MessageResponse extends RepRepairMessage{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 接收人ID
*/
@ApiModelProperty(value="接收人ID")
private Long userId;
/**
* 消息状态;0未查看1已查看
*/
@ApiModelProperty(value="消息状态;0未查看1已查看")
private Integer messageStatus;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getMessageStatus() {
return messageStatus;
}
public void setMessageStatus(Integer messageStatus) {
this.messageStatus = messageStatus;
}
@Override
public String toString() {
return "MessageResponse [userId=" + userId + ", messageStatus=" + messageStatus + "]";
}
}
<file_sep>/aek-repair-web-api/src/main/resources/sql/V2.11.0.sql
CREATE TABLE `rep_repair_bill_parts` (
`id` int(255) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`bill_id` bigint(20) DEFAULT NULL COMMENT '维修单据ID',
`part_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '配件名称',
`part_spec` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '规格型号',
`part_produce` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '配件生产商',
`part_price` decimal(20,2) DEFAULT NULL COMMENT '配件单价',
`unit` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '计数单位',
`num` int(3) DEFAULT NULL COMMENT '操作数量',
`create_time` datetime DEFAULT NULL COMMENT '添加时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='维修单据配件记录表';
CREATE TABLE `rep_repair_bill_file` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`bill_id` int(11) DEFAULT NULL COMMENT '单据ID',
`name` varchar(150) COLLATE utf8_bin DEFAULT NULL COMMENT '附件文件名称',
`url` varchar(300) COLLATE utf8_bin DEFAULT NULL COMMENT '文件路径地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='维修单据附件表';
CREATE TABLE `rep_repair_bill_check_flow` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`bill_id` int(11) DEFAULT NULL COMMENT '单据ID',
`flow_name` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT '流程名称',
`check_user_id` int(11) DEFAULT NULL COMMENT '审核人ID',
`check_user_name` varchar(40) COLLATE utf8_bin DEFAULT NULL COMMENT '审核人姓名',
`check_user_mobile` varchar(15) COLLATE utf8_bin DEFAULT NULL COMMENT '审核人手机号',
`index` int(11) DEFAULT NULL COMMENT '序号1,2,3......',
`check_status` int(11) DEFAULT NULL COMMENT '审核状态(1=待审核,2=审核通过,3=审核未通过)',
`check_remark` varchar(300) COLLATE utf8_bin DEFAULT NULL COMMENT '审核备注',
`check_time` datetime DEFAULT NULL COMMENT '审核时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='维修单据审核流程表';
CREATE TABLE `rep_repair_bill_check_config` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` int(11) DEFAULT NULL COMMENT '所属机构ID',
`check_user_id` int(11) DEFAULT NULL COMMENT '审核人ID',
`check_user_mobile` varchar(15) COLLATE utf8_bin DEFAULT NULL COMMENT '审核人手机号',
`check_user_name` varchar(40) COLLATE utf8_bin DEFAULT NULL COMMENT '审批人姓名',
`check_user_job` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '审核人职务',
`min_fee` decimal(20,2) DEFAULT NULL COMMENT '经费最小数值',
`max_fee` decimal(20,2) DEFAULT NULL COMMENT '经费最大数值',
`index` int(11) DEFAULT NULL COMMENT '层级(1=一级,2=二级,3=三级......)',
`index_name` varchar(40) COLLATE utf8_bin DEFAULT NULL COMMENT '层级名称',
`remark` varchar(300) COLLATE utf8_bin DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='维修单据审核配置表';
CREATE TABLE `rep_repair_bill` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` int(11) DEFAULT NULL COMMENT '机构ID',
`tenant_name` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT '所属机构名称',
`bill_no` varchar(16) COLLATE utf8_bin DEFAULT NULL COMMENT '单据编号',
`type` int(1) DEFAULT NULL COMMENT '单据类型(1=外修费用,2=配件采购)',
`status` int(1) DEFAULT NULL COMMENT '状态(1=审批中,2=审批通过,3=审批未通过,4=已撤销)',
`apply_id` int(11) DEFAULT NULL COMMENT '维修申请单ID',
`apply_no` varchar(30) COLLATE utf8_bin DEFAULT NULL COMMENT '维修单号',
`apply_user_id` int(11) DEFAULT NULL COMMENT '申请人ID',
`apply_user_name` varchar(40) COLLATE utf8_bin DEFAULT NULL COMMENT '单据申请人姓名',
`apply_user_dept_name` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '申请人所在科室名称',
`assets_name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '维修设备名称',
`assets_dept_name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '设备使用科室名称',
`assets_spec` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '设备规格',
`serial_num` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '院内编码',
`start_use_date` datetime DEFAULT NULL COMMENT '设备启用日期',
`report_repair_date` datetime DEFAULT NULL COMMENT '维修申请日期',
`external_repair_company` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '外修单位',
`apply_time` datetime DEFAULT NULL COMMENT '申请时间',
`fee` decimal(20,2) DEFAULT NULL COMMENT '费用金额',
`remark` varchar(300) COLLATE utf8_bin DEFAULT NULL COMMENT '申请备注(理由)',
`current_index` int(11) DEFAULT NULL COMMENT '审批流程所处序号',
`total_index` int(11) DEFAULT NULL COMMENT '单据所有的流程数',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='维修单据表';
CREATE TABLE `rep_repair_config` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`repair_id` bigint(20) NOT NULL COMMENT '维修工程师id',
`repair_name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '维修工程师姓名',
`mobile` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '手机号码',
`dept_id` bigint(20) DEFAULT NULL COMMENT '所在科室id',
`dept_name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '所在科室名称',
`job_id` int(11) DEFAULT NULL COMMENT '职务ID',
`job_name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '职务名称',
`tenant_id` bigint(20) DEFAULT NULL COMMENT '机构id',
`take_order_dept_id` bigint(20) DEFAULT NULL COMMENT '接单科室id',
`take_order_dept_name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '接单科室名称',
`del_flag` bit(1) DEFAULT b'0' COMMENT '删除标志',
PRIMARY KEY (`id`),
KEY `repair_id` (`repair_id`),
KEY `repair_name` (`repair_name`),
KEY `mobile` (`mobile`),
KEY `take_order_dept_id` (`take_order_dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='维修配置表';
ALTER TABLE `rep_repair_apply`
ADD COLUMN `send_person` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '送修人' AFTER `turn_num`;
ALTER TABLE `rep_repair_apply`
ADD COLUMN `send_phone` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '送修人电话' AFTER `send_person`;
ALTER TABLE `rep_repair_apply`
ADD COLUMN `take_order_id` bigint(20) NULL DEFAULT NULL COMMENT '接单人ID' AFTER `send_phone`;
ALTER TABLE `rep_repair_apply`
ADD COLUMN `take_order_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '接单人姓名' AFTER `take_order_id`;
ALTER TABLE `rep_repair_report`
ADD COLUMN `report_status` int(1) NULL DEFAULT NULL COMMENT '报修申请状态(1,送修 2,现场维修)' AFTER `del_flag`;
ALTER TABLE `rep_repair_report`
ADD COLUMN `send_person` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '送修人' AFTER `report_status`;
ALTER TABLE `rep_repair_report`
ADD COLUMN `send_phone` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '送修人电话' AFTER `send_person`;
ALTER TABLE `rep_repair_report`
ADD COLUMN `report_file` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '附件' AFTER `send_phone`;
ALTER TABLE `rep_repair_report`
ADD COLUMN `trouble_code` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '故障代码' AFTER `send_phone`;
UPDATE rep_repair_apply r,rep_repair_take_orders o set r.take_order_id=o.take_order_id,r.take_order_name=o.take_order_name where r.id=o.apply_id;
ALTER TABLE `rep_repair_report`
MODIFY COLUMN `attachment` varchar(5000) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '附件' AFTER `outside_phone`;
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/mapper/RepRepairBillCheckFlowMapper.java
package com.aek.ebey.repair.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.aek.common.core.base.BaseMapper;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.model.RepRepairBillCheckFlow;
import com.aek.ebey.repair.query.RepRepairBillApproveQuery;
import com.aek.ebey.repair.query.RepRepairBillQuery;
import com.aek.ebey.repair.request.RepRepairBillApproveResponse;
import com.aek.ebey.repair.request.RepRepairBillResponse;
import com.baomidou.mybatisplus.plugins.Page;
/**
* 维修单据审核流程Mapper接口
*
* @author HongHui
* @date 2018年1月29日
*/
public interface RepRepairBillCheckFlowMapper extends BaseMapper<RepRepairBillCheckFlow>{
List<RepRepairBillApproveResponse> getRepairBillApprovePage(Page<RepRepairBillApproveResponse> page,
@Param("q") RepRepairBillApproveQuery query, @Param("user") AuthUser authUser);
/**
* 获取单据申请列表数据
* @param page
* @param query
* @param authUser
* @return
*/
List<RepRepairBillResponse> getRepairBillPage(Page<RepRepairBillResponse> page,@Param("q") RepRepairBillQuery query, @Param("user") AuthUser authUser);
List<RepRepairBillApproveResponse> getRepairBillApprovePage2(Page<RepRepairBillApproveResponse> page,
@Param("q") RepRepairBillApproveQuery query, @Param("user") AuthUser authUser);
int getWaitToDo(@Param("id")Long id);
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/ribbon/UserPermissionHystrix.java
package com.aek.ebey.repair.service.ribbon;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.aek.common.core.Result;
import com.aek.ebey.repair.model.vo.RepConfigDeptVo;
import com.aek.ebey.repair.model.vo.RepUserVo;
@Component
public class UserPermissionHystrix implements UserPermissionService {
private static final Logger logger = LoggerFactory.getLogger(UserPermissionHystrix.class);
@Override
public Result<List<Long>> findByTenantAndCanPermiss(String tenantId, String permissionCode, String token) {
logger.error("findByTenantAndCanPermiss------------------------------------------------------");
return null;
}
@Override
public Result<String> findAllSubDeptById(Long deptId, String token) {
logger.error("findAllSubDeptById------------------------------------------------------");
return null;
}
@Override
public Result<Integer> checkIsRep(Long id, String token) {
logger.error("checkIsRep------------------------------------------------------"+id);
return null;
}
@Override
public Result<List<RepUserVo>> getTakeOrderUserList(String token) {
logger.error("token------------------------------------------------------"+token);
return null;
}
@Override
public Result<List<RepConfigDeptVo>> getDeptList(String keyword, String token) {
return null;
}
@Override
public Result<RepUserVo> getUser(Long id, Long tenantId, String token) {
return null;
}
@Override
public Result<Integer> checkIsRepHelp(Long id, String token) {
return null;
}
@Override
public Result<Integer> checkIsRepBill(Long id, String token) {
return null;
}
@Override
public Result<Boolean> checkIsDiscard(Long id, String token) {
logger.error("token------------------------------------------------------id="+id+"=token="+token);
return null;
}
@Override
public Result<Boolean> checkIsTransfer(Long id, String token) {
logger.error("token------------------------------------------------------id="+id+"=token="+token);
return null;
}
@Override
public Result<Boolean> checkIsRht(Long id, String rht, String token) {
logger.error("token------------------------------------------------------id="+id+"=rht="+rht);
return null;
}
@Override
public Result<List<RepUserVo>> getRepairUserList(String token) {
logger.error("token------------------------------------------------------=token="+token);
return null;
}
@Override
public Result<List<RepConfigDeptVo>> getAllDeptList(String keyword, String token) {
return null;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepRepairReportRequest.java
package com.aek.ebey.repair.request;
import java.util.Date;
import java.util.List;
import com.aek.ebey.repair.model.RepPartsRecord;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepRepairReportRequest", description = "维修报告单")
public class RepRepairReportRequest {
/**
* 关联申请单id
*/
@ApiModelProperty(value="关联申请单id")
private Long applyId;
/**
* 关联维修类型字典表
*/
@ApiModelProperty(value="关联维修类型字典表")
private String repairTypeKey;
/**
* 故障现象Ids字典表
*/
@ApiModelProperty(value="故障现象Ids字典表")
private String faultPhenomenonKeys;
/**
* 故障原因ids字典表
*/
@ApiModelProperty(value="故障原因ids字典表")
private String faultReasonKeys;
/**
* 工作内容ids字典表
*/
@ApiModelProperty(value="工作内容ids字典表")
private String workContentKeys;
/**
* 维修结果关联字典表
*/
@ApiModelProperty(value="维修结果关联字典表")
private String repairResultKey;
/**
* 维修开始日期
*/
@ApiModelProperty(value="维修开始日期")
private Date repairPeriodStart;
/**
* 维修结束日期
*/
@ApiModelProperty(value="维修结束日期")
private Date repairPeriodEnd;
/**
* 配件等待开始时间
*/
@ApiModelProperty(value="配件等待开始时间")
private Date partsWaitingStart;
/**
* 配件等待结束时间
*/
@ApiModelProperty(value="配件等待结束时间")
private Date partsWaitingEnd;
/**
* 实际开始时间
*/
@ApiModelProperty(value="实际开始时间")
private Date actualStart;
/**
* 实际结束时间
*/
@ApiModelProperty(value="实际结束时间")
private Date actualEnd;
/**
* 维修费用
*/
@ApiModelProperty(value="维修费用")
private Long repairCost;
/**
* 材料费用
*/
@ApiModelProperty(value="材料费用")
private Long partsCost;
/**
* 总计
*/
@ApiModelProperty(value="总计")
private Long totalCost;
/**
* 维修备注
*/
@ApiModelProperty(value="维修备注")
private String repairComent;
@ApiModelProperty(value="关联配件")
private List<RepPartsRecord> list;
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public String getRepairTypeKey() {
return repairTypeKey;
}
public void setRepairTypeKey(String repairTypeKey) {
this.repairTypeKey = repairTypeKey;
}
public String getFaultPhenomenonKeys() {
return faultPhenomenonKeys;
}
public void setFaultPhenomenonKeys(String faultPhenomenonKeys) {
this.faultPhenomenonKeys = faultPhenomenonKeys;
}
public String getFaultReasonKeys() {
return faultReasonKeys;
}
public void setFaultReasonKeys(String faultReasonKeys) {
this.faultReasonKeys = faultReasonKeys;
}
public String getWorkContentKeys() {
return workContentKeys;
}
public void setWorkContentKeys(String workContentKeys) {
this.workContentKeys = workContentKeys;
}
public String getRepairResultKey() {
return repairResultKey;
}
public void setRepairResultKey(String repairResultKey) {
this.repairResultKey = repairResultKey;
}
public Date getRepairPeriodStart() {
return repairPeriodStart;
}
public void setRepairPeriodStart(Date repairPeriodStart) {
this.repairPeriodStart = repairPeriodStart;
}
public Date getRepairPeriodEnd() {
return repairPeriodEnd;
}
public void setRepairPeriodEnd(Date repairPeriodEnd) {
this.repairPeriodEnd = repairPeriodEnd;
}
public Date getPartsWaitingStart() {
return partsWaitingStart;
}
public void setPartsWaitingStart(Date partsWaitingStart) {
this.partsWaitingStart = partsWaitingStart;
}
public Date getPartsWaitingEnd() {
return partsWaitingEnd;
}
public void setPartsWaitingEnd(Date partsWaitingEnd) {
this.partsWaitingEnd = partsWaitingEnd;
}
public Date getActualStart() {
return actualStart;
}
public void setActualStart(Date actualStart) {
this.actualStart = actualStart;
}
public Date getActualEnd() {
return actualEnd;
}
public void setActualEnd(Date actualEnd) {
this.actualEnd = actualEnd;
}
public Long getRepairCost() {
return repairCost;
}
public void setRepairCost(Long repairCost) {
this.repairCost = repairCost;
}
public Long getPartsCost() {
return partsCost;
}
public void setPartsCost(Long partsCost) {
this.partsCost = partsCost;
}
public Long getTotalCost() {
return totalCost;
}
public void setTotalCost(Long totalCost) {
this.totalCost = totalCost;
}
public String getRepairComent() {
return repairComent;
}
public void setRepairComent(String repairComent) {
this.repairComent = repairComent;
}
public List<RepPartsRecord> getList() {
return list;
}
public void setList(List<RepPartsRecord> list) {
this.list = list;
}
@Override
public String toString() {
return "RepRepairReportRequest [applyId=" + applyId + ", repairTypeKey=" + repairTypeKey
+ ", faultPhenomenonKeys=" + faultPhenomenonKeys + ", faultReasonKeys=" + faultReasonKeys
+ ", workContentKeys=" + workContentKeys + ", repairResultKey=" + repairResultKey
+ ", repairPeriodStart=" + repairPeriodStart + ", repairPeriodEnd=" + repairPeriodEnd
+ ", partsWaitingStart=" + partsWaitingStart + ", partsWaitingEnd=" + partsWaitingEnd + ", actualStart="
+ actualStart + ", actualEnd=" + actualEnd + ", repairCost=" + repairCost + ", partsCost=" + partsCost
+ ", totalCost=" + totalCost + ", repairComent=" + repairComent + ", list=" + list + "]";
}
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/request/RepRepairBillRequest.java
package com.aek.ebey.repair.web.request;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.NotNull;
import com.aek.ebey.repair.model.RepRepairBillFile;
import com.aek.ebey.repair.model.RepRepairBillParts;
import com.aek.ebey.repair.web.validator.group.Add;
import com.baomidou.mybatisplus.annotations.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepRepairBillRequest", description = "维修单据申请Request")
public class RepRepairBillRequest {
/**
* 维修申请单ID
*/
@ApiModelProperty(value="维修申请单ID")
@NotNull(groups = { Add.class }, message = "B_001")
private Long applyId;
/**
* 维修单号
*/
@ApiModelProperty(value="维修单号")
@NotNull(groups = { Add.class }, message = "B_001")
private String applyNo;
/**
* 单据类型(1=外修费用,2=配件采购)
*/
@ApiModelProperty(value="单据类型(1=外修费用,2=配件采购)")
@TableField(value="type")
private Integer type;
/**
* 维修设备名称
*/
@ApiModelProperty(value="维修设备名称")
@NotNull(groups = { Add.class }, message = "B_002")
private String assetsName;
/**
* 设备使用科室名称
*/
@ApiModelProperty(value="设备使用科室名称")
private String assetsDeptName;
/**
* 设备规格型号
*/
@ApiModelProperty(value="设备规格型号")
private String assetsSpec;
/**
* 设备院内编码
*/
@ApiModelProperty(value="设备院内编码")
private String serialNum;
/**
* 设备启用日期
*/
@ApiModelProperty(value="设备启用日期")
private Date startUseDate;
/**
* 维修申请日期
*/
@ApiModelProperty(value="维修申请日期")
private Date reportRepairDate;
/**
* 外修单位
*/
@ApiModelProperty(value="外修单位")
@NotNull(groups = { Add.class }, message = "B_003")
private String externalRepairCompany;
/**
* 费用金额
*/
@ApiModelProperty(value="费用金额")
@NotNull(groups = { Add.class }, message = "B_004")
private BigDecimal fee;
/**
* 申请理由
*/
@ApiModelProperty(value="申请理由")
private String remark;
/**
* 配件信息
*/
@ApiModelProperty(value="配件信息")
private List<RepRepairBillParts> billParts;
/**
* 附件信息
*/
@ApiModelProperty(value="附件信息")
private List<RepRepairBillFile> billFiles;
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public String getApplyNo() {
return applyNo;
}
public void setApplyNo(String applyNo) {
this.applyNo = applyNo;
}
public String getAssetsName() {
return assetsName;
}
public void setAssetsName(String assetsName) {
this.assetsName = assetsName;
}
public String getAssetsDeptName() {
return assetsDeptName;
}
public void setAssetsDeptName(String assetsDeptName) {
this.assetsDeptName = assetsDeptName;
}
public String getExternalRepairCompany() {
return externalRepairCompany;
}
public void setExternalRepairCompany(String externalRepairCompany) {
this.externalRepairCompany = externalRepairCompany;
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public List<RepRepairBillParts> getBillParts() {
return billParts;
}
public void setBillParts(List<RepRepairBillParts> billParts) {
this.billParts = billParts;
}
public List<RepRepairBillFile> getBillFiles() {
return billFiles;
}
public void setBillFiles(List<RepRepairBillFile> billFiles) {
this.billFiles = billFiles;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getAssetsSpec() {
return assetsSpec;
}
public void setAssetsSpec(String assetsSpec) {
this.assetsSpec = assetsSpec;
}
public String getSerialNum() {
return serialNum;
}
public void setSerialNum(String serialNum) {
this.serialNum = serialNum;
}
public Date getStartUseDate() {
return startUseDate;
}
public void setStartUseDate(Date startUseDate) {
this.startUseDate = startUseDate;
}
public Date getReportRepairDate() {
return reportRepairDate;
}
public void setReportRepairDate(Date reportRepairDate) {
this.reportRepairDate = reportRepairDate;
}
@Override
public String toString() {
return "RepRepairBillRequest [applyId=" + applyId + ", applyNo=" + applyNo + ", assetsName=" + assetsName
+ ", assetsDeptName=" + assetsDeptName + ", externalRepairCompany=" + externalRepairCompany + ", fee="
+ fee + ", remark=" + remark + ", billParts=" + billParts + ", billFiles=" + billFiles + "]";
}
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/mapper/RepairDictypeMapper.java
package com.aek.ebey.repair.mapper;
import com.aek.common.core.base.BaseMapper;
import com.aek.ebey.repair.model.RepairDictype;
/**
* <p>
* Mapper接口
* </p>
*
* @author aek
* @since 2017-08-30
*/
public interface RepairDictypeMapper extends BaseMapper<RepairDictype> {
String getValue(String ketId);
}<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/mapper/RepRepairPartsMapper.java
package com.aek.ebey.repair.mapper;
import com.aek.ebey.repair.model.RepRepairParts;
import com.aek.common.core.base.BaseMapper;
/**
* <p>
* Mapper接口
* </p>
*
* @author aek
* @since 2017-06-06
*/
public interface RepRepairPartsMapper extends BaseMapper<RepRepairParts> {
}<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/inter/RepairApplyStatus.java
package com.aek.ebey.repair.inter;
public interface RepairApplyStatus {
/** 待接单 */
public static final Integer WAITTAKE = 1;
/** 已接单 */
/* public static final Integer TAKEED = 2;*/
/** 维修中*/
public static final Integer REPAIRING = 2;
/** 待验收 */
public static final Integer WAITCHECK = 3;
/** 已完成 */
public static final Integer COMPLETED = 4;
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/controller/RepairDictionaryController.java
package com.aek.ebey.repair.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aek.common.core.Result;
import com.aek.common.core.base.BaseController;
import com.aek.common.core.base.page.PageHelp;
import com.aek.ebey.repair.model.RepairDictionary;
import com.aek.ebey.repair.model.RepairDictype;
import com.aek.ebey.repair.service.RepairDictionaryService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
/**
* <p>
* 前端控制器
* </p>
*
* @author aek
* @since 2017-08-30
*/
@RestController
@Api(value = "RepairDictionaryController", description = "数据字典模块")
@RequestMapping("/newrepair/repairDictionary")
public class RepairDictionaryController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(RepairDictionaryController.class);
@Autowired
private RepairDictionaryService repairDictionaryService;
/**
* 查询数据类型列表(分页)
*/
@GetMapping(value = "/search")
@ApiOperation(value = "查询数据类型列表(分页)", httpMethod = "GET", produces = "application/json")
@ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "起始页 [默认1]", paramType = "query", required = false),
@ApiImplicitParam(name = "pageSize", value = "分页大小[默认10]", paramType = "query", required = false)})
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<Page<RepairDictype>> search(PageHelp<RepairDictype> query) {
logger.debug("<---------------------------------"+JSON.toJSONString(query));
Page<RepairDictype> page = repairDictionaryService.search(query);
return response(page);
}
/**
* 根据类型ID查询字典内容
*/
@GetMapping(value = "/search/{typeKey}")
@ApiOperation(value = "根据类型key查询字典内容")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<List<RepairDictionary>> searchBytypeid(@PathVariable(value = "typeKey", required = true) String typeKey) {
logger.debug("<---------------------------------typeKey="+typeKey);
Map map=new HashMap<String,String>();
map.put("type_key", typeKey);
List<RepairDictionary> list = repairDictionaryService.selectByMap(map);
return response(list);
}
/**
* 根据key查询字典内容
*/
@GetMapping(value = "/selectkey/{keyId}")
@ApiOperation(value = "根据key查询字典内容")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<RepairDictionary> selectkey(@PathVariable(value = "keyId", required = true) Long keyId) {
logger.debug("<---------------------------------keyId="+keyId);
Wrapper<RepairDictionary> wrapper = new EntityWrapper<RepairDictionary>();
wrapper.eq("key_id", keyId);
return response(repairDictionaryService.selectOne(wrapper));
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepRepairBillPrintDetailResponse.java
package com.aek.ebey.repair.request;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.aek.ebey.repair.model.RepRepairBillCheckFlow;
import com.aek.ebey.repair.model.RepRepairBillFile;
import com.aek.ebey.repair.model.RepRepairBillParts;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 维修单据打印详情实体类
*
* @author HongHui
* @date 2018年1月26日
*/
@ApiModel(value = "RepRepairBillPrintDetailResponse", description = "维修单据维修单打印详情数据")
public class RepRepairBillPrintDetailResponse{
/**
* 维修单据ID
*/
@ApiModelProperty(value="维修单据ID")
private Long id;
/**
* 机构ID
*/
@ApiModelProperty(value="机构ID")
private Long tenantId;
/**
* 机构名称
*/
@ApiModelProperty(value="机构名称")
private String tenantName;
/**
* 单据编号
*/
@ApiModelProperty(value="单据编号")
private String billNo;
/**
* 单据申请时间
*/
@ApiModelProperty(value="单据申请时间")
private Date applyTime;
/**
* 单据申请人姓名
*/
@ApiModelProperty(value="单据申请人姓名")
private String applyUserName;
/**
* 单据申请人所在科室
*/
@ApiModelProperty(value="单据申请人所在科室")
private String applyUserDeptName;
/**
* 单据类型(1=外修费用,2=配件采购)
*/
@ApiModelProperty(value="单据类型(1=外修费用,2=配件采购)")
private Integer type;
/**
* 状态(1=审批中,2=审批通过,3=审批未通过,4=已撤销)
*/
@ApiModelProperty(value="状态(1=审批中,2=审批通过,3=审批未通过,4=已撤销)")
private Integer status;
/**
* 维修申请单ID
*/
@ApiModelProperty(value="维修申请单ID")
private Long applyId;
/**
* 维修单号
*/
@ApiModelProperty(value="维修单号")
private String applyNo;
/**
* 维修设备名称
*/
@ApiModelProperty(value="维修设备名称")
private String assetsName;
/**
* 设备使用科室名称
*/
@ApiModelProperty(value="设备使用科室名称")
private String assetsDeptName;
/**
* 设备规格型号
*/
@ApiModelProperty(value="设备规格型号")
private String assetsSpec;
/**
* 院内编码
*/
@ApiModelProperty(value="院内编码")
private String serialNum;
/**
* 设备启用日期
*/
@ApiModelProperty(value="设备启用日期")
private Date startUseDate;
/**
* 维修申请日期
*/
@ApiModelProperty(value="维修申请日期")
private Date reportRepairDate;
/**
* 费用金额
*/
@ApiModelProperty(value="费用金额")
private BigDecimal fee;
/**
* 配件信息
*/
@ApiModelProperty(value="配件信息")
private List<RepRepairBillParts> billParts;
/**
* 外修单位
*/
@ApiModelProperty(value="外修单位")
private String externalRepairCompany;
/**
* 申请理由
*/
@ApiModelProperty(value="申请理由")
private String remark;
/**
* 审批时间
*/
@ApiModelProperty(value="审批时间")
private Date checkTime;
/**
* 附件信息
*/
@ApiModelProperty(value="附件信息")
private List<RepRepairBillFile> billFiles;
/**
* 维修单据审批流程
*/
private List<RepRepairBillCheckFlow> billFlows;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
public String getTenantName() {
return tenantName;
}
public void setTenantName(String tenantName) {
this.tenantName = tenantName;
}
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
public Date getApplyTime() {
return applyTime;
}
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
public String getApplyUserName() {
return applyUserName;
}
public void setApplyUserName(String applyUserName) {
this.applyUserName = applyUserName;
}
public String getApplyUserDeptName() {
return applyUserDeptName;
}
public void setApplyUserDeptName(String applyUserDeptName) {
this.applyUserDeptName = applyUserDeptName;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public String getApplyNo() {
return applyNo;
}
public void setApplyNo(String applyNo) {
this.applyNo = applyNo;
}
public String getAssetsName() {
return assetsName;
}
public void setAssetsName(String assetsName) {
this.assetsName = assetsName;
}
public String getAssetsDeptName() {
return assetsDeptName;
}
public void setAssetsDeptName(String assetsDeptName) {
this.assetsDeptName = assetsDeptName;
}
public String getAssetsSpec() {
return assetsSpec;
}
public void setAssetsSpec(String assetsSpec) {
this.assetsSpec = assetsSpec;
}
public String getSerialNum() {
return serialNum;
}
public void setSerialNum(String serialNum) {
this.serialNum = serialNum;
}
public Date getStartUseDate() {
return startUseDate;
}
public void setStartUseDate(Date startUseDate) {
this.startUseDate = startUseDate;
}
public Date getReportRepairDate() {
return reportRepairDate;
}
public void setReportRepairDate(Date reportRepairDate) {
this.reportRepairDate = reportRepairDate;
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public List<RepRepairBillParts> getBillParts() {
return billParts;
}
public void setBillParts(List<RepRepairBillParts> billParts) {
this.billParts = billParts;
}
public String getExternalRepairCompany() {
return externalRepairCompany;
}
public void setExternalRepairCompany(String externalRepairCompany) {
this.externalRepairCompany = externalRepairCompany;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public List<RepRepairBillFile> getBillFiles() {
return billFiles;
}
public void setBillFiles(List<RepRepairBillFile> billFiles) {
this.billFiles = billFiles;
}
public List<RepRepairBillCheckFlow> getBillFlows() {
return billFlows;
}
public void setBillFlows(List<RepRepairBillCheckFlow> billFlows) {
this.billFlows = billFlows;
}
public Date getCheckTime() {
return checkTime;
}
public void setCheckTime(Date checkTime) {
this.checkTime = checkTime;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/RepRepairMessageService.java
package com.aek.ebey.repair.service;
import com.aek.ebey.repair.model.RepRepairMessage;
import com.aek.ebey.repair.request.SendMessage;
import com.aek.common.core.base.BaseService;
/**
* <p>
* 服务类
* </p>
*
* @author aek
* @since 2017-08-30
*/
public interface RepRepairMessageService extends BaseService<RepRepairMessage> {
void save(SendMessage sendMessage);
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/RepRepairConfigService.java
package com.aek.ebey.repair.service;
import com.aek.ebey.repair.model.RepRepairConfig;
import com.aek.ebey.repair.model.vo.RepConfigDeptVo;
import com.aek.ebey.repair.model.vo.RepConfigResponseVo;
import com.aek.ebey.repair.model.vo.RepConfiger;
import com.aek.ebey.repair.model.vo.RepUserVo;
import com.baomidou.mybatisplus.plugins.Page;
import java.util.List;
import com.aek.common.core.base.BaseService;
/**
* <p>
* 服务类
* </p>
*
* @author cyl
* @since 2018-01-26
*/
public interface RepRepairConfigService extends BaseService<RepRepairConfig> {
List<RepConfigDeptVo> selectDept(String keyword);
Page<RepUserVo> repairConfigPage(Page<RepUserVo> page);
void repConfig(Long repairId,List<RepConfigDeptVo> depts);
RepConfigResponseVo getConfigDetail(Long repairId);
RepConfiger selectConfiger(Long deptId);
List<RepConfiger> selectUsers();
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/query/RepRepairBillApproveQuery.java
package com.aek.ebey.repair.query;
import com.aek.common.core.base.page.PageHelp;
import com.aek.ebey.repair.request.RepRepairBillApproveResponse;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepRepairBillApproveQuery", description = "审批查询query")
public class RepRepairBillApproveQuery extends PageHelp<RepRepairBillApproveResponse>{
/**
* 状态
*/
@ApiModelProperty(value = "状态(1=审批中,2=审批通过,3=审批未通过,4=已撤销)")
private Integer status;
/**
* 单据类型(1=外修费用,2=配件采购)
*/
@ApiModelProperty(value = "单据类型(1=外修费用,2=配件采购)")
private Integer type;
/**
* 检索关键字,设备名称/申请单号
*/
@ApiModelProperty(value = "设备名称/申请单号")
private String keyword;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepairRecordResponse.java
package com.aek.ebey.repair.request;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepairRecordResponse", description = "维修记录响应信息")
public class RepairRecordResponse implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 关联维修单id
*/
@ApiModelProperty(value="关联维修单id")
private Long applyId;
/**
* 设备id
*/
@ApiModelProperty(value="设备id")
private String assetsId;
/**
* 维修申请单号
*/
@ApiModelProperty(value="维修申请单号")
private String applyNo;
/**
* 维修方式(1,自主维修 2,外修 3,现场解决)
*/
@ApiModelProperty(value="维修方式(1,自主维修 2,外修 3,现场解决)")
private Integer modeStatus;
/**
* 报修申请时间
*/
@ApiModelProperty(value="报修申请时间")
private Date reportRepairDate;
/**
* 申请人姓名
*/
@ApiModelProperty(value="申请人姓名")
private String reportRepairName;
/**
* 维修人名称
*/
@ApiModelProperty(value="维修人名称")
private String repairName;
/**
* 提交报告单时间
*/
@ApiModelProperty(value="提交报告单时间(完修时间)")
private Date repairDate;
/**
* 总计
*/
@ApiModelProperty(value="总计(维修费用)")
private BigDecimal totalCost;
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public String getApplyNo() {
return applyNo;
}
public void setApplyNo(String applyNo) {
this.applyNo = applyNo;
}
public Integer getModeStatus() {
return modeStatus;
}
public void setModeStatus(Integer modeStatus) {
this.modeStatus = modeStatus;
}
public Date getReportRepairDate() {
return reportRepairDate;
}
public void setReportRepairDate(Date reportRepairDate) {
this.reportRepairDate = reportRepairDate;
}
public String getReportRepairName() {
return reportRepairName;
}
public void setReportRepairName(String reportRepairName) {
this.reportRepairName = reportRepairName;
}
public String getRepairName() {
return repairName;
}
public void setRepairName(String repairName) {
this.repairName = repairName;
}
public Date getRepairDate() {
return repairDate;
}
public void setRepairDate(Date repairDate) {
this.repairDate = repairDate;
}
public BigDecimal getTotalCost() {
return totalCost;
}
public void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
public String getAssetsId() {
return assetsId;
}
public void setAssetsId(String assetsId) {
this.assetsId = assetsId;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/ApplyTurnOrderRequest.java
package com.aek.ebey.repair.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "ApplyTurnOrderRequest", description = "转单")
public class ApplyTurnOrderRequest {
/**
* 关联申请单id
*/
@ApiModelProperty(value="关联申请单id")
private Long applyId;
/**
* 转单接单人id
*/
@ApiModelProperty(value="转单接单人id")
private Long toId;
/**
* 转单接单人姓名
*/
@ApiModelProperty(value="转单接单人姓名")
private String toName;
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public Long getToId() {
return toId;
}
public void setToId(Long toId) {
this.toId = toId;
}
public String getToName() {
return toName;
}
public void setToName(String toName) {
this.toName = toName;
}
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/mapper/RepMessageReceiveMapper.java
package com.aek.ebey.repair.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.aek.common.core.base.BaseMapper;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.model.RepMessageReceive;
import com.aek.ebey.repair.query.RepMessageReceiveQuery;
import com.aek.ebey.repair.request.MessageResponse;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* Mapper接口
* </p>
*
* @author aek
* @since 2017-08-30
*/
public interface RepMessageReceiveMapper extends BaseMapper<RepMessageReceive> {
List<MessageResponse> selectMyPage( Page<MessageResponse> page,@Param("q") RepMessageReceiveQuery query, @Param("user") AuthUser authUser);
int updateByStatus( @Param("userId") Long userId);
List<MessageResponse> selectMyPageX( Page<MessageResponse> page,@Param("q") RepMessageReceiveQuery query, @Param("user") AuthUser authUser);
}<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepRepairBillApproveResponse.java
package com.aek.ebey.repair.request;
import java.util.Date;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 维修单据实体类
*
* @author HongHui
* @date 2018年1月26日
*/
@ApiModel(value = "RepRepairBillApproveResponse", description = "审批单据")
public class RepRepairBillApproveResponse{
/**
* 维修单据ID
*/
@ApiModelProperty(value="维修单据ID")
private Long id;
/**
* 单据编号
*/
@ApiModelProperty(value="单据编号")
private String billNo;
/**
* 维修申请单ID
*/
@ApiModelProperty(value="维修申请单ID")
private Long applyId;
/**
* 维修单号
*/
@ApiModelProperty(value="维修单号")
private String applyNo;
/**
* 单据类型(1=外修费用,2=配件采购)
*/
@ApiModelProperty(value="单据类型(1=外修费用,2=配件采购)")
private Integer type;
/**
* 单据类型文本(1=外修费用,2=配件采购)
*/
@ApiModelProperty(value="单据类型文本(1=外修费用,2=配件采购)")
private String typeText;
/**
* 状态(1=审批中,2=审批通过,3=审批未通过,4=已撤销)
*/
@ApiModelProperty(value="状态(1=审批中,2=审批通过,3=审批未通过)")
private Integer status;
/**
* 状态文本(1=审批中,2=审批通过,3=审批未通过,4=已撤销)
*/
@ApiModelProperty(value="状态文本(1=审批中,2=审批通过,3=审批未通过)")
private String statusText;
/**
* 维修设备名称
*/
@ApiModelProperty(value="维修设备名称")
private String assetsName;
/**
* 设备使用科室名称
*/
@ApiModelProperty(value="设备使用科室名称")
private String assetsDeptName;
/**
* 申请人ID
*/
@ApiModelProperty(value="申请人ID")
private Long applyUserId;
/**
* 申请人姓名
*/
@ApiModelProperty(value="申请人姓名")
private String applyUserName;
/**
* 申请时间
*/
@ApiModelProperty(value="申请时间")
private Date applyTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public String getApplyNo() {
return applyNo;
}
public void setApplyNo(String applyNo) {
this.applyNo = applyNo;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getTypeText() {
return typeText;
}
public void setTypeText(String typeText) {
this.typeText = typeText;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getStatusText() {
return statusText;
}
public void setStatusText(String statusText) {
this.statusText = statusText;
}
public String getAssetsName() {
return assetsName;
}
public void setAssetsName(String assetsName) {
this.assetsName = assetsName;
}
public String getAssetsDeptName() {
return assetsDeptName;
}
public void setAssetsDeptName(String assetsDeptName) {
this.assetsDeptName = assetsDeptName;
}
public Long getApplyUserId() {
return applyUserId;
}
public void setApplyUserId(Long applyUserId) {
this.applyUserId = applyUserId;
}
public String getApplyUserName() {
return applyUserName;
}
public void setApplyUserName(String applyUserName) {
this.applyUserName = applyUserName;
}
public Date getApplyTime() {
return applyTime;
}
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/mapper/RepRepairTakeOrdersMapper.java
package com.aek.ebey.repair.mapper;
import com.aek.ebey.repair.model.RepRepairTakeOrders;
import com.aek.common.core.base.BaseMapper;
/**
* <p>
* Mapper接口
* </p>
*
* @author aek
* @since 2017-08-30
*/
public interface RepRepairTakeOrdersMapper extends BaseMapper<RepRepairTakeOrders> {
}<file_sep>/aek-repair-web-api/src/main/resources/sql/newrepair.sql
ALTER TABLE `rep_repair_report`
ADD COLUMN `engineer_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '工程师姓名' AFTER `repair_hours`,
ADD COLUMN `engineer_num` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '工程师工号' AFTER `engineer_name`;
ADD COLUMN `call_repair_date` datetime NULL COMMENT '叫修时间' AFTER `engineer_num`;
ADD COLUMN `arrival_date` datetime NULL COMMENT '到达时间' AFTER `call_repair_date`;
ADD COLUMN `leave_date` datetime NULL COMMENT '离开时间' AFTER `arrival_date`;
ALTER TABLE `rep_repair_apply`
MODIFY COLUMN `assets_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '设备名称' AFTER `factory_name`;
ALTER TABLE `rep_repair_apply`
MODIFY COLUMN `assets_num` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '资产编号' AFTER `assets_brand`;
ALTER TABLE `rep_parts_record`
MODIFY COLUMN `part_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '配件名称' AFTER `tenant_id`;
MODIFY COLUMN `status` int(1) NULL DEFAULT NULL COMMENT '操作类型(1领用 2 购买)' AFTER `num`;
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/controller/RepRepairConfigController.java
package com.aek.ebey.repair.web.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.aek.common.core.Result;
import com.aek.common.core.base.BaseController;
import com.aek.ebey.repair.model.vo.RepConfigDeptVo;
import com.aek.ebey.repair.model.vo.RepConfigResponseVo;
import com.aek.ebey.repair.model.vo.RepConfiger;
import com.aek.ebey.repair.model.vo.RepUserVo;
import com.aek.ebey.repair.query.RepairConfigDeptQuery;
import com.aek.ebey.repair.query.RepairConfigQuery;
import com.aek.ebey.repair.service.RepRepairConfigService;
import com.aek.ebey.repair.web.request.RepairConfigRequest;
import com.aek.ebey.repair.web.validator.group.Add;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
/**
* <p>
* 维修配置表 前端控制器
* </p>
*
* @author cyl
* @since 2018-01-26
*/
@RestController
@RequestMapping("/newrepair/repRepairConfig")
public class RepRepairConfigController extends BaseController {
@Autowired
RepRepairConfigService repRepairConfigService;
/**
* 维修配置新增或修改
*/
@PreAuthorize("hasAuthority('REP_REPAIR_CONFIG')")
@PostMapping(value = "/repConfig")
@ApiOperation(value = "维修配置新增或修改", httpMethod = "POST", produces = "application/json")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<Object> repConfig(@Validated(value = Add.class)@RequestBody RepairConfigRequest req) {
List<RepConfigDeptVo> depts = req.getDepts();
Long repairId = req.getRepairId();
repRepairConfigService.repConfig(repairId, depts);
return response();
}
/**
* 维修配置详情
*/
@PreAuthorize("hasAuthority('REP_REPAIR_CONFIG')")
@GetMapping(value = "/getConfigDetail")
@ApiOperation(value = "维修配置详情", httpMethod = "GET", produces = "application/json")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<RepConfigResponseVo> getConfigDetail(@RequestParam("id")Long id) {
return response(repRepairConfigService.getConfigDetail(id));
}
/**
* 维修配置列表分页
*/
@PreAuthorize("hasAuthority('REP_REPAIR_CONFIG')")
@GetMapping(value = "/repairConfigPage")
@ApiOperation(value = "维修配置列表分页", httpMethod = "GET", produces = "application/json")
@ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "起始页 [默认1]", paramType = "query", required = false),
@ApiImplicitParam(name = "pageSize", value = "分页大小[默认10]", paramType = "query", required = false)})
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<Page<RepUserVo>> repairConfigPage(RepairConfigQuery query) {
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>"+JSON.toJSONString(query)+">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Page<RepUserVo> page = query.getPage();
return response(repRepairConfigService.repairConfigPage(page));
}
/**
* 维修配置选取未分配部门
*/
@PreAuthorize("hasAuthority('REP_REPAIR_CONFIG')")
@GetMapping(value = "/selectDept")
@ApiOperation(value = "维修配置选取未分配部门", httpMethod = "GET", produces = "application/json")
@ApiImplicitParams({ @ApiImplicitParam(name = "keyword", value = "关键字检索", paramType = "query"),
@ApiImplicitParam(name = "tenantId", value = "机构ID", paramType = "query", required = true)})
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<List<RepConfigDeptVo>> selectDept(RepairConfigDeptQuery query) {
String keyword = query.getKeyword();
return response(repRepairConfigService.selectDept(keyword));
}
/**
* 维修配置选取推荐配置人员
*/
@PreAuthorize("isAuthenticated()")
@GetMapping(value = "/selectConfiger")
@ApiOperation(value = "维修配置选取推荐配置人", httpMethod = "GET", produces = "application/json")
@ApiImplicitParam(name = "deptId", value = "科室id")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<RepConfiger> selectConfiger(@RequestParam("deptId")Long deptId) {
return response(repRepairConfigService.selectConfiger(deptId));
}
/**
* 维修配置选取所有有接单权限和启用的人员
*/
@PreAuthorize("isAuthenticated()")
@GetMapping(value = "/selectUsers")
@ApiOperation(value = "维修配置选取所有有接单权限和启用的人员", httpMethod = "GET", produces = "application/json")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<List<RepConfiger>> selectUsers() {
return response(repRepairConfigService.selectUsers());
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepRepairCheck.java
package com.aek.ebey.repair.model;
import java.util.Date;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* <p>
* 验收详情表
* </p>
*
* @author aek
* @since 2017-08-30
*/
@ApiModel(value = "RepRepairCheck", description = "验收详情")
@TableName("rep_repair_check")
public class RepRepairCheck extends BaseModel {
private static final long serialVersionUID = 1L;
/**
* 关联申请单id
*/
@ApiModelProperty(value="关联申请单id")
@TableField(value="apply_id")
private Long applyId;
/**
* 验收人ID
*/
@ApiModelProperty(value="验收人ID")
@TableField(value="repair_check_id")
private Long repairCheckId;
/**
* 验收人姓名
*/
@ApiModelProperty(value="验收人姓名")
@TableField(value="repair_check_name")
private String repairCheckName;
/**
* 验收时间
*/
@ApiModelProperty(value="验收时间")
@TableField(value="repair_check_time")
private Date repairCheckTime=new Date();
/**
* 维修态度
*/
@ApiModelProperty(value="维修态度")
@TableField(value="repair_attitude")
private String repairAttitude;
/**
* 响应速度
*/
@ApiModelProperty(value="响应速度")
@TableField(value="response_speed")
private String responseSpeed;
/**
* 维修质量
*/
@ApiModelProperty(value="维修质量")
@TableField(value="repair_quality")
private String repairQuality;
/**
* 评价备注
*/
@ApiModelProperty(value="评价备注")
private String remarks;
/**
* 作废标记,0:启用,1:删除
*/
@ApiModelProperty(value="作废标记,0:启用,1:删除")
@TableField(value="del_flag")
private Boolean delFlag;
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public Long getRepairCheckId() {
return repairCheckId;
}
public void setRepairCheckId(Long repairCheckId) {
this.repairCheckId = repairCheckId;
}
public String getRepairCheckName() {
return repairCheckName;
}
public void setRepairCheckName(String repairCheckName) {
this.repairCheckName = repairCheckName;
}
public Date getRepairCheckTime() {
return repairCheckTime;
}
public void setRepairCheckTime(Date repairCheckTime) {
this.repairCheckTime = repairCheckTime;
}
public String getRepairAttitude() {
return repairAttitude;
}
public void setRepairAttitude(String repairAttitude) {
this.repairAttitude = repairAttitude;
}
public String getResponseSpeed() {
return responseSpeed;
}
public void setResponseSpeed(String responseSpeed) {
this.responseSpeed = responseSpeed;
}
public String getRepairQuality() {
return repairQuality;
}
public void setRepairQuality(String repairQuality) {
this.repairQuality = repairQuality;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public Boolean isDelFlag() {
return delFlag;
}
public void setDelFlag(Boolean delFlag) {
this.delFlag = delFlag;
}
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/request/RepRepairWorkflowRequest.java
package com.aek.ebey.repair.web.request;
import java.math.BigDecimal;
import io.swagger.annotations.ApiModelProperty;
public class RepRepairWorkflowRequest {
@ApiModelProperty(value="所属机构ID")
private Long tenantId;
@ApiModelProperty(value="层级索引")
private Integer index;
@ApiModelProperty(value="层级名称")
private String indexName;
@ApiModelProperty(value="区间开始值")
private BigDecimal minFee;
@ApiModelProperty(value="区间结束值")
private BigDecimal maxFee;
@ApiModelProperty(value="审批人id")
private Long checkUserId;
@ApiModelProperty(value="审批人姓名")
private String checkUserName;
@ApiModelProperty(value="审批人职务")
private String checkUserJob;
@ApiModelProperty(value="备注")
private String remark;
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public BigDecimal getMinFee() {
return minFee;
}
public void setMinFee(BigDecimal minFee) {
this.minFee = minFee;
}
public BigDecimal getMaxFee() {
return maxFee;
}
public void setMaxFee(BigDecimal maxFee) {
this.maxFee = maxFee;
}
public Long getCheckUserId() {
return checkUserId;
}
public void setCheckUserId(Long checkUserId) {
this.checkUserId = checkUserId;
}
public String getCheckUserName() {
return checkUserName;
}
public void setCheckUserName(String checkUserName) {
this.checkUserName = checkUserName;
}
public String getCheckUserJob() {
return checkUserJob;
}
public void setCheckUserJob(String checkUserJob) {
this.checkUserJob = checkUserJob;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/controller/RepRepairTakeOrdersController.java
package com.aek.ebey.repair.web.controller;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aek.common.core.Result;
import com.aek.common.core.base.BaseController;
import com.aek.common.core.serurity.WebSecurityUtils;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.model.RepRepairTakeOrders;
import com.aek.ebey.repair.service.RepRepairApplyService;
import com.aek.ebey.repair.service.RepRepairTakeOrdersService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
/**
* <p>
* 接单表 前端控制器
* </p>
*
* @author aek
* @since 2017-08-30
*/
@RestController
@Api(value = "RepRepairTakeOrdersController", description = "维修接单")
@RequestMapping("/newrepair/repRepairTakeOrders")
public class RepRepairTakeOrdersController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(RepRepairTakeOrdersController.class);
@Autowired
private RepRepairApplyService repRepairApplyService;
@Autowired
private RepRepairTakeOrdersService repRepairTakeOrdersService;
/**
* 新建申请单
*
* @throws IOException
*/
@PreAuthorize("hasAuthority('REP_APPLY_TAKE_NEW')")
@PostMapping(value = "/taking")
@ApiOperation(value = "接单")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<Object> taking(@RequestBody RepRepairTakeOrders repRepairTakeOrders){
logger.debug("<---------------------------------"+JSON.toJSONString(repRepairTakeOrders));
repRepairApplyService.taking(repRepairTakeOrders);
return response();
}
/**
* 查询待接单任务数量
*/
@PreAuthorize("hasAuthority('REP_APPLY_TAKE_NEW')")
@GetMapping(value = "/waiTaking/{tenantid}")
@ApiOperation(value = "查询待接单任务数量")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<Integer> find(@PathVariable(value = "tenantid", required = true)String tenantid) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
int ret=repRepairApplyService.selectCountByTenantid(tenantid,authUser,1);
return response(ret);
}
/**
* 根据申请单id搜索接单信息
*/
@PreAuthorize("hasAuthority('REP_APPLY_TAKE_CHECK_VIEW')")
@GetMapping(value = "/search/{id}")
@ApiOperation(value = "根据申请单id搜索接单信息")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<RepRepairTakeOrders> search(@PathVariable(value = "id", required = true) Long id) {
Wrapper<RepRepairTakeOrders> wrapper=new EntityWrapper<RepRepairTakeOrders>();
wrapper.eq("apply_id", id);
wrapper.eq("del_flag", 0);
List<RepRepairTakeOrders> list=repRepairTakeOrdersService.selectList(wrapper);
if(!CollectionUtils.isEmpty(list)){
return response(list.get(0));
}
return response(null);
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepPartsRecord.java
package com.aek.ebey.repair.model;
import java.math.BigDecimal;
import java.util.Date;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* <p>
* 配件操作记录表
* </p>
*
* @author aek
* @since 2017-08-30
*/
@TableName("rep_parts_record")
@ApiModel(value = "RepPartsRecord", description = "配件操作记录信息")
public class RepPartsRecord extends BaseModel {
private static final long serialVersionUID = 1L;
/**
* 维修报告ID
*/
@ApiModelProperty(value="维修报告ID")
@TableField(value="report_id")
private Long reportId;
/**
* 机构id
*/
@ApiModelProperty(value="机构ID")
@TableField(value="tenant_id")
private Long tenantId;
/**
* 配件名称
*/
@ApiModelProperty(value="配件名称")
@TableField(value="part_name")
private String partName;
/**
* 规格型号
*/
@ApiModelProperty(value="规格型号")
@TableField(value="part_spec")
private String partSpec;
/**
* 配件生产商
*/
@ApiModelProperty(value="配件生产商")
@TableField(value="part_produce")
private String partProduce;
/**
* 配件单价
*/
@ApiModelProperty(value="配件单价")
@TableField(value="part_price")
private BigDecimal partPrice;
/**
* 计数单位
*/
@ApiModelProperty(value="计数单位")
private String unit;
/**
* 计数单位名称
*/
@ApiModelProperty(value="计数单位名称")
@TableField(exist=false)
private String unitName;
/**
* 操作数量
*/
@ApiModelProperty(value="操作数量")
private Integer num;
/**
* 操作类型(1领用 2 购买)
*/
@ApiModelProperty(value="操作类型(1领用 2 购买)")
private Integer status;
/**
* 操作时间
*/
@ApiModelProperty(value="操作时间")
@TableField(value="operation_time")
private Date operationTime=new Date();
/**
* 作废标记,0:启用,1:删除
*/
@TableField(value="del_flag")
private Boolean delFlag;
public Long getReportId() {
return reportId;
}
public void setReportId(Long reportId) {
this.reportId = reportId;
}
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
public String getPartName() {
return partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public String getPartSpec() {
return partSpec;
}
public void setPartSpec(String partSpec) {
this.partSpec = partSpec;
}
public String getPartProduce() {
return partProduce;
}
public void setPartProduce(String partProduce) {
this.partProduce = partProduce;
}
public BigDecimal getPartPrice() {
return partPrice;
}
public void setPartPrice(BigDecimal partPrice) {
this.partPrice = partPrice;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getOperationTime() {
return operationTime;
}
public void setOperationTime(Date operationTime) {
this.operationTime = operationTime;
}
public Boolean isDelFlag() {
return delFlag;
}
public void setDelFlag(Boolean delFlag) {
this.delFlag = delFlag;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepairDictionary.java
package com.aek.ebey.repair.model;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* <p>
*
* </p>
*
* @author aek
* @since 2017-08-30
*/
@ApiModel(value = "RepairDictionary", description = "字典信息")
@TableName("repair_dictionary")
public class RepairDictionary extends BaseModel {
private static final long serialVersionUID = 1L;
/**
* 关联类型
*/
@ApiModelProperty(value="关联类型")
@TableField(value="type_key")
private String typeKey;
/**
* 字典值
*/
@ApiModelProperty(value="字典值")
@TableField(value="key_id")
private Long keyId;
/**
* 字典名称
*/
@ApiModelProperty(value="字典名称")
private String name;
public String getTypeKey() {
return typeKey;
}
public void setTypeKey(String typeKey) {
this.typeKey = typeKey;
}
public Long getKeyId() {
return keyId;
}
public void setKeyId(Long keyId) {
this.keyId = keyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/ribbon/AuthClientService.java
package com.aek.ebey.repair.service.ribbon;
import java.util.List;
import java.util.Map;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.aek.common.core.Result;
import com.aek.ebey.repair.request.WeiXinRepairMessageRequest;
/**
* 用户远程调用接口value=${feign-auth.serviceId}
*
* @author HongHui
* @date 2017年12月13日
*/
@FeignClient(value="${feign-auth.serviceId}",fallback = AuthClientHystrix.class)
public interface AuthClientService {
/**
* 发送维修平台消息
* @param request
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/weixin/send/repair/message")
public Result<List<Map<String,Object>>> sendWeiXinRepairMessage(@RequestBody WeiXinRepairMessageRequest request,@RequestHeader("X-AEK56-Token") String token);
}<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairPartsServiceImpl.java
package com.aek.ebey.repair.service.impl;
import com.aek.ebey.repair.model.RepRepairParts;
import com.aek.ebey.repair.mapper.RepRepairPartsMapper;
import com.aek.ebey.repair.service.RepRepairPartsService;
import com.aek.common.core.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* 维修配件表 服务实现类
* </p>
*
* @author aek
* @since 2017-06-06
*/
@Service
@Transactional
public class RepRepairPartsServiceImpl extends BaseServiceImpl<RepRepairPartsMapper, RepRepairParts> implements RepRepairPartsService {
}
<file_sep>/aek-repair-web-api/src/main/resources/sql/rep_parts_record.sql
/*
Navicat MySQL Data Transfer
Source Server : 6446
Source Server Version : 50718
Source Host : mysqlcluster.aek.com:6446
Source Database : repair_dev
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2017-07-19 13:57:00
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for rep_parts_record
-- ----------------------------
DROP TABLE IF EXISTS `rep_parts_record`;
CREATE TABLE `rep_parts_record` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id主键',
`report_id` bigint(20) DEFAULT NULL COMMENT '维修报告ID',
`tenant_id` bigint(20) DEFAULT NULL COMMENT '机构id',
`part_id` bigint(20) DEFAULT NULL COMMENT '关联配件Id',
`part_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '配件名称',
`part_spec` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '规格型号',
`part_produce` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '配件生产商',
`part_price` bigint(20) DEFAULT NULL COMMENT '配件单价',
`unit_key` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '计数单位字典表',
`num` smallint(3) DEFAULT NULL COMMENT '操作数量',
`status` tinyint(1) DEFAULT NULL COMMENT '操作类型(1入库 2 出库)',
`operation_time` datetime DEFAULT NULL COMMENT '操作时间',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='配件操作记录表';
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairBillServiceImpl.java
package com.aek.ebey.repair.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aek.common.core.base.BaseServiceImpl;
import com.aek.common.core.exception.BusinessException;
import com.aek.common.core.exception.ExceptionFactory;
import com.aek.common.core.serurity.WebSecurityUtils;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.core.BeanMapper;
import com.aek.ebey.repair.enums.RepairBillCheckStatusEnum;
import com.aek.ebey.repair.mapper.RepRepairBillCheckFlowMapper;
import com.aek.ebey.repair.mapper.RepRepairBillMapper;
import com.aek.ebey.repair.model.RepRepairBill;
import com.aek.ebey.repair.model.RepRepairBillCheckConfig;
import com.aek.ebey.repair.model.RepRepairBillCheckFlow;
import com.aek.ebey.repair.model.RepRepairBillFile;
import com.aek.ebey.repair.model.RepRepairBillParts;
import com.aek.ebey.repair.query.RepRepairBillApproveQuery;
import com.aek.ebey.repair.query.RepRepairBillQuery;
import com.aek.ebey.repair.request.RepRepairBillApproveResponse;
import com.aek.ebey.repair.request.RepRepairBillCheckRequest;
import com.aek.ebey.repair.request.RepRepairBillDetailResponse;
import com.aek.ebey.repair.request.RepRepairBillLogResponse;
import com.aek.ebey.repair.request.RepRepairBillPrintDetailResponse;
import com.aek.ebey.repair.request.SendMessage;
import com.aek.ebey.repair.service.RepRepairBillCheckConfigService;
import com.aek.ebey.repair.service.RepRepairBillCheckFlowService;
import com.aek.ebey.repair.service.RepRepairBillFileService;
import com.aek.ebey.repair.service.RepRepairBillPartsService;
import com.aek.ebey.repair.service.RepRepairBillService;
import com.aek.ebey.repair.service.RepRepairMessageService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
/**
* 维修单据申请服务实现类
*
* @author HongHui
* @date 2018年1月29日
*/
@Service
@Transactional
public class RepRepairBillServiceImpl extends BaseServiceImpl<RepRepairBillMapper, RepRepairBill> implements RepRepairBillService {
private static final Logger logger = LoggerFactory.getLogger(RepRepairBillServiceImpl.class);
@Autowired
private RepRepairBillMapper repRepairBillMapper;
@Autowired
private RepRepairBillCheckFlowMapper repRepairBillCheckFlowMapper;
@Autowired
private RepRepairBillFileService repRepairBillFileService;
@Autowired
private RepRepairBillPartsService repRepairBillPartsService;
@Autowired
private RepRepairBillCheckConfigService repRepairBillCheckConfigService;
@Autowired
private RepRepairBillCheckFlowService repRepairBillCheckFlowService;
@Autowired
private RepRepairMessageService repRepairMessageService;
@Override
public void save(RepRepairBill repRepairBill, List<RepRepairBillParts> billParts,
List<RepRepairBillFile> billFiles) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
// 保存维修申请单、附件、配件等信息
repRepairBillMapper.insert(repRepairBill);
if(null != billFiles && billFiles.size() > 0){
for (RepRepairBillFile repRepairBillFile : billFiles) {
repRepairBillFile.setBillId(repRepairBill.getId());
}
repRepairBillFileService.insertBatch(billFiles);
}
if(null != billParts && billParts.size() > 0){
for (RepRepairBillParts repRepairBillPart : billParts) {
repRepairBillPart.setBillId(repRepairBill.getId());
repRepairBillPart.setCreateTime(new Date());
}
repRepairBillPartsService.insertBatch(billParts);
}
// 判断机构是否已经配置审批流程
List<RepRepairBillCheckConfig> repRepairBillCheckConfigListByTenant = repRepairBillCheckConfigService.getRepRepairBillCheckConfig(authUser.getTenantId());
if(null == repRepairBillCheckConfigListByTenant || (null != repRepairBillCheckConfigListByTenant && repRepairBillCheckConfigListByTenant.size() == 0)){
throw ExceptionFactory.create("B_005");
}
RepRepairBillCheckConfig minConfig = repRepairBillCheckConfigListByTenant.get(0);
if(repRepairBill.getFee().compareTo(minConfig.getMinFee()) == -1){
throw new BusinessException("B_009", "金额未达标,申请金额必须不小于"+minConfig.getMinFee());
}
// 根据单据费用大小获取当前机构审批流程配置信息,按index正序排序
List<RepRepairBillCheckConfig> repRepairBillCheckConfigList = repRepairBillCheckConfigService.getRepRepairBillCheckConfig(authUser.getTenantId(),repRepairBill.getFee());
// 保存当前机构审批流程
for (RepRepairBillCheckConfig repRepairBillCheckConfig : repRepairBillCheckConfigList) {
RepRepairBillCheckFlow repRepairBillCheckFlow = new RepRepairBillCheckFlow();
repRepairBillCheckFlow.setBillId(repRepairBill.getId());
repRepairBillCheckFlow.setCheckStatus(RepairBillCheckStatusEnum.WAIT_CHECK.getNumber());
repRepairBillCheckFlow.setCheckUserId(repRepairBillCheckConfig.getCheckUserId());
repRepairBillCheckFlow.setCheckUserName(repRepairBillCheckConfig.getCheckUserName());
repRepairBillCheckFlow.setCheckUserMobile(repRepairBillCheckConfig.getCheckUserMobile());
repRepairBillCheckFlow.setIndex(repRepairBillCheckConfig.getIndex());
repRepairBillCheckFlow.setFlowName(repRepairBillCheckConfig.getIndexName());
repRepairBillCheckFlowMapper.insert(repRepairBillCheckFlow);
}
// 设置当前单据审批流程为排序最前的流程
RepRepairBillCheckConfig repRepairBillCheckConfig = repRepairBillCheckConfigList.get(0);
repRepairBill.setCurrentIndex(repRepairBillCheckConfig == null ? null : repRepairBillCheckConfig.getIndex());
repRepairBill.setTotalIndex(repRepairBillCheckConfigList.size());
repRepairBillMapper.updateById(repRepairBill);
}
@Override
public Page<RepRepairBill> getRepairBillPage(RepRepairBillQuery query) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
Page<RepRepairBill> page = query.getPage();
Wrapper<RepRepairBill> wrapper = new EntityWrapper<RepRepairBill>();
if (query.getTenantId() != null) {
wrapper.eq("tenant_id", query.getTenantId());
}
if (query.getApplyType() != null && query.getApplyType() == 1) {
wrapper.eq("apply_user_id", authUser.getId());
}
if (query.getStatus() != null) {
wrapper.eq("status", query.getStatus());
}
if (query.getType() != null) {
wrapper.eq("type", query.getType());
}
String keyword = StringUtils.trimToNull(query.getKeyword());
if (keyword != null) {
if (keyword.startsWith("%") || keyword.startsWith("[") || keyword.startsWith("[]")
|| keyword.startsWith("_")) {
wrapper.andNew("assets_name LIKE {0} OR bill_no LIKE {0}", "%[" + keyword + "]%");
} else {
wrapper.andNew("assets_name LIKE {0} OR bill_no LIKE {0}", "%" + keyword + "%");
}
}
wrapper.orderBy("status", true).orderBy("apply_time", false);
return this.selectPage(page, wrapper);
}
@Override
public RepRepairBillDetailResponse getBillDetails(Long id) {
// 维修单据
RepRepairBill repRepairBill = repRepairBillMapper.selectById(id);
// 维修单据附件
List<RepRepairBillFile> repRepairBillFileList = repRepairBillFileService.getRepRepairBillFile(repRepairBill.getId());
// 维修单据配件
List<RepRepairBillParts> repRepairBillPartsList = repRepairBillPartsService.getRepRepairBillParts(repRepairBill.getId());
List<RepRepairBillLogResponse> repRepairBillLogList = new ArrayList<RepRepairBillLogResponse>();
// 申请日志
RepRepairBillLogResponse applyLog = new RepRepairBillLogResponse();
applyLog.setOperator(repRepairBill.getApplyUserName());
applyLog.setOperateName("提交申请");
applyLog.setOperateStatus(0);
applyLog.setOperateTime(repRepairBill.getApplyTime());
repRepairBillLogList.add(applyLog);
// 单据审批流程
Long currentCheckUserId = null;
List<RepRepairBillCheckFlow> repRepairBillCheckFlowList = repRepairBillCheckFlowService.getRepRepairBillCheckFlow(repRepairBill.getId());
for (RepRepairBillCheckFlow repRepairBillCheckFlow : repRepairBillCheckFlowList) {
RepRepairBillLogResponse checkFlowLog = new RepRepairBillLogResponse();
checkFlowLog.setCheckFlowId(repRepairBillCheckFlow.getId());
checkFlowLog.setOperateStatus(repRepairBillCheckFlow.getCheckStatus());
Integer checkStatus = repRepairBillCheckFlow.getCheckStatus();
String operateName = "待审批";
if(checkStatus==1){operateName="待审批";}
if(checkStatus==2){operateName="审批通过";}
if(checkStatus==3){operateName="审批未通过";}
checkFlowLog.setOperateName(operateName);
checkFlowLog.setOperateTime(repRepairBillCheckFlow.getCheckTime());
checkFlowLog.setOperator(repRepairBillCheckFlow.getCheckUserName());
repRepairBillLogList.add(checkFlowLog);
if(repRepairBill.getCurrentIndex()==repRepairBillCheckFlow.getIndex()){
currentCheckUserId = repRepairBillCheckFlow.getCheckUserId();
}
}
RepRepairBillDetailResponse repRepairBillDetailResponse = BeanMapper.map(repRepairBill, RepRepairBillDetailResponse.class);
repRepairBillDetailResponse.setBillFiles(repRepairBillFileList);
repRepairBillDetailResponse.setBillLogs(repRepairBillLogList);
repRepairBillDetailResponse.setBillParts(repRepairBillPartsList);
repRepairBillDetailResponse.setCurrentCheckUserId(currentCheckUserId);
return repRepairBillDetailResponse;
}
@Override
public RepRepairBillPrintDetailResponse getBillPrintDetails(Long id) {
// 维修单据
RepRepairBill repRepairBill = repRepairBillMapper.selectById(id);
// 维修单据附件
List<RepRepairBillFile> repRepairBillFileList = repRepairBillFileService.getRepRepairBillFile(repRepairBill.getId());
// 维修单据配件
List<RepRepairBillParts> repRepairBillPartsList = repRepairBillPartsService.getRepRepairBillParts(repRepairBill.getId());
// 单据审批流程
List<RepRepairBillCheckFlow> repRepairBillCheckFlowList = repRepairBillCheckFlowService.getRepRepairBillCheckFlow(repRepairBill.getId());
// 已审批流程
List<RepRepairBillCheckFlow> repRepairBillCheckFlowCheckedList = new ArrayList<RepRepairBillCheckFlow>();
for (RepRepairBillCheckFlow repRepairBillCheckFlow : repRepairBillCheckFlowList) {
Integer checkStatus = repRepairBillCheckFlow.getCheckStatus();
String checkStatusText = "待审批";
if(checkStatus==1){checkStatusText="待审批";}
if(checkStatus==2){checkStatusText="审批通过";}
if(checkStatus==3){checkStatusText="审批未通过";}
repRepairBillCheckFlow.setCheckStatusText(checkStatusText);
if(checkStatus != 1){
repRepairBillCheckFlowCheckedList.add(repRepairBillCheckFlow);
}
}
RepRepairBillPrintDetailResponse repRepairBillPrintDetailResponse = BeanMapper.map(repRepairBill, RepRepairBillPrintDetailResponse.class);
repRepairBillPrintDetailResponse.setBillFiles(repRepairBillFileList);
repRepairBillPrintDetailResponse.setBillFlows(repRepairBillCheckFlowList);
repRepairBillPrintDetailResponse.setBillParts(repRepairBillPartsList);
//设置审批时间
if(repRepairBillCheckFlowCheckedList.size() > 0){
RepRepairBillCheckFlow lastCheckFlow = repRepairBillCheckFlowCheckedList.get(repRepairBillCheckFlowCheckedList.size()-1);
repRepairBillPrintDetailResponse.setCheckTime(lastCheckFlow==null ? null : lastCheckFlow.getCheckTime());
}
return repRepairBillPrintDetailResponse;
}
@Override
public Page<RepRepairBillApproveResponse> getRepairBillApprovePage(RepRepairBillApproveQuery query) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
Page<RepRepairBillApproveResponse> page = query.getPage();
List<RepRepairBillApproveResponse> list=repRepairBillCheckFlowService.getRepairBillApprovePage(page,query,authUser);
for (RepRepairBillApproveResponse repRepairBillResponse : list) {
repRepairBillResponse.setTypeText(repRepairBillResponse.getType()==1?"外修费用":"配件采购");
Integer status = repRepairBillResponse.getStatus();
String statusText = "审批中";
if(status==1){statusText="审批中";}
if(status==2){statusText="审批通过";}
if(status==3){statusText="审批未通过";}
if(status==4){statusText="已撤销";}
repRepairBillResponse.setStatusText(statusText);
}
page.setRecords(list);
return page;
}
@Override
public void selectCheck(RepRepairBillCheckRequest request) {
Long id=request.getId();
AuthUser authUser = WebSecurityUtils.getCurrentUser();
RepRepairBill repRepairBill=repRepairBillMapper.selectById(id);
if(repRepairBill!=null){
if(1==repRepairBill.getStatus().intValue()){
int index=repRepairBill.getCurrentIndex();
Wrapper<RepRepairBillCheckFlow> wrapper=new EntityWrapper<>();
wrapper.eq("bill_id", id).eq("`index`", index).eq("check_user_id", authUser.getId()).eq("check_status", 1);
RepRepairBillCheckFlow repRepairBillCheckFlow= repRepairBillCheckFlowService.selectOne(wrapper);
if(repRepairBillCheckFlow!=null){
repRepairBillCheckFlow.setCheckStatus(request.getStatus());
repRepairBillCheckFlow.setCheckRemark(request.getRemark());
repRepairBillCheckFlow.setCheckTime(new Date());
repRepairBillCheckFlowService.updateById(repRepairBillCheckFlow);
//审批不通过
if(request.getStatus().intValue()==3){
repRepairBill.setStatus(3);
SendMessage message=new SendMessage();
message.setModuleId(repRepairBill.getId());
message.setRemarks(repRepairBill.getAssetsDeptName());
message.setMessageContent("维修单据审批未通过,查看详情");
message.setStatus(2);
message.setUserId(repRepairBill.getApplyUserId());
repRepairMessageService.save(message);
}else{
if(repRepairBill.getCurrentIndex().intValue()==repRepairBill.getTotalIndex().intValue()){
repRepairBill.setStatus(request.getStatus());
SendMessage message=new SendMessage();
message.setModuleId(repRepairBill.getId());
message.setRemarks(repRepairBill.getAssetsDeptName());
message.setMessageContent("维修单据审批通过,查看详情");
message.setStatus(2);
message.setUserId(repRepairBill.getApplyUserId());
repRepairMessageService.save(message);
}else{
repRepairBill.setCurrentIndex(repRepairBill.getCurrentIndex()+1);
}
}
repRepairBillMapper.updateById(repRepairBill);
}else{
throw ExceptionFactory.create("W_027");
}
}else if(2==repRepairBill.getStatus().intValue()){
throw ExceptionFactory.create("W_024");
}else if(3==repRepairBill.getStatus().intValue()){
throw ExceptionFactory.create("W_025");
}else if(4==repRepairBill.getStatus().intValue()){
throw ExceptionFactory.create("W_026");
}
}
}
@Override
public Page<RepRepairBillApproveResponse> getRepairBillApprovePage2(RepRepairBillApproveQuery query) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
Page<RepRepairBillApproveResponse> page = query.getPage();
List<RepRepairBillApproveResponse> list=repRepairBillCheckFlowService.getRepairBillApprovePage2(page,query,authUser);
for (RepRepairBillApproveResponse repRepairBillResponse : list) {
repRepairBillResponse.setTypeText(repRepairBillResponse.getType()==1?"外修费用":"配件采购");
Integer status = repRepairBillResponse.getStatus();
String statusText = "审批中";
if(status==1){statusText="审批中";}
if(status==2){statusText="审批通过";}
if(status==3){statusText="审批未通过";}
if(status==4){statusText="已撤销";}
repRepairBillResponse.setStatusText(statusText);
}
page.setRecords(list);
return page;
}
@Override
public RepRepairBillDetailResponse getBillDetails2(Long id) {
// 维修单据
RepRepairBill repRepairBill = repRepairBillMapper.selectById(id);
if(repRepairBill.getStatus().intValue()!=4){
// 维修单据附件
List<RepRepairBillFile> repRepairBillFileList = repRepairBillFileService.getRepRepairBillFile(repRepairBill.getId());
// 维修单据配件
List<RepRepairBillParts> repRepairBillPartsList = repRepairBillPartsService.getRepRepairBillParts(repRepairBill.getId());
List<RepRepairBillLogResponse> repRepairBillLogList = new ArrayList<RepRepairBillLogResponse>();
// 申请日志
RepRepairBillLogResponse applyLog = new RepRepairBillLogResponse();
applyLog.setOperator(repRepairBill.getApplyUserName());
applyLog.setOperateName("提交申请");
applyLog.setOperateStatus(0);
applyLog.setOperateTime(repRepairBill.getApplyTime());
repRepairBillLogList.add(applyLog);
// 单据审批流程
Long currentCheckUserId = null;
List<RepRepairBillCheckFlow> repRepairBillCheckFlowList = repRepairBillCheckFlowService.getRepRepairBillCheckFlow(repRepairBill.getId());
for (RepRepairBillCheckFlow repRepairBillCheckFlow : repRepairBillCheckFlowList) {
RepRepairBillLogResponse checkFlowLog = new RepRepairBillLogResponse();
checkFlowLog.setCheckFlowId(repRepairBillCheckFlow.getId());
checkFlowLog.setOperateStatus(repRepairBillCheckFlow.getCheckStatus());
Integer checkStatus = repRepairBillCheckFlow.getCheckStatus();
String operateName = "待审批";
if(checkStatus==1){operateName="待审批";}
if(checkStatus==2){operateName="审批通过";}
if(checkStatus==3){operateName="审批未通过";}
checkFlowLog.setOperateName(operateName);
checkFlowLog.setOperateTime(repRepairBillCheckFlow.getCheckTime());
checkFlowLog.setOperator(repRepairBillCheckFlow.getCheckUserName());
repRepairBillLogList.add(checkFlowLog);
if(repRepairBill.getCurrentIndex()==repRepairBillCheckFlow.getIndex()){
currentCheckUserId = repRepairBillCheckFlow.getCheckUserId();
}
}
RepRepairBillDetailResponse repRepairBillDetailResponse = BeanMapper.map(repRepairBill, RepRepairBillDetailResponse.class);
repRepairBillDetailResponse.setBillFiles(repRepairBillFileList);
repRepairBillDetailResponse.setBillLogs(repRepairBillLogList);
repRepairBillDetailResponse.setBillParts(repRepairBillPartsList);
repRepairBillDetailResponse.setCurrentCheckUserId(currentCheckUserId);
return repRepairBillDetailResponse;
}else{
throw ExceptionFactory.create("W_026");
}
}
@Override
public Integer getWaitToDo(Long id) {
int i=repRepairBillCheckFlowService.getWaitToDo(id);
return i;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepRepairBill.java
package com.aek.ebey.repair.model;
import java.math.BigDecimal;
import java.util.Date;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 维修单据实体类
*
* @author HongHui
* @date 2018年1月26日
*/
@ApiModel(value = "RepRepairBill", description = "维修单据信息")
@TableName("rep_repair_bill")
public class RepRepairBill extends BaseModel {
private static final long serialVersionUID = -5974521429622544132L;
/**
* 机构ID
*/
@ApiModelProperty(value="机构ID")
@TableField(value="tenant_id")
private Long tenantId;
/**
* 机构名称
*/
@ApiModelProperty(value="机构名称")
@TableField(value="tenant_name")
private String tenantName;
/**
* 单据编号
*/
@ApiModelProperty(value="审单据编号")
@TableField(value="bill_no")
private String billNo;
/**
* 单据类型(1=外修费用,2=配件采购)
*/
@ApiModelProperty(value="单据类型(1=外修费用,2=配件采购)")
@TableField(value="type")
private Integer type;
/**
* 单据类型文本(1=外修费用,2=配件采购)
*/
@ApiModelProperty(value="单据类型文本(1=外修费用,2=配件采购)")
@TableField(exist=false)
private String typeText;
/**
* 状态(1=审批中,2=审批通过,3=审批未通过,4=已撤销)
*/
@ApiModelProperty(value="状态(1=审批中,2=审批通过,3=审批未通过,4=已撤销)")
@TableField(value="status")
private Integer status;
/**
* 状态文本(1=审批中,2=审批通过,3=审批未通过,4=已撤销)
*/
@ApiModelProperty(value="状态文本(1=审批中,2=审批通过,3=审批未通过,4=已撤销)")
@TableField(exist=false)
private String statusText;
/**
* 维修申请单ID
*/
@ApiModelProperty(value="维修申请单ID")
@TableField(value="apply_id")
private Long applyId;
/**
* 维修单号
*/
@ApiModelProperty(value="维修单号")
@TableField(value="apply_no")
private String applyNo;
/**
* 维修设备名称
*/
@ApiModelProperty(value="维修设备名称")
@TableField(value="assets_name")
private String assetsName;
/**
* 设备使用科室名称
*/
@ApiModelProperty(value="设备使用科室名称")
@TableField(value="assets_dept_name")
private String assetsDeptName;
/**
* 设备规格型号
*/
@ApiModelProperty(value="设备规格型号")
@TableField(value="assets_spec")
private String assetsSpec;
/**
* 设备院内编码
*/
@ApiModelProperty(value="设备院内编码")
@TableField(value="serial_num")
private String serialNum;
/**
* 设备启用日期
*/
@ApiModelProperty(value="设备启用日期")
@TableField(value="start_use_date")
private Date startUseDate;
/**
* 维修申请日期
*/
@ApiModelProperty(value="维修申请日期")
@TableField(value="report_repair_date")
private Date reportRepairDate;
/**
* 外修单位
*/
@ApiModelProperty(value="外修单位")
@TableField(value="external_repair_company")
private String externalRepairCompany;
/**
* 申请人ID
*/
@ApiModelProperty(value="申请人ID")
@TableField(value="apply_user_id")
private Long applyUserId;
/**
* 申请人姓名
*/
@ApiModelProperty(value="申请人姓名")
@TableField(value="apply_user_name")
private String applyUserName;
/**
* 申请人所在科室
*/
@ApiModelProperty(value="申请人所在科室")
@TableField(value="apply_user_dept_name")
private String applyUserDeptName;
/**
* 申请时间
*/
@ApiModelProperty(value="申请时间")
@TableField(value="apply_time")
private Date applyTime;
/**
* 费用金额
*/
@ApiModelProperty(value="费用金额")
@TableField(value="fee")
private BigDecimal fee;
/**
* 备注信息
*/
@ApiModelProperty(value="备注信息")
@TableField(value="remark")
private String remark;
/**
* 审批流程所处序号
*/
@ApiModelProperty(value="审批流程所处序号")
@TableField(value="current_index")
private Integer currentIndex;
/**
* 审批流程总共的序号
*/
@ApiModelProperty(value="审批流程总共的序号")
@TableField(value="total_index")
private Integer totalIndex;
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getApplyNo() {
return applyNo;
}
public void setApplyNo(String applyNo) {
this.applyNo = applyNo;
}
public String getAssetsName() {
return assetsName;
}
public void setAssetsName(String assetsName) {
this.assetsName = assetsName;
}
public String getAssetsDeptName() {
return assetsDeptName;
}
public void setAssetsDeptName(String assetsDeptName) {
this.assetsDeptName = assetsDeptName;
}
public String getExternalRepairCompany() {
return externalRepairCompany;
}
public void setExternalRepairCompany(String externalRepairCompany) {
this.externalRepairCompany = externalRepairCompany;
}
public Long getApplyUserId() {
return applyUserId;
}
public void setApplyUserId(Long applyUserId) {
this.applyUserId = applyUserId;
}
public Date getApplyTime() {
return applyTime;
}
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Integer getCurrentIndex() {
return currentIndex;
}
public void setCurrentIndex(Integer currentIndex) {
this.currentIndex = currentIndex;
}
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public String getApplyUserName() {
return applyUserName;
}
public void setApplyUserName(String applyUserName) {
this.applyUserName = applyUserName;
}
public String getAssetsSpec() {
return assetsSpec;
}
public void setAssetsSpec(String assetsSpec) {
this.assetsSpec = assetsSpec;
}
public String getSerialNum() {
return serialNum;
}
public void setSerialNum(String serialNum) {
this.serialNum = serialNum;
}
public Date getStartUseDate() {
return startUseDate;
}
public void setStartUseDate(Date startUseDate) {
this.startUseDate = startUseDate;
}
public Date getReportRepairDate() {
return reportRepairDate;
}
public void setReportRepairDate(Date reportRepairDate) {
this.reportRepairDate = reportRepairDate;
}
public String getTenantName() {
return tenantName;
}
public void setTenantName(String tenantName) {
this.tenantName = tenantName;
}
public String getApplyUserDeptName() {
return applyUserDeptName;
}
public void setApplyUserDeptName(String applyUserDeptName) {
this.applyUserDeptName = applyUserDeptName;
}
public Integer getTotalIndex() {
return totalIndex;
}
public void setTotalIndex(Integer totalIndex) {
this.totalIndex = totalIndex;
}
/* @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((applyId == null) ? 0 : applyId.hashCode());
result = prime * result + ((applyNo == null) ? 0 : applyNo.hashCode());
result = prime * result + ((applyTime == null) ? 0 : applyTime.hashCode());
result = prime * result + ((applyUserId == null) ? 0 : applyUserId.hashCode());
result = prime * result + ((assetsDeptName == null) ? 0 : assetsDeptName.hashCode());
result = prime * result + ((assetsName == null) ? 0 : assetsName.hashCode());
result = prime * result + ((billNo == null) ? 0 : billNo.hashCode());
result = prime * result + ((currentIndex == null) ? 0 : currentIndex.hashCode());
result = prime * result + ((externalRepairCompany == null) ? 0 : externalRepairCompany.hashCode());
result = prime * result + ((fee == null) ? 0 : fee.hashCode());
result = prime * result + ((remark == null) ? 0 : remark.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RepRepairBill other = (RepRepairBill) obj;
if (applyId == null) {
if (other.applyId != null)
return false;
} else if (!applyId.equals(other.applyId))
return false;
if (applyNo == null) {
if (other.applyNo != null)
return false;
} else if (!applyNo.equals(other.applyNo))
return false;
if (applyTime == null) {
if (other.applyTime != null)
return false;
} else if (!applyTime.equals(other.applyTime))
return false;
if (applyUserId == null) {
if (other.applyUserId != null)
return false;
} else if (!applyUserId.equals(other.applyUserId))
return false;
if (assetsDeptName == null) {
if (other.assetsDeptName != null)
return false;
} else if (!assetsDeptName.equals(other.assetsDeptName))
return false;
if (assetsName == null) {
if (other.assetsName != null)
return false;
} else if (!assetsName.equals(other.assetsName))
return false;
if (billNo == null) {
if (other.billNo != null)
return false;
} else if (!billNo.equals(other.billNo))
return false;
if (currentIndex == null) {
if (other.currentIndex != null)
return false;
} else if (!currentIndex.equals(other.currentIndex))
return false;
if (externalRepairCompany == null) {
if (other.externalRepairCompany != null)
return false;
} else if (!externalRepairCompany.equals(other.externalRepairCompany))
return false;
if (fee == null) {
if (other.fee != null)
return false;
} else if (!fee.equals(other.fee))
return false;
if (remark == null) {
if (other.remark != null)
return false;
} else if (!remark.equals(other.remark))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}*/
public String getStatusText() {
return statusText;
}
public void setStatusText(String statusText) {
this.statusText = statusText;
}
public String getTypeText() {
return typeText;
}
public void setTypeText(String typeText) {
this.typeText = typeText;
}
@Override
public String toString() {
return "RepRepairBill [tenantId=" + tenantId + ", billNo=" + billNo + ", type=" + type + ", status=" + status
+ ", applyId=" + applyId + ", applyNo=" + applyNo + ", assetsName=" + assetsName + ", assetsDeptName="
+ assetsDeptName + ", externalRepairCompany=" + externalRepairCompany + ", applyUserId=" + applyUserId
+ ", applyTime=" + applyTime + ", fee=" + fee + ", remark=" + remark + ", currentIndex=" + currentIndex
+ "]";
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/vo/RepLargeScreenDataVo.java
package com.aek.ebey.repair.model.vo;
import java.io.Serializable;
import java.util.List;
/**
* 维修大屏统计数据
*
* @author HongHui
* @date 2018年4月17日
*/
public class RepLargeScreenDataVo implements Serializable{
private static final long serialVersionUID = -5331529467131905703L;
//待接单总数
private Long waitTakeNum;
//维修中总数
private Long repairingNum;
//待验收总数
private Long waitCheckNum;
//工程师数
private Integer engineerNum;
//本周保修数
private Long currentWeekApplyNum;
//本周完修数
private Long currentWeekCompleteNum;
//本月保修数
private Long currentMonthApplyNum;
//本月完修数
private Long currentMonthCompleteNum;
//维修申请单集合
private List<RepRepairApplyVo> repairApplyList;
public Long getWaitTakeNum() {
return waitTakeNum;
}
public void setWaitTakeNum(Long waitTakeNum) {
this.waitTakeNum = waitTakeNum;
}
public Long getRepairingNum() {
return repairingNum;
}
public void setRepairingNum(Long repairingNum) {
this.repairingNum = repairingNum;
}
public Long getWaitCheckNum() {
return waitCheckNum;
}
public void setWaitCheckNum(Long waitCheckNum) {
this.waitCheckNum = waitCheckNum;
}
public Integer getEngineerNum() {
return engineerNum;
}
public void setEngineerNum(Integer engineerNum) {
this.engineerNum = engineerNum;
}
public Long getCurrentWeekApplyNum() {
return currentWeekApplyNum;
}
public void setCurrentWeekApplyNum(Long currentWeekApplyNum) {
this.currentWeekApplyNum = currentWeekApplyNum;
}
public Long getCurrentWeekCompleteNum() {
return currentWeekCompleteNum;
}
public void setCurrentWeekCompleteNum(Long currentWeekCompleteNum) {
this.currentWeekCompleteNum = currentWeekCompleteNum;
}
public Long getCurrentMonthApplyNum() {
return currentMonthApplyNum;
}
public void setCurrentMonthApplyNum(Long currentMonthApplyNum) {
this.currentMonthApplyNum = currentMonthApplyNum;
}
public Long getCurrentMonthCompleteNum() {
return currentMonthCompleteNum;
}
public void setCurrentMonthCompleteNum(Long currentMonthCompleteNum) {
this.currentMonthCompleteNum = currentMonthCompleteNum;
}
public List<RepRepairApplyVo> getRepairApplyList() {
return repairApplyList;
}
public void setRepairApplyList(List<RepRepairApplyVo> repairApplyList) {
this.repairApplyList = repairApplyList;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/query/RepPartsRecordQuery.java
package com.aek.ebey.repair.query;
import com.aek.common.core.base.page.PageHelp;
import com.aek.ebey.repair.model.RepPartsRecord;
import com.aek.ebey.repair.request.RepPartsRecordResponse;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepPartsRecordQuery", description = "操作记录查询query")
public class RepPartsRecordQuery extends PageHelp<RepPartsRecord> {
/**
* 配件名称
*/
@ApiModelProperty(value="配件名称")
private String partName;
/**
* 操作类型(1入库 2 出库)
*/
@ApiModelProperty(value="操作类型(1入库 2 出库)")
private String status;
public String getPartName() {
return partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/validator/group/GET.java
package com.aek.ebey.repair.web.validator.group;
public interface GET {
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairBillFileServiceImpl.java
package com.aek.ebey.repair.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aek.common.core.base.BaseServiceImpl;
import com.aek.ebey.repair.mapper.RepRepairBillFileMapper;
import com.aek.ebey.repair.model.RepRepairBillFile;
import com.aek.ebey.repair.service.RepRepairBillFileService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
/**
* 维修单据申请服务实现类
*
* @author HongHui
* @date 2018年1月29日
*/
@Service
@Transactional
public class RepRepairBillFileServiceImpl extends BaseServiceImpl<RepRepairBillFileMapper, RepRepairBillFile> implements RepRepairBillFileService {
private static final Logger logger = LoggerFactory.getLogger(RepRepairBillFileServiceImpl.class);
@Autowired
private RepRepairBillFileMapper repRepairBillFileMapper;
@Override
public List<RepRepairBillFile> getRepRepairBillFile(Long billId) {
Wrapper<RepRepairBillFile> wrapper=new EntityWrapper<RepRepairBillFile>();
wrapper.eq("bill_id", billId);
List<RepRepairBillFile> list=repRepairBillFileMapper.selectList(wrapper);
return list;
}
}
<file_sep>/aek-repair-web-api/src/main/resources/sql/v3.1.0.sql
ALTER TABLE rep_repair_report MODIFY COLUMN repair_start_date datetime DEFAULT NULL COMMENT '维修开始日期(申请时间)';
ALTER TABLE rep_repair_report MODIFY COLUMN repair_end_date datetime DEFAULT NULL COMMENT '维修结束日期(完修时间-提交维修报告时间)';
ALTER TABLE rep_repair_report MODIFY COLUMN actual_start_date datetime DEFAULT NULL COMMENT '实际开始时间(接单时间)';
ALTER TABLE rep_repair_report MODIFY COLUMN actual_end_date datetime DEFAULT NULL COMMENT '实际结束时间(维修时间-实际维修开始时间)';
commit;
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/inter/RepairMessage.java
package com.aek.ebey.repair.inter;
public interface RepairMessage {
/** 现场解决 */
public static final String REPAIREDCONTENT = "【验收提醒】维修申请已鉴定完成,状态变更为已现场解决,查看详情;";
/** 待维修 */
public static final String WAITREPAIRCONTENT = "【维修提醒】维修申请已鉴定完成,状态变更为待维修,查看详情;";
/** 待故障鉴定*/
public static final String WAITAPPRAISALCONTENT = "【鉴定提醒】新建维修申请,状态变更为待故障鉴定,查看详情;";
/** 鉴定提醒*/
public static final String WARNAPPRAISALCONTENT = "【鉴定提醒】鉴定提醒,请尽快去鉴定设备";
/** 维修 提醒*/
public static final String WARNREPAIRCONTENT = "【维修提醒】维修申请已鉴定完成,状态变更为待维修,查看详情;";
/** 验收未通过*/
public static final String UNCHECKCONTENT = "【验收未通过】验收未通过,状态变更为验收未通过,查看详情;";
/** 验收通过*/
public static final String CHECKEDCONTENT = "【已完成】验收通过,状态变更为已完成,查看详情;";
/** 已维修待验收*/
public static final String WAITCHECKCONTENT = "【验收提醒】设备维修完成,状态变更为已维修待验收,查看详情;";
/** 验收提醒*/
public static final String WARNCHECKCONTENT = "【验收提醒】验收提醒,请尽快去验收设备";
/** 维修完成*/
public static final String COMPLETE = "维修已完成,查看详情";
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepRepairReport.java
package com.aek.ebey.repair.model;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* <p>
* 维修报告
* </p>
*
* @author aek
* @since 2017-08-30
*/
@TableName("rep_repair_report")
@ApiModel(value = "RepRepairReport", description = "维修报告单")
public class RepRepairReport extends BaseModel {
private static final long serialVersionUID = 1L;
/**
* 关联申请单ID
*/
@TableField(value="apply_id")
@ApiModelProperty(value="关联申请单id")
private Long applyId;
/**
* 维修方式(1,自主维修 2,外修 3,现场解决)
*/
@TableField(value="mode_status")
@ApiModelProperty(value="维修方式(1,自主维修 2,外修 3,现场解决)")
private Integer modeStatus;
/**
* 外修单位
*/
@TableField(value="outside_company")
@ApiModelProperty(value="外修单位")
private String outsideCompany;
/**
* 外修电话
*/
@TableField(value="outside_phone")
@ApiModelProperty(value="外修电话")
private String outsidePhone;
/**
* 附件
*/
@ApiModelProperty(value="附件")
private String attachment;
/**
* 故障类型(1,故障维修2,预防性维修3,计量检测性维修 4,质保期内维修 5,厂家合同维修 6,第三方合同维修 7,临时叫修)
*/
@TableField(value="fault_type")
@ApiModelProperty(value="故障类型(1,故障维修2,预防性维修3,计量检测性维修 4,质保期内维修 5,厂家合同维修 6,第三方合同维修 7,临时叫修)")
private Integer faultType;
/**
* 故障现象(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@TableField(value="fault_phenomenon")
@ApiModelProperty(value="故障现象(自定义单独拼接成串,格式1,2,3,电源问题)")
private String faultPhenomenon;
/**
* 故障原因(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@TableField(value="fault_reason")
@ApiModelProperty(value="故障原因(自定义单独拼接成串,格式1,2,3,电源问题)")
private String faultReason;
/**
* 工作内容(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="工作内容(自定义单独拼接成串,格式1,2,3,电源问题)")
@TableField(value="work_content")
private String workContent;
/**
* 维修开始日期
*/
@TableField(value="repair_start_date")
@ApiModelProperty(value="维修开始日期")
private Date repairStartDate;
/**
* 维修结束日期
*/
@TableField(value="repair_end_date")
@ApiModelProperty(value="维修结束日期")
private Date repairEndDate;
/**
* 实际开始时间
*/
@TableField(value="actual_start_date")
@ApiModelProperty(value="实际开始时间")
private Date actualStartDate;
/**
* 实际结束时间
*/
@TableField(value="actual_end_date")
@ApiModelProperty(value="实际结束时间")
private Date actualEndDate;
/**
* 维修工时
*/
@TableField(value="repair_hours")
@ApiModelProperty(value="维修工时")
private Float repairHours;
/**
* 工程师姓名
*/
@TableField(value="engineer_name")
@ApiModelProperty(value="工程师姓名")
private String engineerName;
/**
* 工程师工号
*/
@TableField(value="engineer_num")
@ApiModelProperty(value="工程师工号")
private String engineerNum;
/**
* 叫修时间
*/
@TableField(value="call_repair_date")
@ApiModelProperty(value="叫修时间")
private Date callRepairDate;
/**
* 到达时间
*/
@TableField(value="arrival_date")
@ApiModelProperty(value="到达时间")
private Date arrivalDate;
/**
* 离开时间
*/
@TableField(value="leave_date")
@ApiModelProperty(value="离开时间")
private Date leaveDate;
/**
* 维修结果(1,正常工作 2,基本功能正常 3,需进一步修理 4,需外送修理 5,无法修复 6,其他)
*/
@TableField(value="repair_result")
@ApiModelProperty(value="维修结果(1,正常工作 2,基本功能正常 3,需进一步修理 4,需外送修理 5,无法修复 6,其他)")
private Integer repairResult;
/**
* 维修费用
*/
@TableField(value="repair_cost")
@ApiModelProperty(value="维修费用")
private BigDecimal repairCost;
/**
* 材料费用
*/
@TableField(value="parts_cost")
@ApiModelProperty(value=" 材料费用")
private BigDecimal partsCost;
/**
* 总计
*/
@TableField(value="total_cost")
@ApiModelProperty(value="总计")
private BigDecimal totalCost;
/**
* 发票号码(用,分割)
*/
@TableField(value="repair_invoice")
@ApiModelProperty(value="发票号码(用,分割)")
private String repairInvoice;
/**
* 维修备注
*/
@ApiModelProperty(value="维修备注")
private String remarks;
/**
* 维修人ID
*/
@ApiModelProperty(value="维修人ID")
@TableField(value="repair_id")
private Long repairId;
/**
* 维修人名称
*/
@ApiModelProperty(value="维修人名称")
@TableField(value="repair_name")
private String repairName;
/**
* 提交报告单时间
*/
@ApiModelProperty(value="提交报告单时间")
@TableField(value="repair_date")
private Date repairDate=new Date();
/**
* 作废标记,0:启用,1:删除
*/
@ApiModelProperty(value="作废标记,0:启用,1:删除")
@TableField(value="del_flag")
private Boolean delFlag;
@ApiModelProperty(value="关联配件")
@TableField(exist=false)
private List<RepPartsRecord> list;
@ApiModelProperty(value="报告方式(1,暂存 2,完修)")
@TableField(exist=false)
private Integer status;
/**
* 维修状态(1,送修 2,现场维修)
*/
@ApiModelProperty(value="维修状态(1,送修 2,现场维修)")
@TableField(value="report_status")
private Integer reportStatus;
/**
*送修人
*/
@ApiModelProperty(value="送修人")
@TableField(value="send_person")
private String sendPerson;
/**
*送修电话
*/
@ApiModelProperty(value="送修电话")
@TableField(value="send_phone")
private String sendPhone;
/**
* 附件
*/
@ApiModelProperty(value="附件")
@TableField(value="report_file")
private String reportFile;
/**
*故障代码
*/
@ApiModelProperty(value="故障代码")
@TableField(value="trouble_code")
private String troubleCode;
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public Integer getModeStatus() {
return modeStatus;
}
public void setModeStatus(Integer modeStatus) {
this.modeStatus = modeStatus;
}
public String getOutsideCompany() {
return outsideCompany;
}
public void setOutsideCompany(String outsideCompany) {
this.outsideCompany = outsideCompany;
}
public String getOutsidePhone() {
return outsidePhone;
}
public void setOutsidePhone(String outsidePhone) {
this.outsidePhone = outsidePhone;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public Integer getFaultType() {
return faultType;
}
public void setFaultType(Integer faultType) {
this.faultType = faultType;
}
public String getFaultPhenomenon() {
return faultPhenomenon;
}
public void setFaultPhenomenon(String faultPhenomenon) {
this.faultPhenomenon = faultPhenomenon;
}
public String getFaultReason() {
return faultReason;
}
public void setFaultReason(String faultReason) {
this.faultReason = faultReason;
}
public String getWorkContent() {
return workContent;
}
public void setWorkContent(String workContent) {
this.workContent = workContent;
}
public Date getRepairStartDate() {
return repairStartDate;
}
public void setRepairStartDate(Date repairStartDate) {
this.repairStartDate = repairStartDate;
}
public Date getRepairEndDate() {
return repairEndDate;
}
public void setRepairEndDate(Date repairEndDate) {
this.repairEndDate = repairEndDate;
}
public Date getActualStartDate() {
return actualStartDate;
}
public void setActualStartDate(Date actualStartDate) {
this.actualStartDate = actualStartDate;
}
public Date getActualEndDate() {
return actualEndDate;
}
public void setActualEndDate(Date actualEndDate) {
this.actualEndDate = actualEndDate;
}
public Integer getRepairResult() {
return repairResult;
}
public void setRepairResult(Integer repairResult) {
this.repairResult = repairResult;
}
public BigDecimal getRepairCost() {
return repairCost;
}
public void setRepairCost(BigDecimal repairCost) {
this.repairCost = repairCost;
}
public BigDecimal getPartsCost() {
return partsCost;
}
public void setPartsCost(BigDecimal partsCost) {
this.partsCost = partsCost;
}
public BigDecimal getTotalCost() {
return totalCost;
}
public void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
public String getRepairInvoice() {
return repairInvoice;
}
public void setRepairInvoice(String repairInvoice) {
this.repairInvoice = repairInvoice;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public Long getRepairId() {
return repairId;
}
public void setRepairId(Long repairId) {
this.repairId = repairId;
}
public String getRepairName() {
return repairName;
}
public void setRepairName(String repairName) {
this.repairName = repairName;
}
public Date getRepairDate() {
return repairDate;
}
public void setRepairDate(Date repairDate) {
this.repairDate = repairDate;
}
public Boolean isDelFlag() {
return delFlag;
}
public void setDelFlag(Boolean delFlag) {
this.delFlag = delFlag;
}
public List<RepPartsRecord> getList() {
return list;
}
public void setList(List<RepPartsRecord> list) {
this.list = list;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Float getRepairHours() {
return repairHours;
}
public void setRepairHours(Float repairHours) {
this.repairHours = repairHours;
}
public Date getCallRepairDate() {
return callRepairDate;
}
public void setCallRepairDate(Date callRepairDate) {
this.callRepairDate = callRepairDate;
}
public Date getArrivalDate() {
return arrivalDate;
}
public void setArrivalDate(Date arrivalDate) {
this.arrivalDate = arrivalDate;
}
public Date getLeaveDate() {
return leaveDate;
}
public void setLeaveDate(Date leaveDate) {
this.leaveDate = leaveDate;
}
public String getEngineerName() {
return engineerName;
}
public void setEngineerName(String engineerName) {
this.engineerName = engineerName;
}
public String getEngineerNum() {
return engineerNum;
}
public void setEngineerNum(String engineerNum) {
this.engineerNum = engineerNum;
}
public Integer getReportStatus() {
return reportStatus;
}
public void setReportStatus(Integer reportStatus) {
this.reportStatus = reportStatus;
}
public String getSendPerson() {
return sendPerson;
}
public void setSendPerson(String sendPerson) {
this.sendPerson = sendPerson;
}
public String getSendPhone() {
return sendPhone;
}
public void setSendPhone(String sendPhone) {
this.sendPhone = sendPhone;
}
public String getReportFile() {
return reportFile;
}
public void setReportFile(String reportFile) {
this.reportFile = reportFile;
}
public String getTroubleCode() {
return troubleCode;
}
public void setTroubleCode(String troubleCode) {
this.troubleCode = troubleCode;
}
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairConfigServiceImpl.java
package com.aek.ebey.repair.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aek.common.core.BeanMapper;
import com.aek.common.core.Result;
import com.aek.common.core.base.BaseServiceImpl;
import com.aek.common.core.exception.BusinessException;
import com.aek.common.core.exception.ExceptionFactory;
import com.aek.common.core.serurity.WebSecurityUtils;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.mapper.RepRepairConfigMapper;
import com.aek.ebey.repair.model.RepRepairConfig;
import com.aek.ebey.repair.model.vo.RepConfigDeptVo;
import com.aek.ebey.repair.model.vo.RepConfigResponseVo;
import com.aek.ebey.repair.model.vo.RepConfiger;
import com.aek.ebey.repair.model.vo.RepUserVo;
import com.aek.ebey.repair.model.vo.TakeOrderDeptVo;
import com.aek.ebey.repair.service.RepRepairConfigService;
import com.aek.ebey.repair.service.ribbon.UserPermissionService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
/**
* <p>
* 维修配置表 服务实现类
* </p>
*
* @author cyl
* @since 2018-01-26
*/
@Service
@Transactional
public class RepRepairConfigServiceImpl extends BaseServiceImpl<RepRepairConfigMapper, RepRepairConfig> implements RepRepairConfigService {
@Autowired
UserPermissionService userPermissionService;
@Autowired
RepRepairConfigMapper repRepairConfigMapper;
@Autowired
RepRepairConfigService repRepairConfigService;
@Override
public List<RepConfigDeptVo> selectDept(String keyword) {
String token = WebSecurityUtils.getCurrentToken();
AuthUser currentUser = WebSecurityUtils.getCurrentUser();
Long tenantId = currentUser.getTenantId();
//用户更新repairConfig表
Result<List<RepUserVo>> takeOrderUserListResult = userPermissionService.getTakeOrderUserList(token);
if(takeOrderUserListResult != null){
List<RepUserVo> takeOrderUserList = takeOrderUserListResult.getData();
if(takeOrderUserList !=null && takeOrderUserList.size()>0){
List<RepUserVo> repairGroupById = repRepairConfigMapper.getRepairGroupById(tenantId);
if(repairGroupById !=null && repairGroupById.size()>0){
repairGroupById.removeAll(takeOrderUserList);
}
if(repairGroupById.size()>0){
repRepairConfigMapper.deletByRepairIdList(repairGroupById, tenantId);
}
}
}
List<RepConfigDeptVo> deptList = Lists.newArrayList();
Result<List<RepConfigDeptVo>> result = userPermissionService.getDeptList(keyword, token);
Result<List<RepConfigDeptVo>> allDeptList = userPermissionService.getAllDeptList(keyword, token);
if (result !=null&&"200".equals(result.getCode())) {
deptList = result.getData();
// List<RepConfigDeptVo> deptListCopy = BeanMapper.mapList(deptList, RepConfigDeptVo.class);
if(deptList !=null && deptList.size()>0){
List<RepConfigDeptVo> takeOrderDepts = repRepairConfigMapper.getTakeOrderDeptId(tenantId);
if(takeOrderDepts !=null && takeOrderDepts.size()>0){
deptList.removeAll(takeOrderDepts);//移除已经分配部门
if(allDeptList!=null&&"200".equals(allDeptList.getCode())){
List<RepConfigDeptVo> deptsList = allDeptList.getData();
if(deptsList!=null&&deptsList.size()>0){
takeOrderDepts.removeAll(deptsList);//维修冗余且sys已删除的部门
if(takeOrderDepts.size()>0){
repRepairConfigMapper.deletByEnableDelDeptId(takeOrderDepts, tenantId);
}
}
}
}
}
}
return deptList;
}
@Override
public Page<RepUserVo> repairConfigPage(Page<RepUserVo> page) {
List<RepUserVo> listVo = Lists.newArrayList();
String currentToken = WebSecurityUtils.getCurrentToken();
Long tenantId = WebSecurityUtils.getCurrentUser().getTenantId();
Result<List<RepUserVo>> result = userPermissionService.getTakeOrderUserList(currentToken);
if(result !=null){
List<RepUserVo> repUserList = result.getData();
if(repUserList !=null && repUserList.size() >0){
int total=repUserList.size();
page.setTotal(total);
int pageNo = page.getCurrent();
int pageSize= page.getSize();
int fromIndex=pageSize*(pageNo-1);
int toIndex=pageSize*pageNo;
if(fromIndex <= toIndex){
listVo=repUserList.subList(fromIndex, (toIndex>total?total:toIndex));
if(listVo.size()>0){
for (RepUserVo lv : listVo) {
String takeOrderDeptNames = repRepairConfigMapper.getTakeOrderDeptNames(lv.getId(),tenantId);
lv.setTakeOrderDeptNames(takeOrderDeptNames);
}
}
}
//异步更新维修工程师数据
new Thread() {
@Override
public void run() {
for (RepUserVo repUser : repUserList) {
repRepairConfigMapper.updateRepConfigUser(repUser, tenantId);
}
}
}.start();
}
}
page.setRecords(listVo);
return page;
}
@Override
public void repConfig(Long repairId, List<RepConfigDeptVo> depts) {
if(depts.size()==0){
Long tenantId = WebSecurityUtils.getCurrentUser().getTenantId();
repRepairConfigMapper.delByTenantIdRepairId(repairId, tenantId);
}
if(depts.size()>0){
String token = WebSecurityUtils.getCurrentToken();
//校验是否有维修权限或者是否停用
Result<Integer> checkIntResult = userPermissionService.checkIsRepHelp(repairId, token);
Integer checkInt = checkIntResult.getData();
if(checkInt != null){
switch (checkInt.intValue()) {
case 1:
throw ExceptionFactory.create("A_002");
case 2:
throw ExceptionFactory.create("A_003");
default:
break;
}
}
//校验科室是否已分配
Long tenantId = WebSecurityUtils.getCurrentUser().getTenantId();
for (RepConfigDeptVo dep : depts) {
RepRepairConfig takeOrderDept = repRepairConfigMapper.getByTakeOrderDeptId(dep.getId(),tenantId,repairId);
if(takeOrderDept != null){
throw new BusinessException("201", takeOrderDept.getTakeOrderDeptName()+"已被分配,请移除");
}
}
if(repairId == null){
return;
}
//清除个人历史配置
repRepairConfigMapper.delByTenantIdRepairId(repairId, tenantId);
List<RepRepairConfig> list = Lists.newArrayList();
Result<RepUserVo> userResult = userPermissionService.getUser(repairId, tenantId, token);
if(userResult !=null){
RepUserVo user = userResult.getData();
if(user == null){
return;
}
for (RepConfigDeptVo dep : depts) {
RepRepairConfig rc = BeanMapper.map(user, RepRepairConfig.class);
rc.setRepairId(user.getId());
rc.setRepairName(user.getRealName());
rc.setTakeOrderDeptId(dep.getId());
rc.setTakeOrderDeptName(dep.getName());
rc.setTenantId(tenantId);
list.add(rc);
}
if(list.size()>0){
repRepairConfigService.insertBatch(list);
}
}
}
}
@Override
public RepConfigResponseVo getConfigDetail(Long repairId) {
String token = WebSecurityUtils.getCurrentToken();
Long tenantId = WebSecurityUtils.getCurrentUser().getTenantId();
//校验是否有维修权限或者是否停用
Result<Integer> checkIntResult = userPermissionService.checkIsRepHelp(repairId, token);
Integer checkInt = checkIntResult.getData();
if(checkInt != null){
switch (checkInt.intValue()) {
case 1:
throw ExceptionFactory.create("A_002");
case 2:
throw ExceptionFactory.create("A_003");
default:
break;
}
}
//更新repairConfig表
Result<List<RepUserVo>> takeOrderUserListResult = userPermissionService.getTakeOrderUserList(token);
if(takeOrderUserListResult != null){
List<RepUserVo> takeOrderUserList = takeOrderUserListResult.getData();
if(takeOrderUserList !=null && takeOrderUserList.size()>0){
List<RepUserVo> repairGroupById = repRepairConfigMapper.getRepairGroupById(tenantId);
if(repairGroupById !=null && repairGroupById.size()>0){
repairGroupById.removeAll(takeOrderUserList);
}
if(repairGroupById.size()>0){
repRepairConfigMapper.deletByRepairIdList(repairGroupById, tenantId);
}
}
}
//已选科室
Wrapper<RepRepairConfig> wrapper = new EntityWrapper<RepRepairConfig>();
wrapper.eq("repair_id", repairId).eq("tenant_id", tenantId).eq("del_flag", 0);
List<RepRepairConfig> list = repRepairConfigMapper.selectList(wrapper);
RepConfigResponseVo repCofRep = new RepConfigResponseVo();
List<TakeOrderDeptVo> mapList = Lists.newArrayList();
if(list !=null && list.size()>0){
RepRepairConfig repCof = list.get(0);
repCofRep.setRepairId(repCof.getRepairId());
mapList.addAll(BeanMapper.mapList(list, TakeOrderDeptVo.class));
}
repCofRep.setOwnDepts(mapList);
//可用科室
Result<List<RepConfigDeptVo>> allDeptsResult = userPermissionService.getDeptList(null, token);
List<RepConfigDeptVo> takeOrderDepts = repRepairConfigMapper.getTakeOrderDeptId(tenantId);
List<RepConfigDeptVo> allDeptsList = Lists.newArrayList();
List<TakeOrderDeptVo> listBo = Lists.newArrayList();
if(allDeptsResult != null){
allDeptsList = allDeptsResult.getData();
if(allDeptsList !=null && allDeptsList.size()>0){
allDeptsList.removeAll(takeOrderDepts);
}
if(allDeptsList.size()>0){
for (RepConfigDeptVo repConfigDeptVo : allDeptsList) {
TakeOrderDeptVo takeOrderDept = new TakeOrderDeptVo();
takeOrderDept.setTakeOrderDeptId(repConfigDeptVo.getId());
takeOrderDept.setTakeOrderDeptName(repConfigDeptVo.getName());
listBo.add(takeOrderDept);
}
}
}
repCofRep.setAllDepts(listBo);
Result<List<RepConfigDeptVo>> result = userPermissionService.getDeptList(null, token);
if(result != null){
List<RepConfigDeptVo> deptList = result.getData();
if(deptList.size()>0){
//异步更新配置机构信息
new Thread() {
@Override
public void run() {
for (RepConfigDeptVo dept : deptList) {
repRepairConfigMapper.updateDept(dept,tenantId);//根据部门id更新同步过来的部门名称
}
}
}.start();
}
}
return repCofRep;
}
@Override
public RepConfiger selectConfiger(Long deptId) {
return repRepairConfigMapper.selectConfiger(deptId);
}
@Override
public List<RepConfiger> selectUsers() {
String currentToken = WebSecurityUtils.getCurrentToken();
List<RepConfiger> list = Lists.newArrayList();
Result<List<RepUserVo>> result = userPermissionService.getTakeOrderUserList(currentToken);
if(result != null){
List<RepUserVo> userList = result.getData();
if(userList != null && userList.size()>0){
list=BeanMapper.mapList(userList, RepConfiger.class);
}
}
return list;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepRepairBillCheckConfig.java
package com.aek.ebey.repair.model;
import java.math.BigDecimal;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 维修单据配置实体类
*
* @author HongHui
* @date 2018年1月26日
*/
@ApiModel(value = "RepRepairBillCheckConfig", description = "维修单据配置信息")
@TableName("rep_repair_bill_check_config")
public class RepRepairBillCheckConfig extends BaseModel {
private static final long serialVersionUID = 6794169755745843753L;
/**
* 机构ID
*/
@ApiModelProperty(value="机构ID")
@TableField(value="tenant_id")
private Long tenantId;
/**
* 审批人ID
*/
@ApiModelProperty(value="审批人ID")
@TableField(value="check_user_id")
private Long checkUserId;
/**
* 审批人姓名
*/
@ApiModelProperty(value="审批人姓名")
@TableField(value="check_user_name")
private String checkUserName;
/**
* 审批人手机号
*/
@ApiModelProperty(value="审批人手机号")
@TableField(value="check_user_mobile")
private Long checkUserMobile;
/**
* 审核人职务
*/
@ApiModelProperty(value="审核人职务")
@TableField(value="check_user_job")
private String checkUserJob;
/**
* 费用最小值
*/
@ApiModelProperty(value="费用最小值")
@TableField(value="min_fee")
private BigDecimal minFee;
/**
* 费用最大值
*/
@ApiModelProperty(value="费用最大值")
@TableField(value="max_fee")
private BigDecimal maxFee;
/**
* 层级序号
*/
@ApiModelProperty(value="层级序号")
@TableField(value="index")
private Integer index;
/**
* 层级名称
*/
@ApiModelProperty(value="层级名称")
@TableField(value="index_name")
private String indexName;
/**
* 备注信息
*/
@ApiModelProperty(value="备注信息")
@TableField(value="remark")
private String remark;
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
public Long getCheckUserId() {
return checkUserId;
}
public void setCheckUserId(Long checkUserId) {
this.checkUserId = checkUserId;
}
public Long getCheckUserMobile() {
return checkUserMobile;
}
public void setCheckUserMobile(Long checkUserMobile) {
this.checkUserMobile = checkUserMobile;
}
public String getCheckUserJob() {
return checkUserJob;
}
public void setCheckUserJob(String checkUserJob) {
this.checkUserJob = checkUserJob;
}
public BigDecimal getMinFee() {
return minFee;
}
public void setMinFee(BigDecimal minFee) {
this.minFee = minFee;
}
public BigDecimal getMaxFee() {
return maxFee;
}
public void setMaxFee(BigDecimal maxFee) {
this.maxFee = maxFee;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getCheckUserName() {
return checkUserName;
}
public void setCheckUserName(String checkUserName) {
this.checkUserName = checkUserName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((checkUserId == null) ? 0 : checkUserId.hashCode());
result = prime * result + ((checkUserJob == null) ? 0 : checkUserJob.hashCode());
result = prime * result + ((checkUserMobile == null) ? 0 : checkUserMobile.hashCode());
result = prime * result + ((index == null) ? 0 : index.hashCode());
result = prime * result + ((indexName == null) ? 0 : indexName.hashCode());
result = prime * result + ((maxFee == null) ? 0 : maxFee.hashCode());
result = prime * result + ((minFee == null) ? 0 : minFee.hashCode());
result = prime * result + ((remark == null) ? 0 : remark.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RepRepairBillCheckConfig other = (RepRepairBillCheckConfig) obj;
if (checkUserId == null) {
if (other.checkUserId != null)
return false;
} else if (!checkUserId.equals(other.checkUserId))
return false;
if (checkUserJob == null) {
if (other.checkUserJob != null)
return false;
} else if (!checkUserJob.equals(other.checkUserJob))
return false;
if (checkUserMobile == null) {
if (other.checkUserMobile != null)
return false;
} else if (!checkUserMobile.equals(other.checkUserMobile))
return false;
if (index == null) {
if (other.index != null)
return false;
} else if (!index.equals(other.index))
return false;
if (indexName == null) {
if (other.indexName != null)
return false;
} else if (!indexName.equals(other.indexName))
return false;
if (maxFee == null) {
if (other.maxFee != null)
return false;
} else if (!maxFee.equals(other.maxFee))
return false;
if (minFee == null) {
if (other.minFee != null)
return false;
} else if (!minFee.equals(other.minFee))
return false;
if (remark == null) {
if (other.remark != null)
return false;
} else if (!remark.equals(other.remark))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
return true;
}
@Override
public String toString() {
return "RepRepairBillCheckConfig [tenantId=" + tenantId + ", checkUserId=" + checkUserId + ", checkUserMobile="
+ checkUserMobile + ", checkUserJob=" + checkUserJob + ", minFee=" + minFee + ", maxFee=" + maxFee
+ ", index=" + index + ", indexName=" + indexName + ", remark=" + remark + "]";
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepRepairReportDetails.java
package com.aek.ebey.repair.request;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.aek.ebey.repair.model.RepPartsRecord;
import com.baomidou.mybatisplus.annotations.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepRepairReportDetails", description = "维修报告单详情")
public class RepRepairReportDetails {
private Long id;
/**
* 关联申请单ID
*/
@ApiModelProperty(value="关联申请单id")
private Long applyId;
/**
* 维修方式(1,自主维修 2,外修 3,现场解决)
*/
@ApiModelProperty(value="维修方式(1,自主维修 2,外修 3,现场解决)")
private Integer modeStatus;
/**
* 外修单位
*/
@ApiModelProperty(value="外修单位")
private String outsideCompany;
/**
* 外修电话
*/
@ApiModelProperty(value="外修电话")
private String outsidePhone;
/**
* 附件
*/
@ApiModelProperty(value="附件")
private String attachment;
/**
* 故障类型(1,故障维修2,预防性维修3,计量检测性维修 4,质保期内维修 5,厂家合同维修 6,第三方合同维修 7,临时叫修)
*/
@ApiModelProperty(value="故障类型(1,故障维修2,预防性维修3,计量检测性维修 4,质保期内维修 5,厂家合同维修 6,第三方合同维修 7,临时叫修)")
private Integer faultType;
/**
* 故障现象(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="故障现象(自定义单独拼接成串,格式1,2,3,电源问题)")
private String faultPhenomenon;
/**
* 故障原因(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="故障原因(自定义单独拼接成串,格式1,2,3,电源问题)")
private String faultReason;
/**
* 工作内容(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="工作内容(自定义单独拼接成串,格式1,2,3,电源问题)")
private String workContent;
/**
* 故障现象(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="故障现象(自定义单独拼接成串,格式1,2,3,电源问题)")
private List<String> faultPhenomenonList;
/**
* 故障原因(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="故障原因(自定义单独拼接成串,格式1,2,3,电源问题)")
private List<String> faultReasonList;
/**
* 工作内容(自定义单独拼接成串,格式1,2,3,电源问题)
*/
@ApiModelProperty(value="工作内容(自定义单独拼接成串,格式1,2,3,电源问题)")
private List<String> workContentList;
/**
* 维修开始日期
*/
@ApiModelProperty(value="维修开始日期")
private Date repairStartDate;
/**
* 维修结束日期
*/
@ApiModelProperty(value="维修结束日期")
private Date repairEndDate;
/**
* 实际开始时间
*/
@ApiModelProperty(value="实际开始时间")
private Date actualStartDate;
/**
* 实际结束时间
*/
@ApiModelProperty(value="实际结束时间")
private Date actualEndDate;
/**
* 维修工时
*/
@ApiModelProperty(value="维修工时")
private Float repairHours;
/**
* 工程师姓名
*/
@ApiModelProperty(value="工程师姓名")
private String engineerName;
/**
* 工程师工号
*/
@ApiModelProperty(value="工程师工号")
private String engineerNum;
/**
* 叫修时间
*/
@ApiModelProperty(value="叫修时间")
private Date callRepairDate;
/**
* 到达时间
*/
@ApiModelProperty(value="到达时间")
private Date arrivalDate;
/**
* 离开时间
*/
@ApiModelProperty(value="离开时间")
private Date leaveDate;
/**
* 维修结果(1,正常工作 2,基本功能正常 3,需进一步修理 4,需外送修理 5,无法修复 6,其他)
*/
@ApiModelProperty(value="维修结果(1,正常工作 2,基本功能正常 3,需进一步修理 4,需外送修理 5,无法修复 6,其他)")
private Integer repairResult;
/**
* 维修费用
*/
@ApiModelProperty(value="维修费用")
private BigDecimal repairCost;
/**
* 材料费用
*/
@ApiModelProperty(value=" 材料费用")
private BigDecimal partsCost;
/**
* 总计
*/
@ApiModelProperty(value="总计")
private BigDecimal totalCost;
/**
* 发票号码(用,分割)
*/
@ApiModelProperty(value="发票号码(用,分割)")
private String repairInvoice;
/**
* 维修备注
*/
@ApiModelProperty(value="维修备注")
private String remarks;
/**
* 维修人ID
*/
@ApiModelProperty(value="维修人ID")
private Long repairId;
/**
* 维修人名称
*/
@ApiModelProperty(value="维修人名称")
private String repairName;
/**
* 提交报告单时间
*/
@ApiModelProperty(value="提交报告单时间")
private Date repairDate=new Date();
@ApiModelProperty(value="关联配件")
private List<RepPartsRecord> list;
/**
* 是否可以维修
*/
@ApiModelProperty(value="是否可以维修")
private Boolean flag;
/**
* 维修状态(1,送修 2,现场维修)
*/
@ApiModelProperty(value="维修状态(1,送修 2,现场维修)")
private Integer reportStatus;
/**
*送修人
*/
@ApiModelProperty(value="送修人")
private String sendPerson;
/**
*送修电话
*/
@ApiModelProperty(value="送修电话")
private String sendPhone;
/**
* 附件
*/
@ApiModelProperty(value="附件")
private String reportFile;
/**
*故障代码
*/
@ApiModelProperty(value="故障代码")
private String troubleCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getApplyId() {
return applyId;
}
public void setApplyId(Long applyId) {
this.applyId = applyId;
}
public Integer getModeStatus() {
return modeStatus;
}
public void setModeStatus(Integer modeStatus) {
this.modeStatus = modeStatus;
}
public String getOutsideCompany() {
return outsideCompany;
}
public void setOutsideCompany(String outsideCompany) {
this.outsideCompany = outsideCompany;
}
public String getOutsidePhone() {
return outsidePhone;
}
public void setOutsidePhone(String outsidePhone) {
this.outsidePhone = outsidePhone;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public Integer getFaultType() {
return faultType;
}
public void setFaultType(Integer faultType) {
this.faultType = faultType;
}
public String getFaultPhenomenon() {
return faultPhenomenon;
}
public void setFaultPhenomenon(String faultPhenomenon) {
this.faultPhenomenon = faultPhenomenon;
}
public String getFaultReason() {
return faultReason;
}
public void setFaultReason(String faultReason) {
this.faultReason = faultReason;
}
public String getWorkContent() {
return workContent;
}
public void setWorkContent(String workContent) {
this.workContent = workContent;
}
public List<String> getFaultPhenomenonList() {
return faultPhenomenonList;
}
public void setFaultPhenomenonList(List<String> faultPhenomenonList) {
this.faultPhenomenonList = faultPhenomenonList;
}
public List<String> getFaultReasonList() {
return faultReasonList;
}
public void setFaultReasonList(List<String> faultReasonList) {
this.faultReasonList = faultReasonList;
}
public List<String> getWorkContentList() {
return workContentList;
}
public void setWorkContentList(List<String> workContentList) {
this.workContentList = workContentList;
}
public Date getRepairStartDate() {
return repairStartDate;
}
public void setRepairStartDate(Date repairStartDate) {
this.repairStartDate = repairStartDate;
}
public Date getRepairEndDate() {
return repairEndDate;
}
public void setRepairEndDate(Date repairEndDate) {
this.repairEndDate = repairEndDate;
}
public Date getActualStartDate() {
return actualStartDate;
}
public void setActualStartDate(Date actualStartDate) {
this.actualStartDate = actualStartDate;
}
public Date getActualEndDate() {
return actualEndDate;
}
public void setActualEndDate(Date actualEndDate) {
this.actualEndDate = actualEndDate;
}
public Integer getRepairResult() {
return repairResult;
}
public void setRepairResult(Integer repairResult) {
this.repairResult = repairResult;
}
public BigDecimal getRepairCost() {
return repairCost;
}
public void setRepairCost(BigDecimal repairCost) {
this.repairCost = repairCost;
}
public BigDecimal getPartsCost() {
return partsCost;
}
public void setPartsCost(BigDecimal partsCost) {
this.partsCost = partsCost;
}
public BigDecimal getTotalCost() {
return totalCost;
}
public void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
public String getRepairInvoice() {
return repairInvoice;
}
public void setRepairInvoice(String repairInvoice) {
this.repairInvoice = repairInvoice;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public Long getRepairId() {
return repairId;
}
public void setRepairId(Long repairId) {
this.repairId = repairId;
}
public String getRepairName() {
return repairName;
}
public void setRepairName(String repairName) {
this.repairName = repairName;
}
public Date getRepairDate() {
return repairDate;
}
public void setRepairDate(Date repairDate) {
this.repairDate = repairDate;
}
public List<RepPartsRecord> getList() {
return list;
}
public void setList(List<RepPartsRecord> list) {
this.list = list;
}
public Float getRepairHours() {
return repairHours;
}
public void setRepairHours(Float repairHours) {
this.repairHours = repairHours;
}
public Date getCallRepairDate() {
return callRepairDate;
}
public void setCallRepairDate(Date callRepairDate) {
this.callRepairDate = callRepairDate;
}
public Date getArrivalDate() {
return arrivalDate;
}
public void setArrivalDate(Date arrivalDate) {
this.arrivalDate = arrivalDate;
}
public Date getLeaveDate() {
return leaveDate;
}
public void setLeaveDate(Date leaveDate) {
this.leaveDate = leaveDate;
}
public String getEngineerName() {
return engineerName;
}
public void setEngineerName(String engineerName) {
this.engineerName = engineerName;
}
public String getEngineerNum() {
return engineerNum;
}
public void setEngineerNum(String engineerNum) {
this.engineerNum = engineerNum;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public Integer getReportStatus() {
return reportStatus;
}
public void setReportStatus(Integer reportStatus) {
this.reportStatus = reportStatus;
}
public String getSendPerson() {
return sendPerson;
}
public void setSendPerson(String sendPerson) {
this.sendPerson = sendPerson;
}
public String getSendPhone() {
return sendPhone;
}
public void setSendPhone(String sendPhone) {
this.sendPhone = sendPhone;
}
public String getReportFile() {
return reportFile;
}
public void setReportFile(String reportFile) {
this.reportFile = reportFile;
}
public String getTroubleCode() {
return troubleCode;
}
public void setTroubleCode(String troubleCode) {
this.troubleCode = troubleCode;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/vo/TakeOrderDeptVo.java
package com.aek.ebey.repair.model.vo;
public class TakeOrderDeptVo {
private Long takeOrderDeptId;
private String takeOrderDeptName;
public Long getTakeOrderDeptId() {
return takeOrderDeptId;
}
public void setTakeOrderDeptId(Long takeOrderDeptId) {
this.takeOrderDeptId = takeOrderDeptId;
}
public String getTakeOrderDeptName() {
return takeOrderDeptName;
}
public void setTakeOrderDeptName(String takeOrderDeptName) {
this.takeOrderDeptName = takeOrderDeptName;
}
}
<file_sep>/aek-repair-web-api/src/main/resources/sql/V3.20.sql
ALTER TABLE `rep_repair_apply`
ADD COLUMN `report_date` datetime NULL COMMENT '提交报告单时间' AFTER `report_repair_date`;
ALTER TABLE `rep_repair_apply`
ADD COLUMN `seven_status` int(1) NULL DEFAULT NULL COMMENT '七天完修(1,是 2,否)' AFTER `report_date`;
ALTER TABLE `rep_repair_apply`
ADD COLUMN `days` int(6) NULL AFTER `take_order_id`;
UPDATE rep_repair_apply r,rep_repair_report p set r.report_date=p.repair_date where r.id=p.apply_id;
UPDATE rep_repair_apply r set r.days=(TIMESTAMPDIFF(DAY,r.report_repair_date,r.report_date));
UPDATE rep_repair_apply r set r.seven_status=2 where r.days>7;
UPDATE rep_repair_apply r set r.seven_status=1 where r.days<=7;
ALTER TABLE `rep_repair_apply`
DROP COLUMN `report_date`;
ALTER TABLE `rep_repair_apply`
DROP COLUMN `days`;
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/RepairDictionaryService.java
package com.aek.ebey.repair.service;
import com.aek.common.core.base.BaseService;
import com.aek.common.core.base.page.PageHelp;
import com.aek.ebey.repair.model.RepairDictionary;
import com.aek.ebey.repair.model.RepairDictype;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 服务类
* </p>
*
* @author aek
* @since 2017-08-30
*/
public interface RepairDictionaryService extends BaseService<RepairDictionary> {
Page<RepairDictype> search(PageHelp<RepairDictype> query);
String getValue(String ketId);
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/RepRepairApplyService.java
package com.aek.ebey.repair.service;
import java.util.List;
import com.aek.common.core.base.BaseService;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.model.RepRepairApply;
import com.aek.ebey.repair.model.RepRepairCheck;
import com.aek.ebey.repair.model.RepRepairTakeOrders;
import com.aek.ebey.repair.model.RepairData;
import com.aek.ebey.repair.model.vo.RepLargeScreenDataVo;
import com.aek.ebey.repair.model.vo.RepRepairApplyVo;
import com.aek.ebey.repair.model.vo.RepairDataMonthVo;
import com.aek.ebey.repair.query.RepRepairApplyQuery;
import com.aek.ebey.repair.query.RepRepairBillApplyQuery;
import com.aek.ebey.repair.query.RepRepairRecordQuery;
import com.aek.ebey.repair.request.ApplyDetailsResponse;
import com.aek.ebey.repair.request.ApplyResponse;
import com.aek.ebey.repair.request.ApplyTotalResponse;
import com.aek.ebey.repair.request.ApplyTurnOrderRequest;
import com.aek.ebey.repair.request.RepRepairBillApplyResponse;
import com.aek.ebey.repair.request.RepairRecordResponse;
import com.aek.ebey.repair.request.SevenDataResponse;
import com.aek.ebey.repair.request.SevenQuery;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 服务类
* </p>
*
* @author aek
* @since 2017-08-30
*/
public interface RepRepairApplyService extends BaseService<RepRepairApply> {
void save(RepRepairApply repRepairApply);
boolean getRepRepairApply(RepRepairApply repRepairApply);
Page<ApplyResponse> search(RepRepairApplyQuery query);
ApplyDetailsResponse getApplyDetails(Long id);
List<ApplyTotalResponse> selectApplyStatus(String tenantid);
void check(RepRepairCheck data);
void taking(RepRepairTakeOrders repRepairTakeOrders);
Page<RepairRecordResponse> repairRecord(RepRepairRecordQuery query);
int selectCountByTenantid(String tenantid, AuthUser authUser,int status);
int statsTakeOrdersByUserId(AuthUser authUser);
int statsWaitRepairByUserId(AuthUser authUser);
int statsWaitCheckByUserDeptId(AuthUser authUser);
void turnOrder(ApplyTurnOrderRequest request);
/**
* 新建维修单据申请获取维修单列表分页数据
* @param query
* @return
*/
Page<RepRepairBillApplyResponse> getRepairApplyPageForBill(RepRepairBillApplyQuery query);
void autoCheck();
/**
* 获取维修大屏统计数据
* @param tenantId
* @return
*/
public RepLargeScreenDataVo getLargeScreenData(Long tenantId);
/**
* 获取维修大屏维修单数据
* @param tenantId
* @return
*/
public List<RepRepairApplyVo> getLargeScreenApplyData(Long tenantId);
/**
* 获取维修概览统计数据
* @return
*/
public List<RepairData> getRepairData();
/**
* 获取维修月份数据统计
* @return
*/
public List<RepairDataMonthVo> getRepairDataMonthByDay();
List<SevenDataResponse> countApply(SevenQuery query);
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/web/request/RepRepairApplyResponse.java
package com.aek.ebey.repair.web.request;
import java.util.List;
import com.aek.ebey.repair.model.RepRepairApply;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepRepairApplyResponse", description = "维修申列表")
public class RepRepairApplyResponse {
@ApiModelProperty(value="本月天数")
private Integer days;
@ApiModelProperty(value="维修申请集合")
private List<RepRepairApply> list;
public Integer getDays() {
return days;
}
public void setDays(Integer days) {
this.days = days;
}
public List<RepRepairApply> getList() {
return list;
}
public void setList(List<RepRepairApply> list) {
this.list = list;
}
@Override
public String toString() {
return "RepRepairApplyResponse [days=" + days + ", list=" + list + "]";
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/RepRepairBillCheckFlow.java
package com.aek.ebey.repair.model;
import java.util.Date;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 维修单据审核流程表实体类
*
* @author HongHui
* @date 2018年1月26日
*/
@ApiModel(value = "RepRepairBillCheckFlow", description = "维修单据配置信息")
@TableName("rep_repair_bill_check_flow")
public class RepRepairBillCheckFlow extends BaseModel {
private static final long serialVersionUID = 18685051877537317L;
/**
* 维修单据ID
*/
@ApiModelProperty(value="维修单据ID")
@TableField(value="bill_id")
private Long billId;
/**
* 审批流程名称
*/
@ApiModelProperty(value="审批流程名称")
@TableField(value="flow_name")
private String flowName;
/**
* 审批人ID
*/
@ApiModelProperty(value="审批人ID")
@TableField(value="check_user_id")
private Long checkUserId;
/**
* 审批人姓名
*/
@ApiModelProperty(value="审批人姓名")
@TableField(value="check_user_name")
private String checkUserName;
/**
* 审批人手机号
*/
@ApiModelProperty(value="审批人手机号")
@TableField(value="check_user_mobile")
private Long checkUserMobile;
/**
* 流程序号
*/
@ApiModelProperty(value="流程序号")
@TableField(value="index")
private Integer index;
/**
* 审核状态(1=待审核,2=审核通过,3=审核未通过)
*/
@ApiModelProperty(value="审核状态(1=待审核,2=审核通过,3=审核未通过)")
@TableField(value="check_status")
private Integer checkStatus;
/**
* 审核状态(1=待审核,2=审核通过,3=审核未通过)
*/
@ApiModelProperty(value="审核状态文本(1=待审核,2=审核通过,3=审核未通过)")
@TableField(exist=false)
private String checkStatusText;
/**
* 审核备注
*/
@ApiModelProperty(value="审核备注")
@TableField(value="check_remark")
private String checkRemark;
/**
* 审核时间
*/
@ApiModelProperty(value="审核时间")
@TableField(value="check_time")
private Date checkTime;
public Long getBillId() {
return billId;
}
public void setBillId(Long billId) {
this.billId = billId;
}
public Long getCheckUserId() {
return checkUserId;
}
public void setCheckUserId(Long checkUserId) {
this.checkUserId = checkUserId;
}
public Long getCheckUserMobile() {
return checkUserMobile;
}
public void setCheckUserMobile(Long checkUserMobile) {
this.checkUserMobile = checkUserMobile;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public Integer getCheckStatus() {
return checkStatus;
}
public void setCheckStatus(Integer checkStatus) {
this.checkStatus = checkStatus;
}
public String getCheckRemark() {
return checkRemark;
}
public void setCheckRemark(String checkRemark) {
this.checkRemark = checkRemark;
}
public String getCheckStatusText() {
return checkStatusText;
}
public void setCheckStatusText(String checkStatusText) {
this.checkStatusText = checkStatusText;
}
public Date getCheckTime() {
return checkTime;
}
public void setCheckTime(Date checkTime) {
this.checkTime = checkTime;
}
public String getCheckUserName() {
return checkUserName;
}
public void setCheckUserName(String checkUserName) {
this.checkUserName = checkUserName;
}
public String getFlowName() {
return flowName;
}
public void setFlowName(String flowName) {
this.flowName = flowName;
}
}
<file_sep>/aek-repair-web-api/src/main/java/com/aek/ebey/repair/core/scheduled/RepairDataScheduledTask.java
package com.aek.ebey.repair.core.scheduled;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aek.common.core.Result;
import com.aek.common.core.base.BaseController;
import com.aek.ebey.repair.model.RepairData;
import com.aek.ebey.repair.model.vo.RepairDataMonthVo;
import com.aek.ebey.repair.request.SevenDataResponse;
import com.aek.ebey.repair.request.SevenQuery;
import com.aek.ebey.repair.service.RepRepairApplyService;
import com.aek.ebey.repair.service.ribbon.DataClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
/**
* 维修统计数据定时任务
*
* @author HongHui
* @date 2018年4月17日
*/
@Component
@RestController
@RequestMapping("/newrepair/RepairDataScheduledTask")
@Api(value = "RepairDataScheduledTask", description = "RepairDataScheduledTask")
public class RepairDataScheduledTask extends BaseController{
private static final Logger logger = LoggerFactory.getLogger(RepairDataScheduledTask.class);
//维修自动验收Lock
private static final Lock repairCheckLock = new ReentrantLock();
@Autowired
private RepRepairApplyService repRepairApplyService;
@Autowired
private DataClientService dataClientService;
/**
* 每天凌晨统计维修概览数据
*/
@Scheduled(cron = "0 0 0 * * ?")
//@Scheduled(cron="0/50 * * * * ? ")
public void countRepairDataByDay() {
logger.info("=================获取维修概览数据=================");
//获取维修概览数据
List<RepairData> repairData = repRepairApplyService.getRepairData();
//调用统计服务将数据保存至统计服务
dataClientService.addRepairData(repairData);
}
/**
* 每天凌晨统计维修月度数据
*/
@Scheduled(cron = "0 0 0 * * ?")
//@Scheduled(cron="0/50 * * * * ? ")
public void countRepairDataMonthByDay(){
logger.info("=================获取维修月度数据=================");
//获取维修月度数据
List<RepairDataMonthVo> repairDataMonthList = repRepairApplyService.getRepairDataMonthByDay();
dataClientService.addRepairDataMonth(repairDataMonthList);
}
/**
* 定时统计Apply
*/
@Scheduled(cron="0 0 1 7 * ?")
//@Scheduled(cron="0/50 * * * * ? ")
public void autoCountApply() throws Exception{
List<SevenDataResponse> list=repRepairApplyService.countApply(new SevenQuery());
dataClientService.pushSevenData(list);
}
/**
* 定时统计PM
*/
@GetMapping(value = "/historySevenData")
@ApiOperation(value = "Qc设备统计")
@ApiResponse(code = 200, message = "OK", response = Result.class)
public Result<List<SevenDataResponse>> SevenData(SevenQuery query) throws Exception {
List<SevenDataResponse> list=repRepairApplyService.countApply(query);
if(null != list && list.size() > 0) {
dataClientService.pushSevenData(list);
}
return response(list);
}
/**
* 定时验收
*/
@Scheduled(cron="0/50 * * * * ? ")
public void autoCheck() throws Exception{
repairCheckLock.lock();
try {
repRepairApplyService.autoCheck();
} finally {
repairCheckLock.unlock();
}
}
}
<file_sep>/readme.md
## 项目简介
- 维修管理
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/model/AssetsInfo.java
package com.aek.ebey.repair.model;
import java.util.Date;
import com.aek.common.core.base.BaseModel;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* <p>
* 资产信息表
* </p>
*
* @author aek
* @since 2017-06-13
*/
@ApiModel(value = "AssetsInfo", description = "设备典信息")
public class AssetsInfo extends BaseModel
{
private static final long serialVersionUID = 1L;
/**
* 关联类型
*/
@ApiModelProperty(value="启用时间")
private Date startUseDate;
/**
* 关联类型
*/
@ApiModelProperty(value="出产编号")
private String factoryNum;
/**
* 关联类型
*/
@ApiModelProperty(value="设备品牌")
private String assetsBrand;
/**
* 关联类型
*/
@ApiModelProperty(value="设备名称")
private String assetsName;
/**
* 关联类型
*/
@ApiModelProperty(value="设备编号")
private String assetsNum;
/**
* 生产商
*
*/
@ApiModelProperty(value="生产商")
private String factoryName;
/**
* 关联类型
*/
@ApiModelProperty(value="设备规格")
private String assetsSpec;
/**
* 关联类型
*/
@ApiModelProperty(value="供应商")
private String splName;
/**
* 关联类型
*/
@ApiModelProperty(value="来源 0:入库新增,1:批量导入")
private String assetsSourceName;
/**
* 关联类型
*/
@ApiModelProperty(value="状态:1未启用、2正常运行、3计量中、4维修中、5停用中、6已报废、7已报损")
private String statusName;
/**
* 关联类型
*/
@ApiModelProperty(value="使用科室")
private String deptName;
public String getAssetsName()
{
return assetsName;
}
public void setAssetsName(String assetsName)
{
this.assetsName = assetsName;
}
public String getAssetsNum()
{
return assetsNum;
}
public void setAssetsNum(String assetsNum)
{
this.assetsNum = assetsNum;
}
public String getFactoryName()
{
return factoryName;
}
public void setFactoryName(String factoryName)
{
this.factoryName = factoryName;
}
public String getAssetsSpec()
{
return assetsSpec;
}
public void setAssetsSpec(String assetsSpec)
{
this.assetsSpec = assetsSpec;
}
public String getSplName()
{
return splName;
}
public void setSplName(String splName)
{
this.splName = splName;
}
public String getAssetsSourceName()
{
return assetsSourceName;
}
public void setAssetsSourceName(String assetsSourceName)
{
this.assetsSourceName = assetsSourceName;
}
public String getStatusName()
{
return statusName;
}
public void setStatusName(String statusName)
{
this.statusName = statusName;
}
public String getDeptName()
{
return deptName;
}
public void setDeptName(String deptName)
{
this.deptName = deptName;
}
public Date getStartUseDate()
{
return startUseDate;
}
public void setStartUseDate(Date startUseDate)
{
this.startUseDate = startUseDate;
}
public String getFactoryNum()
{
return factoryNum;
}
public void setFactoryNum(String factoryNum)
{
this.factoryNum = factoryNum;
}
public String getAssetsBrand()
{
return assetsBrand;
}
public void setAssetsBrand(String assetsBrand)
{
this.assetsBrand = assetsBrand;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
@Override
public String toString() {
return "AssetsInfo [startUseDate=" + startUseDate + ", factoryNum=" + factoryNum + ", assetsBrand="
+ assetsBrand + ", assetsName=" + assetsName + ", assetsNum=" + assetsNum + ", factoryName="
+ factoryName + ", assetsSpec=" + assetsSpec + ", splName=" + splName + ", assetsSourceName="
+ assetsSourceName + ", statusName=" + statusName + ", deptName=" + deptName + "]";
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/RepPartsRecordResponse.java
package com.aek.ebey.repair.request;
import com.aek.ebey.repair.model.RepPartsRecord;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "RepPartsRecordResponse", description = "配件操作记录response")
public class RepPartsRecordResponse extends RepPartsRecord{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 分类编码
*/
@ApiModelProperty(value="分类编码")
private String kindCode;
/**
* 分类名称
*/
@ApiModelProperty(value="分类名称")
private String kindName;
public String getKindCode() {
return kindCode;
}
public void setKindCode(String kindCode) {
this.kindCode = kindCode;
}
public String getKindName() {
return kindName;
}
public void setKindName(String kindName) {
this.kindName = kindName;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/request/ApplyResponse.java
package com.aek.ebey.repair.request;
import java.util.Date;
import com.aek.ebey.repair.model.RepRepairApply;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "ApplyResponse", description = "维修申请响应信息")
public class ApplyResponse extends RepRepairApply{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 预计维修到达时间
*/
@ApiModelProperty(value="预计到达科室")
private Date predictReachDate;
/**
* 报修申请时间
*/
@ApiModelProperty(value="报修申请时间")
private String reportRepairDateStr;
public String getReportRepairDateStr() {
return reportRepairDateStr;
}
public void setReportRepairDateStr(String reportRepairDateStr) {
this.reportRepairDateStr = reportRepairDateStr;
}
public Date getPredictReachDate() {
return predictReachDate;
}
public void setPredictReachDate(Date predictReachDate) {
this.predictReachDate = predictReachDate;
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/RepRepairBillPartsService.java
package com.aek.ebey.repair.service;
import java.util.List;
import com.aek.common.core.base.BaseService;
import com.aek.ebey.repair.model.RepRepairBillParts;
/**
* 维修单据附件服务接口类
*
* @author HongHui
* @date 2018年1月29日
*/
public interface RepRepairBillPartsService extends BaseService<RepRepairBillParts> {
/**
* 获取单据配件信息
* @param billId
* @return
*/
public List<RepRepairBillParts> getRepRepairBillParts(Long billId);
}
<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/mapper/RepairDictionaryMapper.java
package com.aek.ebey.repair.mapper;
import com.aek.ebey.repair.model.RepairDictionary;
import com.aek.common.core.base.BaseMapper;
/**
* <p>
* Mapper接口
* </p>
*
* @author aek
* @since 2017-08-30
*/
public interface RepairDictionaryMapper extends BaseMapper<RepairDictionary> {
}<file_sep>/aek-repair-service/src/main/java/com/aek/ebey/repair/service/impl/RepRepairReportServiceImpl.java
package com.aek.ebey.repair.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.aek.common.core.BeanMapper;
import com.aek.common.core.Result;
import com.aek.common.core.base.BaseServiceImpl;
import com.aek.common.core.exception.ExceptionFactory;
import com.aek.common.core.serurity.WebSecurityUtils;
import com.aek.common.core.serurity.model.AuthUser;
import com.aek.ebey.repair.enums.WeiXinRepairMessageTypeEnum;
import com.aek.ebey.repair.inter.Constants;
import com.aek.ebey.repair.inter.RepairApplyStatus;
import com.aek.ebey.repair.mapper.RepPartsRecordMapper;
import com.aek.ebey.repair.mapper.RepRepairReportMapper;
import com.aek.ebey.repair.model.RepPartsRecord;
import com.aek.ebey.repair.model.RepRepairApply;
import com.aek.ebey.repair.model.RepRepairReport;
import com.aek.ebey.repair.model.RepRepairTakeOrders;
import com.aek.ebey.repair.request.RepRepairReportDetails;
import com.aek.ebey.repair.request.RepRepairReportResponse;
import com.aek.ebey.repair.request.WeiXinRepairMessageRequest;
import com.aek.ebey.repair.service.RepPartsRecordService;
import com.aek.ebey.repair.service.RepRepairApplyService;
import com.aek.ebey.repair.service.RepRepairReportService;
import com.aek.ebey.repair.service.RepRepairTakeOrdersService;
import com.aek.ebey.repair.service.RepairDictionaryService;
import com.aek.ebey.repair.service.ribbon.AuthClientService;
import com.aek.ebey.repair.service.ribbon.UserPermissionService;
import com.aek.ebey.repair.utils.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
/**
* <p>
* 维修报告 服务实现类
* </p>
*
* @author aek
* @since 2017-08-30
*/
@Service
@Transactional
public class RepRepairReportServiceImpl extends BaseServiceImpl<RepRepairReportMapper, RepRepairReport> implements RepRepairReportService {
private static final Logger logger = LoggerFactory.getLogger(RepRepairReportServiceImpl.class);
@Autowired
private RepRepairApplyService repRepairApplyService;
@Autowired
private RepRepairReportMapper repRepairReportMapper;
@Autowired
private RepPartsRecordMapper repPartsRecordMapper;
@Autowired
private RepPartsRecordService repPartsRecordService;
@Autowired
private RepairDictionaryService repairDictionaryService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private AuthClientService authClientService;
@Autowired
private RepRepairTakeOrdersService repRepairTakeOrdersService;
@Autowired
private UserPermissionService userPermissionService;
@Override
public Boolean save(RepRepairReport data) {
RepRepairApply repRepairApply = repRepairApplyService.selectById(data.getApplyId());
// 判断当前订单状态是否为2待维修状态
if (null != repRepairApply && repRepairApply.getStatus() == RepairApplyStatus.REPAIRING) {
AuthUser authUser = WebSecurityUtils.getCurrentUser();
Wrapper<RepRepairTakeOrders> wrapperTakeOrders=new EntityWrapper<>();
wrapperTakeOrders.eq("apply_id", data.getApplyId());
List<RepRepairTakeOrders> listTakeOrders=repRepairTakeOrdersService.selectList(wrapperTakeOrders);
RepRepairTakeOrders repRepairTakeOrders=null;
if(listTakeOrders!=null&&listTakeOrders.size()>0){
repRepairTakeOrders=listTakeOrders.get(0);
}
if (null != authUser && authUser.getId() != null) {
data.setRepairId(authUser.getId());
data.setRepairName(authUser.getRealName());
}
if(repRepairTakeOrders!=null){
Result<Integer> result= userPermissionService.checkIsRep(repRepairTakeOrders.getRepairId(), WebSecurityUtils.getCurrentToken());
logger.info("用户是否具有维修权限返回结果="+(result!=null?result.getData().toString():null));
if(result!=null){
if(result.getData().intValue()==3){
if(repRepairTakeOrders.getRepairId().longValue()==authUser.getId().longValue()){
Wrapper<RepRepairReport> wrapper = new EntityWrapper<RepRepairReport>();
wrapper.eq("apply_id", data.getApplyId());
wrapper.eq("del_flag", 0);
List<RepRepairReport> listRepRepairReport = repRepairReportMapper.selectList(wrapper);
if(data.getPartsCost()!=null&&data.getRepairCost()!=null){
data.setTotalCost(data.getPartsCost().add(data.getRepairCost()));
}else{
BigDecimal partsCost = new BigDecimal(0);
BigDecimal repairCost = new BigDecimal(0);
if(data.getPartsCost() != null){
partsCost = data.getPartsCost();
}
if(data.getRepairCost() != null){
repairCost = data.getRepairCost();
}
data.setPartsCost(partsCost);
data.setRepairCost(repairCost);
data.setTotalCost(partsCost.add(repairCost));
}
Wrapper<RepPartsRecord> wrapperRepPartsRecord =null;
List<RepPartsRecord> listRepPartsRecord =null;
if (!CollectionUtils.isEmpty(listRepRepairReport)) {
// 删除
//data.setId(listRepRepairReport.get(0).getId());
repRepairReportMapper.deleteById(listRepRepairReport.get(0).getId());
wrapperRepPartsRecord = new EntityWrapper<RepPartsRecord>();
wrapperRepPartsRecord.eq("report_id", listRepRepairReport.get(0).getId());
//wrapperRepPartsRecord.eq("del_flag", 0);
listRepPartsRecord = repPartsRecordMapper.selectList(wrapperRepPartsRecord);
}
// 新增
data.setRepairDate(new Date());
repRepairReportMapper.insert(data);
List<RepPartsRecord> list = data.getList();
// 更新
// 查询所有的来源id
List<Long> listids = new ArrayList<Long>();
if (!CollectionUtils.isEmpty(listRepPartsRecord)) {
for (RepPartsRecord repPartsRecord : listRepPartsRecord) {
listids.add(repPartsRecord.getId());
}
}
//删除
if(listids.size()>0){
repPartsRecordService.deleteBatchIds(listids);
}
//新增
if (list != null && list.size() > 0) {
if(data.getStatus().intValue() == 2){
for (RepPartsRecord repPartsRecord : list) {
if (authUser != null) {
// 设置机构
repPartsRecord.setTenantId(Long.parseLong(authUser.getTenantId() + ""));
}
repPartsRecord.setReportId(data.getId());
// 新增
repPartsRecordService.insert(repPartsRecord);
}
}else{
for (RepPartsRecord repPartsRecord : list) {
if (authUser != null) {
// 设置机构
repPartsRecord.setTenantId(Long.parseLong(authUser.getTenantId() + ""));
}
repPartsRecord.setReportId(data.getId());
repPartsRecord.setDelFlag(true);
// 新增
repPartsRecordService.insert(repPartsRecord);
}
}
}
// 更改订单状态
if (data.getStatus().intValue() == 2) {
repRepairApply.setStatus(RepairApplyStatus.WAITCHECK);
repRepairApply.setSevenStatus(DateUtil.getSevenStatus(repRepairApply.getReportRepairDate(), data.getRepairDate()));
//用户填写维修报告时,将申请单消息推送给本机构下拥有验收维修权限的用户
WeiXinRepairMessageRequest repairMessageBody = BeanMapper.map(repRepairApply, WeiXinRepairMessageRequest.class);
repairMessageBody.setApplyId(repRepairApply.getId());
repairMessageBody.setType(WeiXinRepairMessageTypeEnum.CHECK.getType());
Result<List<Map<String, Object>>> messageResult = authClientService.sendWeiXinRepairMessage(repairMessageBody, WebSecurityUtils.getCurrentToken());
logger.info("用户填写维修报告时推送消息接口返回结果="+(messageResult!=null?messageResult.getData().toString():null));
}
repRepairApplyService.updateById(repRepairApply);
return true;
}else{
throw ExceptionFactory.create("W_016");
}
}else if(result.getData().intValue()==2){
throw ExceptionFactory.create("W_021");
}else if(result.getData().intValue()==1){
//没有权限
throw ExceptionFactory.create("W_019");
}
}else{
throw ExceptionFactory.create("G_007");
}
}else{
throw ExceptionFactory.create("W_017");
}
} else {
throw ExceptionFactory.create("W_002");
}
return null;
}
@Override
public RepRepairReportResponse searchResponse(Long id) {
HashOperations<String, String, String> hash= redisTemplate.opsForHash();
RepRepairReportResponse response=new RepRepairReportResponse();
Wrapper<RepRepairReport> wrapper=new EntityWrapper<RepRepairReport>();
wrapper.eq("apply_id", id);
wrapper.eq("del_flag", 0);
List<RepRepairReport> list=repRepairReportMapper.selectList(wrapper);
if (!CollectionUtils.isEmpty(list)) {
RepRepairReport report = list.get(0);
response.setModeStatusName(getModeStatusName(report.getModeStatus().intValue()));
response.setOutsideCompany(report.getOutsideCompany());
response.setOutsidePhone(report.getOutsidePhone());
response.setFaultPhenomenonList(getList(hash,report.getFaultPhenomenon()));
response.setFaultReasonList(getList(hash,report.getFaultReason()));
response.setWorkContentList(getList(hash,report.getWorkContent()));
}
Wrapper<RepPartsRecord> wrapperRecord = new EntityWrapper<RepPartsRecord>();
wrapperRecord.eq("report_id", id);
wrapperRecord.eq("del_flag", 0);
List<RepPartsRecord> listRecord = repPartsRecordService.selectList(wrapperRecord);
if (!CollectionUtils.isEmpty(listRecord)) {
for(RepPartsRecord repPartsRecord:listRecord){
getReportsRecord(hash, repPartsRecord);
}
response.setList(listRecord);
}
return response;
}
private void getReportsRecord(HashOperations<String, String, String> hash, RepPartsRecord repPartsRecord) {
if(repPartsRecord.getUnit()!=null){
if(hash.get(Constants.REPAIR_DICTIONARY, repPartsRecord.getUnit())!=null){
repPartsRecord.setUnitName(hash.get(Constants.REPAIR_DICTIONARY, repPartsRecord.getUnit()));
}else{
String name= repairDictionaryService.getValue(repPartsRecord.getUnit());
if(name!=null){
hash.put(Constants.REPAIR_DICTIONARY,repPartsRecord.getUnit(), name);
repPartsRecord.setUnitName(name);
}
}
}
}
private List<String> getList(HashOperations<String, String, String> hash,String faultPhenomenon) {
if(faultPhenomenon!=null&&faultPhenomenon.length()>0){
String[] listFaultPhenomenon=faultPhenomenon.split(",");
List<String> list=new ArrayList<String>();
if(listFaultPhenomenon!=null&&listFaultPhenomenon.length>0){
for(String keyId:listFaultPhenomenon){
getKey(list,hash,keyId);
}
}
return list;
}
return null;
}
private void getKey(List<String> list,HashOperations<String, String, String> hash,String keyId) {
String reg = "^\\d+$";
boolean b= Pattern.compile(reg).matcher(keyId).find();
if(b){
String value= hash.get(Constants.REPAIR_DICTIONARY, keyId);
if(value!=null){
list.add(value);
}else{
String name= repairDictionaryService.getValue(keyId);
if(name!=null){
hash.put(Constants.REPAIR_DICTIONARY,keyId, name);
list.add(name);
}else{
list.add(keyId);
}
}
}else{
list.add(keyId);
}
}
private String getModeStatusName(int modeStatus) {
// 1,自主维修 2,外修 3,现场解决
String mode = "";
switch (modeStatus) {
case 1:
mode = "自主维修";
break;
case 2:
mode = "外修";
break;
case 3:
mode = "现场解决";
break;
default:
break;
}
return mode;
}
@Override
public RepRepairReportDetails search(Long id) {
Wrapper<RepRepairReport> wrapper=new EntityWrapper<RepRepairReport>();
wrapper.eq("apply_id", id);
wrapper.eq("del_flag", 0);
RepRepairReportDetails details=new RepRepairReportDetails();
List<RepRepairReport> list=repRepairReportMapper.selectList(wrapper);
AuthUser authUser = WebSecurityUtils.getCurrentUser();
if(!CollectionUtils.isEmpty(list)){
RepRepairReport repRepairReport=list.get(0);
Wrapper<RepPartsRecord> wrapperRepPartsRecord = new EntityWrapper<RepPartsRecord>();
wrapperRepPartsRecord.eq("report_id", repRepairReport.getId());
//wrapperRepPartsRecord.eq("del_flag", 0);
List<RepPartsRecord> listRepPartsRecord = repPartsRecordService.selectList(wrapperRepPartsRecord);
repRepairReport.setList(listRepPartsRecord);
details = BeanMapper.map(repRepairReport, RepRepairReportDetails.class);
getDetails(details);
}
Wrapper<RepRepairTakeOrders> wrapperTakeOrders=new EntityWrapper<>();
wrapperTakeOrders.eq("apply_id", id);
List<RepRepairTakeOrders> listTakeOrders=repRepairTakeOrdersService.selectList(wrapperTakeOrders);
RepRepairTakeOrders repRepairTakeOrders=null;
if(listTakeOrders!=null&&listTakeOrders.size()>0){
repRepairTakeOrders=listTakeOrders.get(0);
}
if(repRepairTakeOrders!=null){
if(authUser!=null){
details.setFlag(repRepairTakeOrders.getRepairId().longValue()==authUser.getId().longValue()?true:false);
}
}
return details;
}
private void getDetails(RepRepairReportDetails details) {
HashOperations<String, String, String> hash= redisTemplate.opsForHash();
details.setFaultPhenomenonList(getList(hash,details.getFaultPhenomenon()));
details.setFaultReasonList(getList(hash,details.getFaultReason()));
details.setWorkContentList(getList(hash,details.getWorkContent()));
if (!CollectionUtils.isEmpty(details.getList())) {
for(RepPartsRecord repPartsRecord:details.getList()){
getReportsRecord(hash, repPartsRecord);
}
details.setList(details.getList());
}
}
}
<file_sep>/aek-repair-api/src/main/java/com/aek/ebey/repair/service/ribbon/AuthClientHystrix.java
package com.aek.ebey.repair.service.ribbon;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import com.aek.common.core.Result;
import com.aek.ebey.repair.request.WeiXinRepairMessageRequest;
/**
* 断路器
*
* @author HongHui
* @date 2017年12月13日
*/
@Component
public class AuthClientHystrix implements AuthClientService{
private static final Logger logger = LogManager.getLogger(AuthClientHystrix.class);
@Override
public Result<List<Map<String,Object>>> sendWeiXinRepairMessage(WeiXinRepairMessageRequest request,
String token) {
logger.error("Auth Server is not connected!");
logger.info("token = " + token);
logger.info("tenantId = " + request.getTenantId());
logger.info("applyId = " + request.getApplyId());
logger.info("type = " + request.getType());
logger.info("applyNo = " + request.getApplyNo());
logger.info("assetsName = " + request.getAssetsName());
logger.info("assetsNum = " + request.getAssetsNum());
logger.info("assetsDeptId = " + request.getAssetsDeptId());
logger.info("assetsDeptName = " + request.getAssetsDeptName());
logger.info("reportRepairId = " + request.getReportRepairId());
logger.info("reportRepairName = " + request.getReportRepairName());
return null;
}
}
<file_sep>/aek-repair-web-api/src/main/resources/sql/3.0脚本.sql
ALTER TABLE `rep_repair_message`
CHANGE COLUMN `apply_id` `module_id` bigint(20) NULL DEFAULT NULL COMMENT '模块id(维修申请id)' AFTER `id`;
ALTER TABLE `rep_repair_message`
CHANGE COLUMN `check_dept_name` `remarks` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '消息备注' AFTER `message_time`;
ALTER TABLE `rep_repair_message`
ADD COLUMN `status` int(1) NULL COMMENT '消息所属类型' AFTER `del_flag`;
UPDATE rep_repair_message set `status`=1;
<file_sep>/aek-repair-web-api/src/main/resources/sql/repair_test.sql
/*
Navicat MySQL Data Transfer
Source Server : sys
Source Server Version : 50718
Source Host : 192.168.1.57:3306
Source Database : repair_test
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2017-07-19 13:43:40
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for repair_dictionary
-- ----------------------------
DROP TABLE IF EXISTS `repair_dictionary`;
CREATE TABLE `repair_dictionary` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`typeid` bigint(20) DEFAULT NULL COMMENT '关联类型',
`key` bigint(20) DEFAULT NULL COMMENT '字典值',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '字典名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of repair_dictionary
-- ----------------------------
INSERT INTO `repair_dictionary` VALUES ('1', '1', '1001', '个');
INSERT INTO `repair_dictionary` VALUES ('2', '1', '1002', '盒');
INSERT INTO `repair_dictionary` VALUES ('3', '1', '1003', '支');
INSERT INTO `repair_dictionary` VALUES ('4', '2', '1004', '故障维修');
INSERT INTO `repair_dictionary` VALUES ('5', '2', '1005', '预防修性维修');
INSERT INTO `repair_dictionary` VALUES ('6', '2', '1006', '计量/检测后维修');
INSERT INTO `repair_dictionary` VALUES ('7', '3', '1007', '故障停机');
INSERT INTO `repair_dictionary` VALUES ('8', '3', '1008', '部分功能失效');
INSERT INTO `repair_dictionary` VALUES ('9', '3', '1009', '附件损坏');
INSERT INTO `repair_dictionary` VALUES ('10', '3', '1010', '不规则或偶发现象');
INSERT INTO `repair_dictionary` VALUES ('11', '3', '1011', '性能指标偏离');
INSERT INTO `repair_dictionary` VALUES ('12', '3', '1012', '开机后死机');
INSERT INTO `repair_dictionary` VALUES ('13', '3', '1013', '其他');
INSERT INTO `repair_dictionary` VALUES ('14', '4', '1014', '操作不当');
INSERT INTO `repair_dictionary` VALUES ('15', '4', '1015', '校正失调');
INSERT INTO `repair_dictionary` VALUES ('16', '4', '1016', '保养不当');
INSERT INTO `repair_dictionary` VALUES ('17', '5', '1017', '电源损坏');
INSERT INTO `repair_dictionary` VALUES ('18', '5', '1018', '保险丝熔断');
INSERT INTO `repair_dictionary` VALUES ('19', '5', '1019', '内部电路损坏');
INSERT INTO `repair_dictionary` VALUES ('20', '5', '1020', '机械传动部分损坏');
INSERT INTO `repair_dictionary` VALUES ('21', '5', '1021', '电机损坏');
INSERT INTO `repair_dictionary` VALUES ('22', '5', '1022', '记录器损坏');
INSERT INTO `repair_dictionary` VALUES ('23', '5', '1023', '显示器损坏');
INSERT INTO `repair_dictionary` VALUES ('24', '5', '1024', '附件损坏');
INSERT INTO `repair_dictionary` VALUES ('25', '5', '1025', '电池失效');
INSERT INTO `repair_dictionary` VALUES ('26', '5', '1026', '软件损坏');
INSERT INTO `repair_dictionary` VALUES ('27', '6', '1027', '电源');
INSERT INTO `repair_dictionary` VALUES ('28', '6', '1028', '温度');
INSERT INTO `repair_dictionary` VALUES ('29', '6', '1029', '湿度');
INSERT INTO `repair_dictionary` VALUES ('30', '6', '1030', '气源');
INSERT INTO `repair_dictionary` VALUES ('31', '6', '1031', '水源');
INSERT INTO `repair_dictionary` VALUES ('32', '6', '1032', '电磁干扰');
INSERT INTO `repair_dictionary` VALUES ('33', '7', '1033', '修理');
INSERT INTO `repair_dictionary` VALUES ('34', '7', '1034', '更换部件');
INSERT INTO `repair_dictionary` VALUES ('35', '7', '1035', '电路板更换');
INSERT INTO `repair_dictionary` VALUES ('36', '7', '1036', '附件更换');
INSERT INTO `repair_dictionary` VALUES ('37', '7', '1037', '调试与校正');
INSERT INTO `repair_dictionary` VALUES ('38', '7', '1038', '维护,保养');
INSERT INTO `repair_dictionary` VALUES ('39', '7', '1039', '软件重新设置与安装');
INSERT INTO `repair_dictionary` VALUES ('40', '7', '1040', '排除外界因素');
INSERT INTO `repair_dictionary` VALUES ('41', '7', '1041', '其他');
INSERT INTO `repair_dictionary` VALUES ('42', '8', '1042', '工作正常');
INSERT INTO `repair_dictionary` VALUES ('43', '8', '1043', '基本功能正常');
INSERT INTO `repair_dictionary` VALUES ('44', '8', '1044', '需要进一步修理');
INSERT INTO `repair_dictionary` VALUES ('45', '8', '1045', '需要外送修理');
INSERT INTO `repair_dictionary` VALUES ('46', '8', '1046', '无法修复');
INSERT INTO `repair_dictionary` VALUES ('47', '8', '1047', '其他');
-- ----------------------------
-- Table structure for repair_dictype
-- ----------------------------
DROP TABLE IF EXISTS `repair_dictype`;
CREATE TABLE `repair_dictype` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '类型名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of repair_dictype
-- ----------------------------
INSERT INTO `repair_dictype` VALUES ('1', '配件单位');
INSERT INTO `repair_dictype` VALUES ('2', '维修类型');
INSERT INTO `repair_dictype` VALUES ('3', '故障现象');
INSERT INTO `repair_dictype` VALUES ('4', '人为因素');
INSERT INTO `repair_dictype` VALUES ('5', '设备故障');
INSERT INTO `repair_dictype` VALUES ('6', '外界环境因素');
INSERT INTO `repair_dictype` VALUES ('7', '工作内容');
INSERT INTO `repair_dictype` VALUES ('8', '维修结果');
-- ----------------------------
-- Table structure for rep_message_receive
-- ----------------------------
DROP TABLE IF EXISTS `rep_message_receive`;
CREATE TABLE `rep_message_receive` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID主键',
`message_id` bigint(20) DEFAULT NULL COMMENT '关联消息ID',
`user_id` bigint(20) DEFAULT NULL COMMENT '接收人ID',
`message_status` tinyint(1) DEFAULT NULL COMMENT '消息状态;0未查看1已查看',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='消息接收表';
-- ----------------------------
-- Records of rep_message_receive
-- ----------------------------
-- ----------------------------
-- Table structure for rep_repair_apply
-- ----------------------------
DROP TABLE IF EXISTS `rep_repair_apply`;
CREATE TABLE `rep_repair_apply` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID主键',
`tenant_id` bigint(20) NOT NULL COMMENT '机构ID',
`apply_no` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '维修申请单号',
`assets_id` bigint(20) NOT NULL COMMENT '关联设备ID',
`assets_dept_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '使用科室名称',
`assets_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '设备名称',
`assets_num` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '资产编号',
`fault_desc` varchar(300) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '故障描述',
`assets_img` varchar(500) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '设备图片路径,多图以,分割',
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态,1:待故障判定、2:现场解决、3:待维修、4:以维修待验收、5:验收通过、6:验收不通过;',
`urgent_level` tinyint(1) DEFAULT NULL COMMENT '紧急程度(1;2;3;4)',
`report_repair_id` bigint(20) DEFAULT NULL COMMENT '报修申请人ID',
`report_repair_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '申请人姓名',
`report_repair_date` datetime DEFAULT NULL COMMENT '报修申请时间',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='设备维修申请表';
-- ----------------------------
-- Records of rep_repair_apply
-- ----------------------------
-- ----------------------------
-- Table structure for rep_repair_appraisal
-- ----------------------------
DROP TABLE IF EXISTS `rep_repair_appraisal`;
CREATE TABLE `rep_repair_appraisal` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID主键',
`apply_id` bigint(20) DEFAULT NULL COMMENT '关联申请单id',
`identify_id` bigint(20) DEFAULT NULL COMMENT '鉴定人id',
`identify_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '鉴定人姓名',
`identify_date` datetime DEFAULT NULL COMMENT '鉴定时间',
`scene_flag` tinyint(1) DEFAULT NULL COMMENT '现场解决1是2否',
`repair_mode` tinyint(1) DEFAULT NULL COMMENT '1:内修;2:外修',
`identify_coment` varchar(300) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '鉴定备注',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='维修鉴定表';
-- ----------------------------
-- Records of rep_repair_appraisal
-- ----------------------------
-- ----------------------------
-- Table structure for rep_repair_check
-- ----------------------------
DROP TABLE IF EXISTS `rep_repair_check`;
CREATE TABLE `rep_repair_check` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`apply_id` bigint(20) DEFAULT NULL COMMENT '关联申请单id',
`repair_check_date` datetime DEFAULT NULL COMMENT '验收时间',
`repair_attitude` tinyint(4) DEFAULT NULL COMMENT '维修态度',
`response_speed` tinyint(4) DEFAULT NULL COMMENT '响应速度',
`repair_quality` tinyint(4) DEFAULT NULL COMMENT '维修质量',
`assess_coment` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT '评价备注',
`check_status` tinyint(1) DEFAULT NULL COMMENT '验收结果1,验收通过2,验收未通过',
`assets_status` tinyint(4) DEFAULT NULL COMMENT '设备现况(1:正常工作;2:基本正常;3:其它)',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='验收详情表';
-- ----------------------------
-- Records of rep_repair_check
-- ----------------------------
-- ----------------------------
-- Table structure for rep_repair_message
-- ----------------------------
DROP TABLE IF EXISTS `rep_repair_message`;
CREATE TABLE `rep_repair_message` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID主键',
`apply_id` bigint(20) DEFAULT NULL COMMENT '关联维修申请id',
`message_content` varchar(1000) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '消息内容',
`message_time` datetime DEFAULT NULL COMMENT '消息时间',
`assets_dept_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '输入科室',
`assets_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '设备名称',
`assets_id` bigint(20) DEFAULT NULL,
`message_level` tinyint(1) DEFAULT NULL COMMENT '消息紧急程度',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='消息表';
-- ----------------------------
-- Records of rep_repair_message
-- ----------------------------
-- ----------------------------
-- Table structure for rep_repair_parts
-- ----------------------------
DROP TABLE IF EXISTS `rep_repair_parts`;
CREATE TABLE `rep_repair_parts` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`report_id` bigint(20) NOT NULL COMMENT '维修报告ID',
`part_id` bigint(20) DEFAULT NULL COMMENT '配件id',
`part_no` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '配件编号',
`part_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '配件名称',
`part_produce` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '配件生产商',
`part_spec` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '配件规格',
`unit_key` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '计数单位字典表',
`num` smallint(3) NOT NULL COMMENT '使用数量',
`part_price` bigint(20) NOT NULL COMMENT '配件单价',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='维修配件表';
-- ----------------------------
-- Records of rep_repair_parts
-- ----------------------------
-- ----------------------------
-- Table structure for rep_repair_report
-- ----------------------------
DROP TABLE IF EXISTS `rep_repair_report`;
CREATE TABLE `rep_repair_report` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`apply_id` bigint(20) DEFAULT NULL COMMENT '关联申请单id',
`repair_type_key` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '关联维修类型字典表',
`fault_phenomenon_keys` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '故障现象Ids字典表',
`fault_reason_keys` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '故障原因ids字典表',
`work_content_keys` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '工作内容ids字典表',
`repair_result_key` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '维修结果关联字典表',
`repair_period_start` datetime DEFAULT NULL COMMENT '维修开始日期',
`repair_period_end` datetime DEFAULT NULL COMMENT '维修结束日期',
`parts_waiting_start` datetime DEFAULT NULL COMMENT '配件等待开始时间',
`parts_waiting_end` datetime DEFAULT NULL COMMENT '配件等待结束时间',
`actual_start` datetime DEFAULT NULL COMMENT '实际开始时间',
`actual_end` datetime DEFAULT NULL COMMENT '实际结束时间',
`repair_cost` bigint(20) DEFAULT NULL COMMENT '维修费用',
`parts_cost` bigint(20) DEFAULT NULL COMMENT '材料费用',
`total_cost` bigint(20) DEFAULT NULL COMMENT '总计',
`repair_coment` varchar(500) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '维修备注',
`repair_id` bigint(20) DEFAULT NULL COMMENT '维修人ID',
`repair_name` varchar(20) DEFAULT NULL COMMENT '维修人名称',
`repair_date` datetime DEFAULT NULL COMMENT '提交报告单时间',
`custom_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='维修报告单表';
-- ----------------------------
-- Records of rep_repair_report
-- ----------------------------
|
bce621fe09b43106c90f54df068de795b3203266
|
[
"Markdown",
"Java",
"SQL"
] | 77 |
Java
|
honghuixixi/aek-repair-service
|
f2d713bf603b3ef3c737042c1f87df217b7e6ecd
|
7b48f5cbe34abbf621e513eec5bd06ee9a82f8f4
|
refs/heads/main
|
<repo_name>data301-2020-winter2/course-project-solo_121<file_sep>/README.md
[](https://classroom.github.com/online_ide?assignment_repo_id=366454&assignment_repo_type=GroupAssignmentRepo)
# Group YYY - {Short snappy Title of your project}
- Your title can change over time.
## Milestones
Details for Milestone are available on Canvas (left sidebar, Course Project) or [here](https://firas.moosvi.com/courses/data301/project/milestone01.html).
## Describe your topic/interest in about 150-200 words
This data explains the medical cost of small population in the United States. Its columns are sample's age, sex, bmi, number of children or dependets, if the sample is smoker or not, region and medical costs. This data is used in the book introducing machine learning using R. So, I beliece this data was corrected for education of machine learning and public interest that how their health and life choices affect their medical costs.
## Describe your dataset in about 150-200 words
Of course, I would like to see which column most affect to the medical cost. Also I am interested in finding how or which column affect to other or lead to unhealthy life. For example, what kind of person tend to smoke or in out og health range of BMI, and test if genders affect these facts. Especially I would like to see if single mothers and fathers are experiencing unhealthy habits or unhealthy body mass since it is stressful to take care her kids alone and support them financially.
## Team Members
- Person 1: one sentence about you!
- Person 2: one sentence about you!
- Person 3: one sentence about you!
## References
https://gist.github.com/meperezcuello/82a9f1c1c473d6585e750ad2e3c05a41
This is the video link: https://youtu.be/ByL1-8TKFAY
<file_sep>/analysis/scripts/project_function.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def cleaning(data):
data=(data
#.dropna()
.rename(columns={'charges': 'cost'})
.reset_index()
.drop(columns=['index'])
.sort_values(by=['age'])
)<file_sep>/analysis/scripts/.ipynb_checkpoints/README-checkpoint.md
Any py files will be placed in this directory.
|
51bfc48cf426e201e254d5dda46dd7fa19f47ba7
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
data301-2020-winter2/course-project-solo_121
|
015d9ef8474d4b1bb20cabd5465705606b6c4d5f
|
fad971d2f1db6753fde5aaa47cacfcfdf21e40f9
|
refs/heads/master
|
<file_sep># es6
#Setting up the project
#Prerequisite
npm and angular cli
Install Globally
npm install -g @angular/cli
Install Locally
npm install @angular/cli
npm init -y //To Skip Interactive questions
#Commands for actual js lib and webpack on cmd line but change package.json file "scripts": "start":"webpack --mode development"
npm i [email protected] [email protected] --save-dev
#Installing server which contiously runs the code but change the package.json to "scripts": "start":"webpack-dev-server --mode development"
npm i [email protected] --save-dev
#Transpiler -> Downloading the Transpilers ie babel so that our js will run properly in the old browsers
npm i [email protected] [email protected] [email protected] --save-dev
#Issues Faced
If the Server is not exited properly
Find process id -
~ Windows - >netstat -aon | findstr 3000
~ Kill the porcess > taskkill /pid 8884
#npm start
#Notes
Methods and Modules | Section Overview
Section Overview/Coding Break: Methods and Modules
You made it to the end of the ES6 essentials overview! Woohoo! Now we can move on to some new material in ES6. Before you race onward, here you have a pitstop for an optional coding break. We’ll briefly review the vital topics that came up in this section. But you can use this time to grab coffee or whatever you need to keep learning :)
ES6 introduces the arrow function and a whole lot of helper methods to simplify manipulating arrays, objects, strings, and numbers.
The arrow function works just like a normal function expression, but with reduced syntax: ( ) => { … }
By default, arrow functions are anonymous because we declare them with an operator rather than the ‘function’ keyword.
The map helper method creates arrays by calling functions on each individual element of an initial array.
The filter helper method creates arrays based on the same elements of an original array depending on a certain test.
String.repeat() creates large strings by concatenating a string a certain number of times.
The search methods for strings include .startsWith, .endsWith, .includes, and more.
Number type checking can occur through the Number.isFinite method.
Number safety checking can occur through the Number.isSafeInteger method.
Modules refer to reusable pieces of code within an application. Most often, they exist independently within separate files, which come in handy when having to split up a large application.
The export keyword sends primitive values, objects, or functions from one module to another.
The import keyword receives primitive values, objects, or functions from another module.
Using the default keyword gives a module a fallback function when exporting multiple values and methods.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Classes and Prototypes | Section Overview
We just thoroughly explored classes and prototypes in JavaScript. Many of the concepts we discussed span even beyond the realm of ES6 and JS, so these lessons will translate to most programming languages you come across.
We covered a lot of ground though. It may feel nice to take an optional coding break. Grab some coffee, tea, or whatever you need - the usual!
Ok, let’s review the important topics we went over:
Classes in JavaScript construct structures of data based off of the state and behavior of real world objects and introduce a system of inheritance.
The constructor keyword initializes an object for a class.
The extends keyword creates subclasses and children of parent classes.
Static methods in classes can be called even outside the context of class.
Object-oriented programming models objects to create programs centered around the interactions of these objects with each other. Major programming languages like C, Java, and Ruby contain heavy support for object-oriented programming.
JavaScript is not based on object-oriented programming, but a prototypal-inheritance model.
A prototype is a characteristic in every JavaScript object that reveals its parent and the properties that it inherits.
All JavaScript objects contain a prototype and can trace their chain of prototypal inheritance all the way back to the base level Object prototype.
Arrow functions don’t create their own local ‘this’ object like a normal function prototype, but instead refer to the ‘this’ tied to its outer scope.
Classes and prototypes appear everywhere in JavaScript. And every ES6 programmer needs to grasp these fundamental concepts to truly grasp how the language works. Luckily, once you understand that classes are simply prototypes, and prototypes are simply references to an object’s parent, it becomes less abstract.
Ok class (or should I say prototype?), off to the next subject!<file_sep>export {add, multiply}
const add = (a,b) => a+b;
const multiply = (a,b) => a*b;
export default multiply;
|
9b42e7e527a907ba485f9824867722fe5a6cf7db
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
MrAbhishekDas/es6
|
6adcf980133828d65f17e576d8a20f0bc907f966
|
c11703ff4f901aeb4809c7846a3d899ac2d7d119
|
refs/heads/master
|
<repo_name>TheDuplicity/CMP105_W6<file_sep>/Week6/CMP105App/ForcePhysics.h
#pragma once
#include "Framework/GameObject.h"
class ForcePhysics : public GameObject {
protected:
float gravity;
float drag;
sf::RenderWindow* window;
sf::Vector2f direction;
public:
ForcePhysics();
ForcePhysics(sf::RenderWindow* currentWindow);
~ForcePhysics();
void gravityUpdate(float dt);
};
<file_sep>/Week6/CMP105App/ForcePhysics.cpp
#include "ForcePhysics.h"
#include "Framework/Vector.h"
ForcePhysics::ForcePhysics() {
}
ForcePhysics::ForcePhysics(sf::RenderWindow* currentWindow) {
direction = velocity;
gravity = 10.f;
drag = 0.5f;
window = currentWindow;
}
ForcePhysics::~ForcePhysics() {
}
void ForcePhysics::gravityUpdate(float dt) {
setPosition(getPosition() + sf::Vector2f(velocity.x ,velocity.y * dt + 0.5 * gravity * dt * dt));
velocity += (sf::Vector2f(0, gravity) * dt);
if (getPosition().y + getSize().y > window->getSize().y) {
setPosition(getPosition().x, window->getSize().y - getSize().y);
velocity.y = 0;
}
//move(velocity);
}
|
8aa9c051246fb3fd4c4b71426e66a39b05b38f6a
|
[
"C++"
] | 2 |
C++
|
TheDuplicity/CMP105_W6
|
33da7fc9b7ecee0e2fa9c18e6db01cf5e31a7d1a
|
74ba66b549e6698df1b7a2eef657f73fb62a1605
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.