blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17fe9ddc4cd9457a1575b96def2a77cc8d414940
|
913c4e6121012405582ba92364a4c9518a184a3b
|
/16-2.cc
|
ae59173f7c0488217cdd7ece3c5e60007d95d5fd
|
[] |
no_license
|
weijiaming2012/Cpp
|
56c3f79532405c8d58d9e2b4fade1eb195718b4d
|
d942fec522613f66d1730777d6c64fa927ce068e
|
refs/heads/master
| 2020-07-08T19:39:52.747168
| 2019-10-27T13:15:45
| 2019-10-27T13:15:45
| 203,758,783
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 330
|
cc
|
16-2.cc
|
#include<iostream>
using namespace std;
int main()
{
int donuts,milk;
double dpg;
try{
cout<<"Enter donuts:";
cin>>donuts;
cout<<"Enter milk:";
cin>>milk;
if(milk<=0)
{
throw donuts;
}
dpg=donuts/static_cast<double>(milk);
cout<<"dpg:"<<dpg<<endl;
}
catch(int e)
{
cout<<e<<endl;
}
return 0;
}
|
feaa6185ae88b43905fd82c681921a30a84f27f5
|
42d4df931d26091b5a2963d811db88f710469bdd
|
/src/proposer.cc
|
b0b38c5ef62a0128222ea637fcf5faeb357aff09
|
[] |
no_license
|
irbowen/Sharded_Key_Value_Store
|
4245e65a957b3054412812c4907be5cdd9797dad
|
ca49d2e2de916d0889874705921d6980a8186a58
|
refs/heads/master
| 2021-01-19T08:45:22.188074
| 2017-05-15T19:54:18
| 2017-05-15T19:54:18
| 87,669,516
| 8
| 0
| null | 2017-05-15T19:54:19
| 2017-04-08T23:05:29
|
C++
|
UTF-8
|
C++
| false
| false
| 4,753
|
cc
|
proposer.cc
|
#include "../headers/proposer.h"
using namespace std;
void Proposer::init(Environment* env, vector<int> holes) {
env_ = env;
seq_holes = holes;
quorum_ = (1 + env_->num_replicas_) >> 1;
}
Message* Proposer::handle_start_prepare(int view_num) {
Message *msg = new Message;
msg->msg_type = MessageType::PREPARE;
msg->view_num = view_num;
return msg;
}
Message* Proposer::handle_prepare_accept_fast(std::vector<view_val> acceptor_state, int view_num, std::string value, int seq_num) {
Message *msg = new Message;
// regular case where proposer proposes the original value
msg->msg_type = MessageType::PROPOSE;
// bug fixed : view num can never be -1 (we did this earlier since we had n_a)
if (value == "") {
// Propose the original value
msg->value = to_propose;
msg->view_num = view_num;
} else {
// Propose the already accepted value
msg->value = value;
msg->view_num = view_num;
}
// TODO : Need to add sequence number to this message (Important) - Pranav
// if quorum is not reached, the message type default is NO_ACTION
msg->seq_num = seq_num;
return msg;
}
// TODO check view vs proposal
// Note: copying vector by value to avoid delete invalidation
Message* Proposer::handle_prepare_accept(std::vector<view_val> acceptor_state, int view_num, std::string value, int seq_num) {
Message *msg = new Message;
if (is_new_primary) {
all_acceptors_state.push_back(acceptor_state);
}
count[view_num] += 1;
if (count[view_num] == quorum_ && is_new_primary) {
// i am the new primary, i have reached a quorum, i have f+1 acceptor states
// i can begin the fix process
// find longest acceptor state
auto max_length_acceptor = std::max_element(all_acceptors_state.begin(), all_acceptors_state.end(),
[]( const std::vector<view_val> &a, const std::vector<view_val> &b )
{
return a.size() < b.size();
});
// for each column
for (int j = 0; j < max_length_acceptor->size(); j++) {
// for each item in that column
std::map<int, int> quorum_count;
bool quorum_reached = false;
// Note: best_view_val has -1 view num and no_op value by default
// if it doesn't get updated in the below loop, we can decide accordingly
view_val best_view_val;
for(int i = 0; i < all_acceptors_state.size(); i++){
auto item = all_acceptors_state[i][j];
quorum_count[item.view_num] += 1;
if(quorum_count[item.view_num] >= quorum_){
quorum_reached = true;
}
if(item.view_num > best_view_val.view_num){
best_view_val = item;
}
}
if(!quorum_reached){
Message *reply = new Message;
reply->view_num = view_num; // view_num of the new primary
reply->value = best_view_val.value; // will automatically be no_op if that is the best
reply->seq_num = j; // jth column becomes the sequence number
reply->msg_type = MessageType::PROPOSE;
//broadcast message
for (auto& r : replicas) {
reply->receivers.push_back(r);
}
reply->sender = replicas[id]; // quick hack to get proposer's info
env_->net_->sendto(reply);
}
// if quorum is reached, do nothing for this column
}
// update sequence number to max_length
seq_num = static_cast<int>(max_length_acceptor->size());
// update seq_num if required based on acceptor state
// seq_num = new_seq_num;
is_new_primary = false;
all_acceptors_state.clear();
}
if (count[view_num] == quorum_) {
return handle_prepare_accept_fast(acceptor_state, view_num, value, seq_num);
}
return msg;
}
Message* Proposer::handle_prepare_reject(int view_num) {
// go back to prepare phase
return handle_start_prepare(view_num + 1);
}
Message* Proposer::handle_propose_accept(int n) {
// nothing to do for now in this scenario
Message *msg = new Message;
return msg;
}
Message* Proposer::handle_propose_reject(int view_num) {
// if the proposal gets rejected, we are back to the prepare phase
return handle_start_prepare(view_num + 1);
}
bool Proposer::reached_quroum(int view_num) {
return count[view_num] >= quorum_;
}
bool Proposer::is_seq_hole(int seq){
return find(seq_holes.begin(), seq_holes.end(), seq) != seq_holes.end();
}
|
7296bb7ac27ef37b6116fb12a571b5d05aa59981
|
fcaaf840784495f21a8b1a56ed9e5ca38c84bcc3
|
/Week 5/homework/hw5-2.cpp
|
c9b68eb5fdc507c1d5715c01a594888739ac6519
|
[] |
no_license
|
stephanie0324/Data-Structure-2020
|
4215c805166493e899d2c489ce78a66610afdc86
|
268aba9c3166b43bd4c679003630fb4988abd263
|
refs/heads/master
| 2021-02-18T04:45:22.670038
| 2020-07-03T08:27:18
| 2020-07-03T08:27:18
| 245,162,230
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,095
|
cpp
|
hw5-2.cpp
|
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
const int Max_Val = 1000;
//============================================================================
// Item
// 若為 1,表示該道具是所有角色都可以使用的;若為 2,只有戰士可以 使用;若為 3,只有巫師可以使用。
//============================================================================
struct typeArray
{
string name;
int type;
};
template <typename Itemtype>
class BagInterface
{
public:
virtual int getCurrentSize() const = 0;
virtual bool isEmpty() const = 0;
virtual void add(const Itemtype& name) = 0;
};
//---------------NODE---------------------------//
template<class Itemtype>
class Node
{
private:
Itemtype item;
Node<Itemtype>* next;
public:
Node();
Node(const Itemtype& anItem);
Node(const Itemtype& anItem, Node<Itemtype>* nextNodePtr);
void setItem(const Itemtype& anItem);
void setNext(Node<Itemtype>* nextNodePtr);
Itemtype getItem() const;
Node<Itemtype>* getNext() const;
};
template<class Itemtype>
Node<Itemtype>::Node() : next(nullptr)
{
}
template<class Itemtype>
Node<Itemtype>::Node(const Itemtype& anItem) : item(anItem), next(nullptr)
{
}
template<class Itemtype>
Node<Itemtype>::Node(const Itemtype& anItem, Node<Itemtype>* nextNodePtr) :
item(anItem), next(nextNodePtr)
{
}
template<class Itemtype>
void Node<Itemtype>::setItem(const Itemtype& anItem)
{
item = anItem;
}
template<class Itemtype>
void Node<Itemtype>::setNext(Node<Itemtype>* nextNodePtr)
{
next = nextNodePtr;
}
template<class Itemtype>
Itemtype Node<Itemtype>::getItem() const
{
return item;
}
template<class Itemtype>
Node<Itemtype>* Node<Itemtype>::getNext() const
{
return next;
}
//----------------LINKED----------------------//
template<typename Itemtype>
class LinkedBag: public BagInterface<Itemtype>
{
private:
Node<Itemtype> *headPtr;
int itemCnt;
public:
virtual bool isEmpty() const = 0;
virtual int getCurrentSize() const = 0;
virtual void add(const Itemtype& newEntry);
virtual void remove(const Itemtype& anEntry);
virtual Node<Itemtype> *getPointerTo(const Itemtype& anEntry) const = 0;
virtual bool contains(const Itemtype& anEntry) const = 0;
virtual void clear();
virtual void getItemList();
LinkedBag(); //default constructor
LinkedBag(const LinkedBag<Itemtype>& aBag); //copt constructor
virtual ~LinkedBag(); //destructor
};
template<typename Itemtype>
bool LinkedBag<Itemtype>::isEmpty() const
{
return itemCnt == 0;
}
template<typename Itemtype>
int LinkedBag<Itemtype>::getCurrentSize() const
{
return itemCnt;
}
template<typename Itemtype>
void LinkedBag<Itemtype>::add(const Itemtype& newEntry)
{
Node<Itemtype>* newNodePtr = new Node<Itemtype>();
newNodePtr->setItem(newEntry);
newNodePtr->setNext(headPtr);
headPtr = newNodePtr;
itemCnt++;
}
template<typename Itemtype>
void LinkedBag<Itemtype>::remove(const Itemtype& anEntry)
{
Node<Itemtype>* entryNodePtr = getPointerTo(anEntry); // step 1
bool canRemoveItem = !isEmpty() && (entryNodePtr != nullptr);
if(canRemoveItem)
{
entryNodePtr->setItem(headPtr->getItem()); // step 2
Node<Itemtype>* nodeToDeletePtr = headPtr; // step 3
headPtr = headPtr->getNext();
delete nodeToDeletePtr;
nodeToDeletePtr = nullptr;
itemCnt--;
}
}
template<typename Itemtype>
bool LinkedBag<Itemtype>::contains(const Itemtype& anEntry) const
{
return (getPointerTo(anEntry) != nullptr);
}
template<typename Itemtype>
Node<Itemtype>* LinkedBag<Itemtype>::getPointerTo(const Itemtype& anEntry) const
{
bool found = false;
Node<Itemtype>* curPtr = headPtr;
while(!found && (curPtr != nullptr))
{
if(anEntry == curPtr->getItem())
found = true;
else
curPtr = curPtr->getNext();
}
return curPtr;
}
template<typename Itemtype>
void LinkedBag<Itemtype>::clear()
{
Node<Itemtype>* nodeToDeletePtr = headPtr;
while(headPtr != nullptr)
{
headPtr = headPtr->getNext();
delete nodeToDeletePtr;
nodeToDeletePtr = headPtr;
}
itemCnt = 0;
}
template<typename Itemtype>
void LinkedBag<Itemtype>::getItemList()
{
string tmp[itemCnt];
for(int i = 0 ; i < itemCnt ; i++){
tmp[i] = headPtr->getItem();
headPtr = headPtr->getNext();
}
for(int i =0; i<itemCnt ; i++){
cout << tmp[i]<< " ";
}
cout << endl;
}
//-------------------------------Con & Destructors-----------------------------//
template<typename Itemtype>
LinkedBag<Itemtype>::LinkedBag():headPtr(nullptr),itemCnt(0)
{}
template<typename Itemtype>
LinkedBag<Itemtype>::~LinkedBag()
{
clear();
}
//deep copy version
template<typename Itemtype>
LinkedBag<Itemtype>::LinkedBag(const LinkedBag<Itemtype>& aBag)
{
itemCnt = aBag->itemCnt;
Node<Itemtype>* origChainPtr = aBag->headPtr;
if(origChainPtr == nullptr)
headPtr = nullptr;
else
{
headPtr = new Node<Itemtype>();
headPtr->setItem(origChainPtr->getItem());
Node<Itemtype>* newChainPtr = headPtr;
while(origChainPtr != nullptr)
{
origChainPtr = origChainPtr->getNext();
Itemtype nextItem = origChainPtr->getItem();
Node<Itemtype>* newNodePtr = new Node<Itemtype>(nextItem);
newChainPtr->setNext(newNodePtr);
newChainPtr = newChainPtr->getNext();
}
newChainPtr->setNext(nullptr);
}
}
//============================================================================
// End of Item
//============================================================================
// ===========================================================================
// Character, Warrior, Wizard, and Team
// ===========================================================================
class Character
{
protected:
static const int EXP_LV = 100;
string name;
int level;
int bag_max;
int career;
public:
Character(string n, int lv, int bm , int career);
LinkedBag <string> itemBag;
string getName();
int getBagMax();
int getCareer();
void useItem(const string& item_name , int ta_cnt , typeArray *ta);
};
Character::Character(string n, int lv, int bm , int career)
: name(n), level(lv), bag_max(bm), career(career)
{
}
string Character::getName()
{
return this->name;
}
int Character::getBagMax()
{
return this ->bag_max;
}
int Character::getCareer()
{
return this ->career;
}
void Character::useItem(const string& item_name , int ta_cnt , typeArray *ta)
{
if(this->itemBag.contains(item_name)==true){
// cout <<"yyy"<<endl;
for(int j = 0 ; j < ta_cnt ; j++){
if((ta[j].name).compare(item_name)==0){
if(ta[j].type == 1){
this->itemBag.remove(item_name);
}else if(ta[j].type == this->getCareer()){
this->itemBag.remove(item_name);
}else if(ta[j].type != this->getCareer())
cout <<"cannot use it"<<endl;
}
}
}else{
cout << "does the character own it?"<<endl;
}
}
class Warrior : public Character
{
private:
public:
Warrior(string n, int lv , int bm ,int career) : Character(n, lv, bm ,career) {}
};
class Wizard : public Character
{
private:
public:
Wizard(string n, int lv , int bm , int career) : Character(n, lv, bm ,career) {}
};
//=====================================================
// oop(p. 49)
class Team
{
private:
int memberCount;
Character *member[10];
public:
Team();
~Team();
};
//======================================================
//opp(p. 50)
Team::Team()
{
this->memberCount = 0;
for(int i = 0; i < 10; i++)
member[i] = nullptr;
}
Team::~Team()
{
for(int i = 0; i < this->memberCount; i++)
delete this->member[i];
}
// ===========================================================================
// End of Character, Warrior, Wizard, and Team
// ===========================================================================
int main()
{
Character *member[10];
typeArray ta[Max_Val];
string order;
string sub;
//各種cnt
int characterCnt = 0;
int ta_cnt = 0;
int itembagCnt = 0;
while(cin)
{
getline(cin , order ,' ');
bool exists =false;
// 增加一個戰士角色
if(order.compare("R")==0)
{
string name;
int lv = 0;
int bm = 0;
// cout << "addWAR" << endl;
getline(cin , sub , ' ');
name = sub;
//---------檢查是否存在-------------
for(int i = 0 ; i < characterCnt ; i++){
if(member[i]->getName()==name){
exists = true;
}
}
if(exists ==true)
{
cout << "the character exists" <<endl;
getline(cin , sub , '\n');
}
else{
getline(cin , sub , ' ');
lv = stoi(sub);
getline(cin , sub , '\n');
bm = stoi(sub);
member[characterCnt] = new Warrior(name , lv , bm , 2);
characterCnt++;
}
}
//增加一個巫師
else if(order.compare("D")==0)
{
string name;
int lv = 0;
int bm = 0;
// cout << "addWIZ" << endl;
getline(cin , sub , ' ');
name = sub;
//---------檢查是否存在-------------
for(int i = 0 ; i < characterCnt ; i++){
if(member[i]->getName()==name){
exists = true;
}
}
if(exists ==true)
{
cout << "the character exists"<<endl;
getline(cin,sub,'\n');
}
else{
getline(cin , sub , ' ');
lv = stoi(sub);
getline(cin , sub , '\n');
bm = stoi(sub);
member[characterCnt] = new Wizard(name , lv , bm , 3);
characterCnt++;
}
//增加道具
}else if(order.compare("A")== 0)
{
// cout << "Add" <<endl;
string name;
string item_name;
int type;
getline(cin , sub , ' ');
name = sub;
getline(cin , sub , ' ');
item_name = sub;
getline(cin , sub , '\n');
type = stoi(sub);
//先記錄屬性,不重複紀錄
bool ta_exists = false;
for(int i = 0 ; i < ta_cnt ; i++){
if(ta[i].name==item_name){
ta_exists = true;
}
}
if(ta_exists==false){
ta[ta_cnt].name = item_name;
ta[ta_cnt].type = type;
ta_cnt++;
}
//放入包包
for(int i = 0 ; i < characterCnt ; i++){
if(member[i]->getName()==name)
{
exists = true;
// cout << member[i]->itemBag.getCurrentSize() <<endl;
// cout << member[i]->getBagMax() <<endl;
if(member[i]->itemBag->getCurrentSize()< member[i]->getBagMax())
{
member[i]->itemBag->add(item_name);
}
else
{
cout << "no more capacity"<<endl;
}
}
}
if(exists==false){
cout <<"no such a character"<<endl;
}
// //該角色包包中有沒有道具
// }else if(order.compare("H")== 0){
// string name;
// string item_name;
// getline(cin , sub ,' ');
// name = sub;
// getline(cin,sub,'\n');
// item_name = sub;
// for(int i = 0 ; i < characterCnt ; i++){
// if(member[i]->getName()== name){
// exists = true;
// if(member[i]->itemBag->contains(item_name)==true){
// cout << "yes"<<endl;
// }else{
// cout << "no"<<endl;
// }
// }
// }
// if(exists==false)
// cout << "no such a character"<<endl;
// //該角色使用道具
// }else if(order.compare("U")== 0){
// // cout << "uuu" <<endl;
// string name;
// string item_name;
// getline(cin,sub,' ');
// name = sub;
// getline(cin,sub,'\n');
// item_name = sub;
// for(int i = 0 ; i < characterCnt ; i++){
// if(member[i]->getName()==name){
// exists = true;
// member[i]->useItem(item_name , ta_cnt , ta);
// }
// }
// if(exists==false)
// cout << "no such a character"<<endl;
// //印出東西
// }else if(order.compare("L")== 0){
// // cout << "lll" <<endl;
// string name;
// getline(cin,sub,'\n');
// name = sub;
// for(int i = 0 ; i < characterCnt ; i++){
// if(member[i]->getName()==name){
// exists= true;
// if(member[i]->itemBag->getCurrentSize() > 0)
// member[i]->itemBag->getItemList();
// else
// cout << "empty"<<endl;
// }
// }
// if(exists==false)
// cout << "no such a character"<<endl;
//印出東西與數量
// }else if(order.compare("S")== 0){
// // cout << "sss" <<endl;
// string name;
// getline(cin,sub,'\n');
// name = sub;
// for(int i = 0 ; i < characterCnt ; i++){
// if(member[i]->getName()==name){
// exists= true;
// if(member[i]->itemBag.getCurrentSize() > 0)
// member[i]->itemBag.getItemSummary();
// else
// cout << "empty"<<endl;
// }
// }
// if(exists==false)
// cout << "no such a character"<<endl;
// //丟掉東西
// }else if(order.compare("V")== 0){
// // cout << "vvv" <<endl;
// string name;
// string item_name;
// getline(cin,sub,' ');
// name = sub;
// getline(cin,sub,'\n');
// item_name = sub;
// for(int i = 0 ; i < characterCnt ; i++){
// if(member[i]->getName()==name){
// exists= true;
// if(member[i]->itemBag.itemExists(item_name)==true){
// member[i]->itemBag.removeItem(item_name);
// }else{
// cout << "does the character own it?"<<endl;
// }
// }
// }
// if(exists==false)
// cout << "no such a character"<<endl;
// }
}
}
return 0;
}
|
50e5849cc940c30fc1c3b28a167c6940e4dd8b99
|
39dbffad5f45b1cb09061459458b79c62b0fb598
|
/Src/Base/PsuadeRSInterpreter.cpp
|
c31d190bf9f530827d031090f8d608991a0c3747
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
tong10/psuade
|
27a6af2bf5ffa23dd11c13362f2ba1d93feb20c4
|
20d7df05360d2d98cbc134e1a49e60ac33f18e20
|
refs/heads/master
| 2023-08-31T07:04:10.483864
| 2023-01-11T21:15:27
| 2023-01-11T21:15:27
| 114,056,555
| 0
| 0
| null | 2017-12-13T01:08:17
| 2017-12-13T01:08:16
| null |
UTF-8
|
C++
| false
| false
| 357,688
|
cpp
|
PsuadeRSInterpreter.cpp
|
// ************************************************************************
// Copyright (c) 2007 Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the PSUADE team.
// All rights reserved.
//
// Please see the COPYRIGHT_and_LICENSE file for the copyright notice,
// disclaimer, contact information and the GNU Lesser General Public License.
//
// PSUADE 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 2.1 dated February 1999.
//
// PSUADE 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 terms and conditions of the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ************************************************************************
// Functions for the class PsuadeBase
// AUTHOR : CHARLES TONG
// DATE : 2005
// ************************************************************************
//
// ------------------------------------------------------------------------
// system includes
// ------------------------------------------------------------------------
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <PsuadeCmakeConfig.h>
#ifdef WINDOWS
#include <windows.h>
#endif
// ------------------------------------------------------------------------
// local includes : class definition and utilities
// ------------------------------------------------------------------------
#include "Psuade.h"
#include "PsuadeBase.h"
#include "dtype.h"
#include "sysdef.h"
#include "PsuadeUtil.h"
#include "PrintingTS.h"
#include "PsuadeConfig.h"
#include "psVector.h"
#include "MainEffectAnalyzer.h"
#include "TwoParamAnalyzer.h"
// ------------------------------------------------------------------------
// local includes : function approximator and others
// ------------------------------------------------------------------------
#include "FuncApprox.h"
#include "pData.h"
#include "PDFManager.h"
#include "PDFNormal.h"
// ------------------------------------------------------------------------
// local defines
// ------------------------------------------------------------------------
#define PABS(x) ((x) > 0 ? x : -(x))
// ************************************************************************
// interpret command from interactive session
// ------------------------------------------------------------------------
int PsuadeBase::RSBasedAnalysis(char *lineIn, PsuadeSession *session)
{
int ss, ii, jj, kk, status, outputID, flag, faType;
int nSamples, outputLevel, nInputs, nOutputs, *sampleStates=NULL;
double ddata, *sampleInputs=NULL, *sampleOutputs=NULL;
double *iLowerB=NULL, *iUpperB=NULL;
char command[1001], winput[1001], pString[1001], dataFile[1001];
char lineIn2[1001], **inputNames=NULL, **outputNames=NULL;
FILE *fp=NULL;
PsuadeData *psuadeIO=NULL;
pData pPtr;
//**/ -------------------------------------------------------------
// read in command and data from main interpreter
//**/ -------------------------------------------------------------
winput[0] = '\0';
sscanf(lineIn,"%s", command);
//**/ session == NULL when help (-h) is issued
if (session == NULL)
{
nSamples = outputLevel = nInputs = nOutputs = 0;
sampleInputs = sampleOutputs = NULL;
sampleStates = NULL;
psuadeIO = NULL;
inputNames = outputNames = NULL;
iLowerB = iUpperB = NULL;
}
else
{
nSamples = session->nSamples_;
outputLevel = session->outputLevel_;
nInputs = session->nInputs_;
nOutputs = session->nOutputs_;
sampleInputs = session->vecSamInputs_.getDVector();
sampleOutputs = session->vecSamOutputs_.getDVector();
sampleStates = session->vecSamStates_.getIVector();
psuadeIO = (PsuadeData *) session->psuadeIO_;
inputNames = session->inputNames_.getStrings();
outputNames = session->outputNames_.getStrings();
iLowerB = session->vecInpLBounds_.getDVector();
iUpperB = session->vecInpUBounds_.getDVector();
}
//**/ -------------------------------------------------------------
// +++ rsua
//**/ uncertainty analysis on response surface
//**/ RS uncertainties introduced by the use of stochastic RS
//**/ Worst-case analysis (optional: average case analysis)
// ----------------------------------------------------------------
if (!strcmp(command, "rsua"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsua: uncertainty analysis on response surface\n");
printf("Syntax: rsua (no argument needed)\n");
printf("This command perform uncertainty analysis on ");
printf("the response surface\n");
printf("built from the LOADED sample. Uncertainty analysis ");
printf("is performed\n");
printf("using a user-provided sample created beforehand ");
printf("in PSUADE data\n");
printf("format or a PSUADE-generated sample. If a stochastic ");
printf("response surface\n");
printf("(e.g. Kriging, MARSB, or polynomial regression) is ");
printf("selected, its\n");
printf("response surface uncertainty will also be shown in ");
printf("the PDF and CDF\n");
printf("plots produced by this command.\n");
printf("NOTE: Turn on master mode to select between average ");
printf("case and worst\n");
printf(" case analysis.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("* Response surface-based Uncertainty Analysis\n");
printDashes(PL_INFO, 0);
printf("* To include response surface uncertainties, use ");
printf("stochastic response\n");
printf("* surface such as polynomial regression, MARSB, Kriging, ");
printf(".. (specified\n");
printf("* in your loaded data file).\n");
printf("* This command computes worst case RS uncertainties. Turn ");
printf("on MASTER\n");
printf("* mode to select average case RS uncertainties.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ query user for output ID
sscanf(lineIn,"%s %s", command, winput);
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ request or generate a sample for evaluation
printf("A sample is needed from you to propagate through the RS.\n");
printf("Select between the two options below: \n");
printf("1. PSUADE will generate the sample\n");
printf("2. User will provide the sample (in PSUADE data format)\n");
sprintf(pString, "Enter 1 or 2 : ");
int samSrc = getInt(1, 2, pString);
int uaNSams;
psVector vecUAInps, vecUAOuts;
psIVector vecUAStas;
if (samSrc == 1)
{
printf("PSUADE will generate a sample for uncertainty analysis.\n");
sprintf(pString, "Sample size ? (10000 - 100000) ");
uaNSams = getInt(10000, 100000, pString);
vecUAInps.setLength(uaNSams * nInputs);
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
int usePDFs = pPtr.intData_;
if (usePDFs == 1)
{
printf("NOTE: Some inputs have non-uniform PDFs.\n");
printf(" A MC sample will be created with these PDFs.\n");
psuadeIO->getParameter("method_sampling", pPtr);
kk = pPtr.intData_;
psuadeIO->updateMethodSection(PSUADE_SAMP_MC,-1,-1,-1,-1);
PDFManager *pdfman = new PDFManager();
pdfman->initialize(psuadeIO);
vecUAInps.setLength(uaNSams*nInputs);
psVector vecLs, vecUs;
vecUs.load(nInputs, iUpperB);
vecLs.load(nInputs, iLowerB);
pdfman->genSample(uaNSams, vecUAInps, vecLs, vecUs);
psuadeIO->updateMethodSection(kk,-1,-1,-1,-1);
delete pdfman;
}
else
{
printAsterisks(PL_INFO, 0);
printf("NOTE: Uniform distribution is assumed for all inputs. ");
printf("To use other\n");
printf(" than uniform distributions, prescribe them in ");
printf("the sample file\n");
printf(" and set use_input_pdfs in the ANALYSIS section.\n");
printAsterisks(PL_INFO, 0);
Sampling *samPtr;
if (nInputs < 51)
samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LPTAU);
else samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LHS);
samPtr->setPrintLevel(0);
samPtr->setInputBounds(nInputs, iLowerB, iUpperB);
samPtr->setOutputParams(1);
samPtr->setSamplingParams(uaNSams, -1, -1);
samPtr->initialize(0);
vecUAOuts.setLength(uaNSams);
vecUAStas.setLength(uaNSams);
samPtr->getSamples(uaNSams,nInputs,1,vecUAInps.getDVector(),
vecUAOuts.getDVector(),vecUAStas.getIVector());
delete samPtr;
}
}
else if (samSrc == 2)
{
printf("Enter UA sample file name (in PSUADE data format): ");
char uaFileName[1001];
scanf("%s", uaFileName);
fgets(lineIn2, 500, stdin);
PsuadeData *sampleIO = new PsuadeData();
status = sampleIO->readPsuadeFile(uaFileName);
if (status != 0)
{
printf("ERROR: cannot read sample file.\n");
delete sampleIO;
return 1;
}
sampleIO->getParameter("input_ninputs", pPtr);
kk = pPtr.intData_;
if (kk != nInputs)
{
printf("ERROR: sample nInputs mismatch.\n");
printf(": input size in workspace = %d.\n",nInputs);
printf(": input size from your sample = %d.\n",kk);
delete sampleIO;
return 1;
}
sampleIO->getParameter("method_nsamples", pPtr);
uaNSams = pPtr.intData_;
if (uaNSams < 1000)
{
printf("ERROR: Your sample size should be at least 1000 to give\n");
printf(" any reasonable UA results.\n");
delete sampleIO;
return 1;
}
sampleIO->getParameter("input_sample", pPtr);
vecUAInps.load(uaNSams * nInputs, pPtr.dbleArray_);
pPtr.clean();
delete sampleIO;
}
//**/ ====================================================================
// ask which method to us
//**/ ====================================================================
printf("The default is to perform the average case analysis (1): \n");
printf(" - For each sample point, evaluation using stochastic ");
printf("RS gives a mean\n");
printf(" and a std deviation. Average case analysis take ");
printf("these quantities\n");
printf(" and creates a small sample for each sample point. ");
printf("Afterward, it\n");
printf(" creates a probability distribution based on ");
printf("this enlarged sample.\n");
printf("However, you can also perform a worst case analysis (2): \n");
printf(" - For each sample point, evaluation using stochastic ");
printf("RS gives a mean\n");
printf(" and a standard deviation. Worst case analysis takes the ");
printf("max and min\n");
printf(" at each sample point as the +/- 3 std dev. Afterward, ");
printf("it creates a\n");
printf(" probability distribution enveloped by the max/min ");
printf("distributions.\n");
sprintf(pString,"Enter 1 (average case) or 2 (worst case) analysis : ");
int uaMethod = getInt(1,2,pString);
uaMethod--;
//**/ ====================================================================
// perform UA
//**/ ====================================================================
psVector vecUAStds;
vecUAOuts.setLength(uaNSams);
vecUAStds.setLength(uaNSams);
//**/ ----------------------------------------------
// stochastic RS with average case analysis
//**/ ----------------------------------------------
FuncApprox *faPtrUA=NULL;
psConfig_.InteractiveSaveAndReset();
if (uaMethod == 0)
{
//**/ create response surface
printf("** CREATING RESPONSE SURFACE\n");
faPtrUA = genFA(-1, nInputs, -1, nSamples);
if (faPtrUA == NULL)
{
printf("ERROR: cannot create response surface.\n");
return 1;
}
faPtrUA->setBounds(iLowerB, iUpperB);
faPtrUA->setOutputLevel(outputLevel);
psVector vecYOut;
vecYOut.setLength(nSamples);
for (ss = 0; ss < nSamples; ss++)
vecYOut[ss] = sampleOutputs[ss*nOutputs+outputID];
status = faPtrUA->initialize(sampleInputs,vecYOut.getDVector());
if (status != 0)
{
printf("ERROR: cannot initialize response surface.\n");
if (faPtrUA != NULL) delete faPtrUA;
return 1;
}
//**/ evaluate response surface
faPtrUA->evaluatePointFuzzy(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector(),
vecUAStds.getDVector());
fp = fopen("rsua_sample","w");
if (fp != NULL)
{
fprintf(fp,"%% This file is primarily for diagnostics and \n");
fprintf(fp,"%% expert analysis\n");
fprintf(fp,"%% First line: nSamples nInputs\n");
fprintf(fp,"%% All inputs, output(Y), Y-3*sigma,Y+3*sigma\n");
fprintf(fp,"%d %d 3\n", uaNSams, nInputs);
for (ss = 0; ss < uaNSams; ss++)
{
for (ii = 0; ii < nInputs; ii++)
fprintf(fp, "%e ", vecUAInps[ss*nInputs+ii]);
fprintf(fp, "%e ", vecUAOuts[ss]);
fprintf(fp, "%e ", vecUAOuts[ss]-3*vecUAStds[ss]);
fprintf(fp, "%e\n", vecUAOuts[ss]+3*vecUAStds[ss]);
}
fclose(fp);
printf("The outputs and std deviations of the evaluation ");
printf("sample has been\n");
printf("written into 'rsua_sample'.\n");
}
//**/ first set of statistics
double mean=0, stdev=0;
for (ss = 0; ss < uaNSams; ss++) mean += vecUAOuts[ss];
mean /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
stdev += pow(vecUAOuts[ss] - mean, 2.0);
stdev = sqrt(stdev/(double) uaNSams);
printAsterisks(PL_INFO, 0);
printf("Sample mean = %e (RS uncertainties not included)\n",
mean);
printf("Sample std dev = %e (RS uncertainties not included)\n",
stdev);
printEquals(PL_INFO, 0);
//**/ initialize for binning
int nbins = 100, ntimes=20;
int **Fcounts = new int*[ntimes+1];
double Fmax=-PSUADE_UNDEFINED, Fmin=PSUADE_UNDEFINED;
for (ss = 0; ss < uaNSams; ss++)
{
if (vecUAOuts[ss]+3*vecUAStds[ss] > Fmax)
Fmax = vecUAOuts[ss] + 3 * vecUAStds[ss];
if (vecUAOuts[ss]-3*vecUAStds[ss] < Fmin)
Fmin = vecUAOuts[ss] - 3 * vecUAStds[ss];
}
Fmax = Fmax + 0.1 * (Fmax - Fmin);
Fmin = Fmin - 0.1 * (Fmax - Fmin);
if (Fmax == Fmin)
{
Fmax = Fmax + 0.1 * PABS(Fmax);
Fmin = Fmin - 0.1 * PABS(Fmin);
}
for (ii = 0; ii <= ntimes; ii++)
{
Fcounts[ii] = new int[nbins];
for (kk = 0; kk < nbins; kk++) Fcounts[ii][kk] = 0;
}
//**/ generate stochastic RS and bin
psVector vecSamOutTime, vecSamOutSave;
vecSamOutTime.setLength(ntimes*nInputs);
vecSamOutSave.setLength(ntimes*uaNSams);
for (ss = 0; ss < uaNSams; ss++)
{
if (vecUAStds[ss] == 0)
{
for (ii = 0; ii < ntimes; ii++)
vecSamOutTime[ii] = vecUAOuts[ss];
}
else
{
ddata = 2.0 * vecUAStds[ss] / (ntimes - 1);
for (ii = 0; ii < ntimes; ii++)
vecSamOutTime[ii] = vecUAOuts[ss]+ii*ddata-
vecUAStds[ss];
}
for (ii = 0; ii < ntimes; ii++)
vecSamOutSave[ss*ntimes+ii] = vecSamOutTime[ii];
//**/ bin the original sample
ddata = vecUAOuts[ss] - Fmin;
if (Fmax > Fmin) ddata = ddata / ((Fmax - Fmin) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ntimes][kk]++;
//**/ bin the perturbed sample
for (ii = 0; ii < ntimes; ii++)
{
ddata = vecSamOutTime[ii] - Fmin;
if (Fmax > Fmin)
ddata = ddata / ((Fmax - Fmin) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ii][kk]++;
}
}
double mean2=0, stdev2=0;
for (ss = 0; ss < uaNSams*ntimes; ss++)
mean2 += vecSamOutSave[ss];
mean2 /= (double) (uaNSams*ntimes);
stdev2 = 0.0;
for (ss = 0; ss < uaNSams*ntimes; ss++)
stdev2 += pow(vecSamOutSave[ss] - mean2, 2.0);
stdev2 = sqrt(stdev2/(double) (uaNSams*ntimes));
printf("Sample mean = %e (RS uncertainties included)\n",
mean2);
printf("Sample std dev = %e (RS uncertainties included)\n",
stdev2);
printAsterisks(PL_INFO, 0);
//**/ write to file
double dsum = 0.0;
for (ss = 0; ss < uaNSams; ss++) dsum += vecUAStds[ss];
if (plotMatlab()) fp = fopen("matlabrsua.m", "w");
else fp = fopen("scilabrsua.sci", "w");
if (fp == NULL)
{
printf("INFO: cannot write the PDFs/CDFs to matlab file.\n");
}
else
{
fwriteHold(fp, 0);
fprintf(fp, "X = [\n");
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%e\n",(Fmax-Fmin)/nbins*(0.5+kk)+Fmin);
fprintf(fp, "];\n");
for (ii = 0; ii <= ntimes; ii++)
{
fprintf(fp, "N%d = [\n", ii+1);
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%d\n", Fcounts[ii][kk]);
fprintf(fp, "];\n");
}
fprintf(fp, "N = [");
for (ii = 0; ii <= ntimes; ii++)
fprintf(fp, "N%d/sum(N%d) ", ii+1, ii+1);
fprintf(fp, "];\n");
fprintf(fp, "NA = N(:,%d+1);\n",ntimes);
fprintf(fp, "NA = NA / sum(NA);\n");
if (plotMatlab())
fprintf(fp, "NB = sum(N(:,1:%d)');\n",ntimes);
else fprintf(fp, "NB = sum(N(:,1:%d)',1);\n",ntimes);
fprintf(fp, "NB = NB' / sum(NB);\n");
fprintf(fp, "NN = [NA NB];\n");
fprintf(fp, "subplot(2,2,1)\n");
fprintf(fp, "bar(X,NA,1.0)\n");
fprintf(fp, "xmin = min(X);\n");
fprintf(fp, "xmax = max(X);\n");
fprintf(fp, "ymin = min(min(NA),min(NB));\n");
fprintf(fp, "ymax = max(max(NA),max(NB));\n");
fwritePlotScales2D(fp);
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (means of RS)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities)");
if (plotMatlab())
{
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",
mean);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev);
}
if (dsum == 0.0)
{
printf("Deterministic RS used ==> no RS uncertainties.\n");
fprintf(fp,"subplot(2,2,3)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp,"Prob. Dist. (RS with uncertainties)");
if (plotMatlab())
{
fprintf(fp,"text(0.01,0.5,'No RS uncertainty info.','sc',");
fprintf(fp,"'FontSize',11)\n");
fprintf(fp,"text(0.01,0.4,'Deterministic RS used.','sc',");
fprintf(fp,"'FontSize',11)\n");
}
}
else
{
fprintf(fp,"subplot(2,2,3)\n");
fprintf(fp,"bar(X,NB,1.0)\n");
fwritePlotScales2D(fp);
fwritePlotAxes(fp);
fwritePlotTitle(fp,"Prob. Dist. (RS with uncertainties)");
fwritePlotXLabel(fp,"Output Value");
fwritePlotYLabel(fp,"Probabilities");
if (plotMatlab())
{
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",
mean2);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev2);
}
}
for (ii = 0; ii <= ntimes; ii++)
{
fprintf(fp,"for ii = 2 : %d\n", nbins);
fprintf(fp," N%d(ii) = N%d(ii) + N%d(ii-1);\n",ii+1,ii+1,ii+1);
fprintf(fp,"end;\n");
}
fprintf(fp, "N = [");
for (ii = 0; ii <= ntimes; ii++)
fprintf(fp,"N%d/N%d(%d) ", ii+1, ii+1, nbins);
fprintf(fp, "];\n");
if (plotMatlab()) fprintf(fp, "subplot(2,2,[2 4])\n");
else fprintf(fp, "subplot(1,2,2)\n");
fprintf(fp, "NA = N(:,%d+1);\n",ntimes);
fprintf(fp, "NA = NA / NA(%d);\n",nbins);
if (plotMatlab())
fprintf(fp, "NB = sum(N(:,1:%d)');\n",ntimes);
else fprintf(fp, "NB = sum(N(:,1:%d)',1);\n",ntimes);
fprintf(fp, "NB = NB' / NB(%d);\n", nbins);
fprintf(fp, "NN = [NA NB];\n");
if (dsum == 0.0)
{
fprintf(fp, "plot(X,NA,'linewidth',3)\n");
fwritePlotTitle(fp,"Cum. Dist.: (b) mean; (g) with uncertainties");
}
else
{
fprintf(fp, "plot(X,NN,'linewidth',3)\n");
fwritePlotTitle(fp,"Cum. Dist.: (*) uncertainties unavailable");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
if (plotMatlab())
printf("Output distribution plots are in matlabrsua.m.\n");
else
printf("Output distribution plots are in scilabrsua.sci.\n");
}
for (ii = 0; ii <= ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
}
//**/ ----------------------------------------------
// stochastic RS with worst case analysis
//**/ ----------------------------------------------
else if (uaMethod == 1)
{
//**/ create response surface
printf("** CREATING RESPONSE SURFACE\n");
faPtrUA = genFA(-1, nInputs, -1, nSamples);
if (faPtrUA == NULL)
{
printf("ERROR: cannot generate response surface.\n");
return 1;
}
faPtrUA->setBounds(iLowerB, iUpperB);
faPtrUA->setOutputLevel(0);
psVector vecYOut;
vecYOut.setLength(nSamples);
for (ss = 0; ss < nSamples; ss++)
vecYOut[ss] = sampleOutputs[ss*nOutputs+outputID];
status = faPtrUA->initialize(sampleInputs,vecYOut.getDVector());
if (status != 0)
{
printf("ERROR: cannot initialize response surface.\n");
if (faPtrUA != NULL) delete faPtrUA;
return 1;
}
//**/ create response surface
faPtrUA->evaluatePointFuzzy(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector(),vecUAStds.getDVector());
//**/ first set of statistics
double mean=0, stdev=0;
for (ss = 0; ss < uaNSams; ss++) mean += vecUAOuts[ss];
mean /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
stdev += pow(vecUAOuts[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) uaNSams);
printAsterisks(PL_INFO, 0);
printf("Sample mean = %e (RS uncertainties not included)\n",
mean);
printf("Sample std dev = %e (RS uncertainties not included)\n",
stdev);
printEquals(PL_INFO, 0);
fp = fopen("rsua_sample","w");
fprintf(fp,"%% This file is primarily for diagnostics and \n");
fprintf(fp,"%% expert analysis\n");
fprintf(fp,"%% First line: nSamples nInputs\n");
fprintf(fp,"%% All inputs, output(Y), Y-3*sigma, Y+3*sigma\n");
fprintf(fp,"%d %d 3\n", uaNSams, nInputs);
for (ss = 0; ss < uaNSams; ss++)
{
for (ii = 0; ii < nInputs; ii++)
fprintf(fp, "%e ", vecUAInps[ss*nInputs+ii]);
fprintf(fp,"%e ", vecUAOuts[ss]);
fprintf(fp,"%e ", vecUAOuts[ss]-3*vecUAStds[ss]);
fprintf(fp,"%e\n", vecUAOuts[ss]+3*vecUAStds[ss]);
}
fclose(fp);
printf("The outputs and std deviations of the evaluation ");
printf("sample has been\n");
printf("written into 'rsua_sample'.\n");
//**/ initialize for binning
int nbins = 100, ntimes=7;
int **Fcounts = new int*[ntimes+1];
double Fmax=-PSUADE_UNDEFINED;
double Fmin=PSUADE_UNDEFINED;
PDFNormal *rsPDF=NULL;
for (ss = 0; ss < uaNSams; ss++)
{
if (vecUAOuts[ss]+3*vecUAStds[ss] > Fmax)
Fmax = vecUAOuts[ss] + 3 * vecUAStds[ss];
if (vecUAOuts[ss]-3*vecUAStds[ss] < Fmin)
Fmin = vecUAOuts[ss] - 3 * vecUAStds[ss];
}
Fmax = Fmax + 0.1 * (Fmax - Fmin);
Fmin = Fmin - 0.1 * (Fmax - Fmin);
if (Fmax == Fmin)
{
Fmax = Fmax + 0.1 * PABS(Fmax);
Fmin = Fmin - 0.1 * PABS(Fmin);
}
for (ii = 0; ii <= ntimes; ii++)
{
Fcounts[ii] = new int[nbins];
for (kk = 0; kk < nbins; kk++) Fcounts[ii][kk] = 0;
}
//**/ binning
double dsum = 0.0;
for (ss = 0; ss < uaNSams; ss++)
{
for (ii = 0; ii < ntimes; ii++)
{
ddata = vecUAOuts[ss]+vecUAStds[ss]*(ii-3) - Fmin;
if (Fmax > Fmin)
ddata = ddata / ((Fmax - Fmin) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ii][kk]++;
}
dsum += vecUAStds[ss];
}
if (plotMatlab()) fp = fopen("matlabrsua.m", "w");
else fp = fopen("scilabrsua.sci", "w");
if (fp == NULL)
{
printf("INFO: cannot write the PDFs/CDFs to matlab/scilab file.\n");
}
else
{
fwriteHold(fp, 0);
strcpy(pString, "worst case analysis\n");
fwriteComment(fp, pString);
fprintf(fp, "X = [\n");
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%e\n", (Fmax-Fmin)/nbins*(0.5+kk)+Fmin);
fprintf(fp, "];\n");
for (ii = 0; ii < ntimes; ii++)
{
fprintf(fp, "E%d = [\n", ii+1);
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%d\n", Fcounts[ii][kk]);
fprintf(fp, "];\n");
}
fprintf(fp, "EE = [");
for (ii = 0; ii < ntimes; ii++)
fprintf(fp, "E%d/sum(E%d) ", ii+1, ii+1);
fprintf(fp, "];\n");
fprintf(fp, "subplot(2,2,1)\n");
fprintf(fp, "bar(X,EE(:,4),1.0)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (means of RS)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities)");
if (plotMatlab())
{
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",
mean);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev);
}
fprintf(fp,"xmin = min(X);\n");
fprintf(fp,"xmax = max(X);\n");
fprintf(fp,"ymin = min(min(EE));\n");
fprintf(fp,"ymax = max(max(EE));\n");
fwritePlotScales2D(fp);
if (dsum == 0.0)
{
printf("Deterministic RS used ==> no RS uncertainties.\n");
fprintf(fp,"subplot(2,2,3)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp,"Prob. Dist. (RS with uncertainties)");
if (plotMatlab())
{
fprintf(fp,"text(0.01,0.5,'No RS uncertainty info.','sc',");
fprintf(fp,"'FontSize',11)\n");
fprintf(fp,"text(0.01,0.4,'Deterministic RS used.','sc',");
fprintf(fp,"'FontSize',11)\n");
}
}
else
{
fprintf(fp,"subplot(2,2,3)\n");
fprintf(fp,"plot(X,EE,'lineWidth',2)\n");
fwritePlotScales2D(fp);
fwritePlotAxes(fp);
fwritePlotTitle(fp,"Prob. Dist. (-3,2,1,0,1,2,3 std.)");
fwritePlotXLabel(fp,"Output Value");
fwritePlotYLabel(fp,"Probabilities");
}
if (plotMatlab()) fprintf(fp, "subplot(2,2,[2 4])\n");
else fprintf(fp, "subplot(1,2,2)\n");
for (ii = 0; ii < ntimes; ii++)
{
fprintf(fp,"for ii = 2 : %d\n", nbins);
fprintf(fp," E%d(ii) = E%d(ii) + E%d(ii-1);\n",ii+1,ii+1,ii+1);
fprintf(fp,"end;\n");
}
fprintf(fp, "EE = [");
for (ii = 0; ii < ntimes; ii++)
fprintf(fp, "E%d/E%d(%d) ", ii+1, ii+1, nbins);
fprintf(fp, "];\n");
fprintf(fp, "plot(X,EE,'linewidth',2)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Cum. Dist. (-3,2,1,0,1,2,3 std.)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
if (plotMatlab())
printf("Output distribution plots is now in matlabrsua.m\n");
else
printf("Output distribution plots is now in scilabrsua.sci\n");
for (ii = 0; ii < ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
}
}
if (faPtrUA != NULL) delete faPtrUA;
psConfig_.InteractiveRestore();
}
//**/ -------------------------------------------------------------
// +++ rsuab
//**/ RS-based UA with bootstrap and can be with posterior
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsuab"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsuab: uncertainty analysis on bootstrapped RS\n");
printf("Syntax: rsuab (no argument needed)\n");
printf("This command perform uncertainty analysis on the ");
printf("RS built from the\n");
printf("loaded sample. It is similar to the rsua command, ");
printf("except that the RS\n");
printf("uncertainties in this case is induced by bootstrapping ");
printf("rather than\n");
printf("predicted by the RS itself.\n");
return 0;
}
printAsterisks(PL_INFO, 0);
printf("* Response surface-based Uncertainty Analysis (with bootstrap)\n");
printDashes(PL_INFO, 0);
printf("It is similar to 'rsua' except that the RS uncertainties ");
printf("in this case\n");
printf("is induced by bootstrapping rather than predicted");
printf("by the RS.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
//**/ query user for output ID
sscanf(lineIn,"%s %s", command, winput);
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ request or generate a sample for evaluation
printf("A sample is needed from you to propagate through the RS.\n");
printf("Select between the two options below: \n");
printf("1. PSUADE will generate the sample\n");
printf("2. User will provide the sample (in PSUADE data format)\n");
sprintf(pString, "Enter 1 or 2 : ");
int samSrc = getInt(1, 2, pString);
//**/ generate a sample or get from user a sample for evaluation
//**/ ==> usNSams, vecUAInps
int uaNSams;
psVector vecUAInps, vecUAOuts;
psIVector vecUAStas;
if (samSrc == 1)
{
printf("PSUADE will generate a sample for uncertainty analysis.\n");
sprintf(pString, "Sample size ? (10000 - 100000) ");
uaNSams = getInt(10000, 100000, pString);
vecUAInps.setLength(uaNSams * nInputs);
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
int usePDFs = pPtr.intData_;
if (usePDFs == 1)
{
printf("NOTE: Some inputs have non-uniform PDFs.\n");
printf(" A MC sample will be created with these PDFs.\n");
psuadeIO->getParameter("method_sampling", pPtr);
kk = pPtr.intData_;
psuadeIO->updateMethodSection(PSUADE_SAMP_MC,-1,-1,-1,-1);
PDFManager *pdfman = new PDFManager();
pdfman->initialize(psuadeIO);
vecUAInps.setLength(uaNSams*nInputs);
psVector vecLs, vecUs;
vecUs.load(nInputs, iUpperB);
vecLs.load(nInputs, iLowerB);
pdfman->genSample(uaNSams, vecUAInps, vecLs, vecUs);
psuadeIO->updateMethodSection(kk,-1,-1,-1,-1);
delete pdfman;
}
else
{
printAsterisks(PL_INFO, 0);
printf("NOTE: Uniform distribution is assumed for all inputs. ");
printf("To use other\n");
printf(" than uniform distributions, prescribe them in ");
printf("the sample file\n");
printf(" and set use_input_pdfs in the ANALYSIS section.\n");
printAsterisks(PL_INFO, 0);
Sampling *samPtr;
if (nInputs < 51)
samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LPTAU);
else samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LHS);
samPtr->setPrintLevel(0);
samPtr->setInputBounds(nInputs, iLowerB, iUpperB);
samPtr->setOutputParams(1);
samPtr->setSamplingParams(uaNSams, -1, -1);
samPtr->initialize(0);
vecUAOuts.setLength(uaNSams);
vecUAStas.setLength(uaNSams);
samPtr->getSamples(uaNSams,nInputs,1,vecUAInps.getDVector(),
vecUAOuts.getDVector(),vecUAStas.getIVector());
delete samPtr;
}
}
else
{
printf("Enter UA sample file name (in PSUADE data format): ");
char uaFileName[1001];
scanf("%s", uaFileName);
fgets(lineIn2, 500, stdin);
PsuadeData *sampleIO = new PsuadeData();
status = sampleIO->readPsuadeFile(uaFileName);
if (status != 0)
{
printf("ERROR: cannot read sample file.\n");
delete sampleIO;
return 1;
}
sampleIO->getParameter("input_ninputs", pPtr);
kk = pPtr.intData_;
if (kk != nInputs)
{
printf("ERROR: sample nInputs mismatch.\n");
printf(": input size in workspace = %d.\n",nInputs);
printf(": input size from your sample = %d.\n",kk);
delete sampleIO;
return 1;
}
sampleIO->getParameter("method_nsamples", pPtr);
uaNSams = pPtr.intData_;
if (uaNSams < 1000)
{
printf("ERROR: Your sample size should be at least 1000 to give\n");
printf(" any reasonable UA results.\n");
delete sampleIO;
return 1;
}
sampleIO->getParameter("input_sample", pPtr);
vecUAInps.load(uaNSams * nInputs, pPtr.dbleArray_);
pPtr.clean();
delete sampleIO;
}
//**/ need information to get bootstrapped sample
sprintf(pString,
"How many bootstraps to create from the loaded sample (10 - 300) : ");
int numBS = getInt(10, 300, pString);
double bsPC=0;
if (psConfig_.MasterModeIsOn())
{
printf("Bootstrapped samples will be created from randomly\n");
printf("drawing from your RS sample. Normally a random draw\n");
printf("may include around 60%% of the original sample. You\n");
printf("may increase this percentage below.\n");
kk = 0;
while ((bsPC < 60 || bsPC > 90) && kk < 10)
{
printf("Enter percentage (60-90) : ");
scanf("%lg", &bsPC);
kk++;
}
if (bsPC < 60 || bsPC > 90 || kk >= 10) bsPC = 0;
else bsPC *= 0.01;
}
//**/ ===========================================================
//**/ perform UA
//**/ ===========================================================
vecUAOuts.setLength(uaNSams);
//**/ ----------------------------------------------
// bootstrapped method
//**/ ----------------------------------------------
//**/ create response surface place holder
printf("** CREATING RESPONSE SURFACE\n");
FuncApprox *faPtrUAB = genFA(-1, nInputs, -1, nSamples);
if (faPtrUAB == NULL)
{
printf("ERROR: cannot generate response surface.\n");
return 1;
}
int rsMethod = faPtrUAB->getID();
delete faPtrUAB;
faPtrUAB = NULL;
//**/ for each bootstrap, initialize and evaluate response surface
int its;
psVector vecBsSamInps, vecBsSamOuts, vecBsMeans, vecBsStds;
vecBsSamInps.setLength(nSamples*nInputs);
vecBsSamOuts.setLength(nSamples);
vecBsMeans.setLength(numBS);
vecBsStds.setLength(numBS);
psIVector vecUseFlags;
vecUseFlags.setLength(nSamples);
if (plotMatlab()) fp = fopen("matlabrsuab.m", "w");
else fp = fopen("scilabrsuab.sci", "w");
psConfig_.InteractiveSaveAndReset();
for (its = 0; its < numBS; its++)
{
for (ss = 0; ss < nSamples; ss++) vecUseFlags[ss] = 0;
//**/ generate bootstrapped sample
int bsnSams = 0;
kk = 0;
while (kk < nSamples || (1.0*bsnSams/nSamples) < bsPC)
{
jj = PSUADE_rand() % nSamples;
if (vecUseFlags[jj] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecBsSamInps[bsnSams*nInputs+ii] = sampleInputs[jj*nInputs+ii];
vecBsSamOuts[bsnSams] = sampleOutputs[jj*nOutputs+outputID];
vecUseFlags[jj] = 1;
bsnSams++;
}
kk++;
}
printf("Bootstrap %d has sample size = %d (drawn from %d)\n",its+1,
bsnSams,nSamples);
//**/ initialize response surface
faPtrUAB = genFA(rsMethod, nInputs, -1, bsnSams);
faPtrUAB->setBounds(iLowerB, iUpperB);
faPtrUAB->setOutputLevel(0);
status = faPtrUAB->initialize(vecBsSamInps.getDVector(),
vecBsSamOuts.getDVector());
if (status != 0)
{
printf("ERROR: in initializing response surface (1).\n");
if (faPtrUAB != NULL) delete faPtrUAB;
return 1;
}
//**/ evaluate the user sample
faPtrUAB->evaluatePoint(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector());
delete faPtrUAB;
//**/ compute statistics
vecBsMeans[its] = vecBsStds[its] = 0.0;
for (ss = 0; ss < uaNSams; ss++)
vecBsMeans[its] += vecUAOuts[ss];
vecBsMeans[its] /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
vecBsStds[its] += pow(vecUAOuts[ss] - vecBsMeans[its], 2.0);
vecBsStds[its] = sqrt(vecBsStds[its] / uaNSams);
if (fp != NULL)
{
fprintf(fp, "Y = [\n");
for (ss = 0; ss < uaNSams; ss++)
fprintf(fp,"%e\n",vecUAOuts[ss]);
fprintf(fp, "];\n");
fprintf(fp, "Y%d = sort(Y);\n",its+1);
fprintf(fp, "X%d = (1 : %d)';\n", its+1, uaNSams);
fprintf(fp, "X%d = X%d / %d;\n", its+1, its+1, uaNSams);
if (its == 0)
{
fprintf(fp, "YY = Y%d;\n", its+1);
fprintf(fp, "XX = X%d;\n", its+1);
}
else
{
fprintf(fp, "YY = [YY Y%d];\n", its+1);
fprintf(fp, "XX = [XX X%d];\n", its+1);
}
}
}
//**/ RS means
faPtrUAB = genFA(rsMethod, nInputs, -1, nSamples);
faPtrUAB->setBounds(iLowerB, iUpperB);
faPtrUAB->setOutputLevel(0);
for (ss = 0; ss < nSamples; ss++)
vecBsSamOuts[ss] = sampleOutputs[ss*nOutputs+outputID];
status = faPtrUAB->initialize(sampleInputs,
vecBsSamOuts.getDVector());
faPtrUAB->evaluatePoint(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector());
delete faPtrUAB;
psConfig_.InteractiveRestore();
//**/ compute statistics
printAsterisks(PL_INFO, 0);
double mean, stdev;
mean = stdev = 0.0;
for (its = 0; its < numBS; its++) mean += vecBsMeans[its];
mean /= (double) numBS;
for (ss = 0; ss < numBS; ss++) stdev += pow(vecBsMeans[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) numBS);
printf("Sample mean = %e (std = %e)\n", mean, stdev);
mean = stdev = 0.0;
for (its = 0; its < numBS; its++) mean += vecBsStds[its];
mean /= (double) numBS;
for (ss = 0; ss < numBS; ss++) stdev += pow(vecBsStds[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) numBS);
printf("Sample std dev = %e (std = %e)\n", mean, stdev);
printEquals(PL_INFO, 0);
if (fp != NULL)
{
fprintf(fp, "Y0 = [\n");
for (ss = 0; ss < uaNSams; ss++)
fprintf(fp,"%e\n",vecUAOuts[ss]);
fprintf(fp, "];\n");
fwriteHold(fp, 0);
fprintf(fp,"subplot(2,2,3);\n");
fprintf(fp,"YYY = reshape(YY,%d,1);\n",uaNSams*numBS);
fprintf(fp,"[nk,xk] = hist(YYY,50);\n");
fprintf(fp,"nk = nk / %d;\n",uaNSams);
fprintf(fp,"bar(xk,nk,1.0)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (RS with uncertainties)");
fwritePlotXLabel(fp,"Output Value");
fwritePlotYLabel(fp,"Probabilities");
fprintf(fp,"subplot(2,2,1);\n");
fprintf(fp,"[nk0,xk0] = hist(Y0,xk,50);\n");
fprintf(fp,"nk0 = nk0 / %d;\n",uaNSams);
fprintf(fp,"bar(xk0,nk0,1.0)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (Original Sample)");
fwritePlotXLabel(fp,"Output Value");
fwritePlotYLabel(fp,"Probabilities");
mean = stdev = 0.0;
for (ss = 0; ss < uaNSams; ss++) mean += vecUAOuts[ss];
mean /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
stdev += pow(vecUAOuts[ss] - mean, 2.0);
stdev = sqrt(stdev / uaNSams);
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",mean);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",stdev);
fprintf(fp,"subplot(2,2,[2 4]);\n");
fprintf(fp,"plot(YY, XX, 'b-', 'lineWidth',3)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Cumulative Distributions");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
printf("Output distribution plots has been created in matlabrsuab.m.\n");
}
}
//**/ -------------------------------------------------------------
// +++ rssobol1
//**/ Sobol main effect
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssobol1"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssobol1: compute RS-based Sobol' first-order indices\n");
printf("Syntax: rssobol1 (no argument needed)\n");
printf("NOTE: to compute error bars for indices, use rssobol1b\n");
return 1;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command computes first-order sensitivity ");
printf("indices using the\n");
printf("response surface constructed from the loaded sample.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
int analysisMethod = PSUADE_ANA_RSSOBOL1;
AnalysisManager *anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
psuadeIO->getParameter("ana_diagnostics",pPtr);
int saveDiag = pPtr.intData_;
psuadeIO->getParameter("ana_rstype", pPtr);
int saveRS = pPtr.intData_;
psuadeIO->updateAnalysisSection(-1,-1,faType,outputLevel,-1,-1);
anaManager->analyze(psuadeIO, 0, NULL, outputID);
psuadeIO->updateAnalysisSection(-1,-1,saveRS,saveDiag,-1,-1);
//**/ get the statistics
pData *pdata = psuadeIO->getAuxData();
if (pdata->nDbles_ >= nInputs)
{
if (pdata->dbleData_ > 0)
{
#if 0
printEquals(PL_INFO, 0);
printf("Main Effect Statistics: \n");
for (ii = 0; ii < nInputs; ii++)
{
printf("Input %4d: Sobol' main effect = %12.4e",
ii+1,pdata->dbleArray_[ii]);
if (pdata->nDbles_ == 3*nInputs)
printf(", bounds = [%12.4e, %12.4e]\n",
pdata->dbleArray_[ii+nInputs],
pdata->dbleArray_[ii+2*nInputs]);
else printf(" (unnormalized)\n");
}
#endif
if (plotScilab())
fp = fopen("scilabrssobol1.sci", "w");
else fp = fopen("matlabrssobol1.m", "w");
if (fp == NULL)
printf("rssobol1 ERROR: cannot open file to save data\n");
else
{
if (plotScilab())
{
fprintf(fp,"// This file contains Sobol' indices\n");
fprintf(fp,"// set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"// of inputs to display.\n");
}
else
{
fprintf(fp,"%% This file contains Sobol' indices\n");
fprintf(fp,"%% set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"%% of inputs to display.\n");
}
fprintf(fp, "sortFlag = 0;\n");
fprintf(fp, "nn = %d;\n", nInputs);
fprintf(fp, "Mids = [\n");
for (ii = 0; ii < nInputs; ii++)
fprintf(fp,"%24.16e\n", pdata->dbleArray_[ii]/pdata->dbleData_);
fprintf(fp, "];\n");
if (pdata->nDbles_ == 3*nInputs)
{
fprintf(fp, "Mins = [\n");
for (ii = 0; ii < nInputs; ii++)
fprintf(fp,"%24.16e\n",
pdata->dbleArray_[nInputs+ii]/pdata->dbleData_);
fprintf(fp, "];\n");
fprintf(fp, "Maxs = [\n");
for (ii = 0; ii < nInputs; ii++)
fprintf(fp,"%24.16e\n",
pdata->dbleArray_[2*nInputs+ii]/pdata->dbleData_);
fprintf(fp, "];\n");
}
if (inputNames == NULL)
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1);
if (plotScilab()) fprintf(fp,"'X%d'];\n",nInputs);
else fprintf(fp,"'X%d'};\n",nInputs);
}
else
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++)
{
if (inputNames[ii] != NULL)
fprintf(fp,"'%s',",inputNames[ii]);
else fprintf(fp,"'X%d',",ii+1);
}
if (plotScilab())
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'];\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'];\n",nInputs);
}
else
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'};\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'};\n",nInputs);
}
}
fwriteHold(fp, 0);
fprintf(fp, "if (sortFlag == 1)\n");
if (plotScilab())
fprintf(fp, " [Mids, I2] = gsort(Mids);\n");
else fprintf(fp, " [Mids, I2] = sort(Mids,'descend');\n");
if (pdata->nDbles_ == 3*nInputs)
{
fprintf(fp, " Maxs = Maxs(I2);\n");
fprintf(fp, " Mins = Mins(I2);\n");
}
fprintf(fp, " Str = Str(I2);\n");
fprintf(fp, " I2 = I2(1:nn);\n");
fprintf(fp, " Mids = Mids(1:nn);\n");
if (pdata->nDbles_ == 3*nInputs)
{
fprintf(fp, " Maxs = Maxs(1:nn);\n");
fprintf(fp, " Mins = Mins(1:nn);\n");
}
fprintf(fp, " Str = Str(1:nn);\n");
fprintf(fp, "end\n");
if (pdata->nDbles_ == 3*nInputs)
{
fprintf(fp, "ymin = min(Mins);\n");
fprintf(fp, "ymax = max(Maxs);\n");
}
else
{
fprintf(fp, "ymin = min(Mids);\n");
fprintf(fp, "ymax = max(Mids);\n");
}
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
if (plotScilab()) fprintf(fp, "drawlater\n");
fprintf(fp, "bar(Mids,0.8);\n");
if (pdata->nDbles_ == 3*nInputs)
{
fprintf(fp,"for ii = 1:nn\n");
if (plotScilab())
fprintf(fp,
"// h = plot(ii,Means(ii),'r*','MarkerSize',13);\n");
else
fprintf(fp,
"%% h = plot(ii,Means(ii),'r*','MarkerSize',13);\n");
fprintf(fp," if (ii == 1)\n");
fwriteHold(fp, 1);
fprintf(fp," end;\n");
fprintf(fp," XX = [ii ii];\n");
fprintf(fp," YY = [Mins(ii) Maxs(ii)];\n");
fprintf(fp,
" plot(XX,YY,'-ko','LineWidth',3.0,'MarkerEdgeColor',");
fprintf(fp,"'k','MarkerFaceColor','g','MarkerSize',13)\n");
fprintf(fp,"end;\n");
}
fwritePlotAxes(fp);
fprintf(fp,"ymin=0;\n");
if (plotScilab())
{
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, ymin; nn+1, ymax];\n");
fprintf(fp, "newtick = a.x_ticks;\n");
fprintf(fp, "newtick(2) = [1:nn]';\n");
fprintf(fp, "newtick(3) = Str';\n");
fprintf(fp, "a.x_ticks = newtick;\n");
fprintf(fp, "a.x_label.font_size = 3;\n");
fprintf(fp, "a.x_label.font_style = 4;\n");
}
else
{
fprintf(fp,"axis([0 nn+1 ymin ymax])\n");
fprintf(fp,"set(gca,'XTickLabel',[]);\n");
fprintf(fp,
"th=text(1:nn, repmat(ymin-0.07*(ymax-ymin),nn,1),Str,");
fprintf(fp,"'HorizontalAlignment','left','rotation',90);\n");
fprintf(fp,"set(th, 'fontsize', 12)\n");
fprintf(fp,"set(th, 'fontweight', 'bold')\n");
}
fwritePlotTitle(fp,"Sobol First Order Indices");
fwritePlotYLabel(fp, "Sobol Indices");
fwriteHold(fp, 0);
if (plotScilab())
{
fprintf(fp, "drawnow\n");
printf("rssobol1 plot file = scilabrssobol1.sci\n");
}
else printf("rssobol1 plot file = matlabrssobol1.m\n");
fclose(fp);
}
}
else
{
printf("Total variance = 0. Hence, no main effect plot.\n");
}
pdata->clean();
}
delete anaManager;
}
//**/ -------------------------------------------------------------
// +++ rssobol2
//**/ Sobol interaction effect
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssobol2"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssobol2: compute RS-based Sobol' second-order indices\n");
printf("Syntax: rssobol2 (no argument needed)\n");
printf("NOTE: to compute error bars for indices, use rssobol2b\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
if (nInputs <= 2)
{
printf("INFO: no point doing this for nInputs <= 2.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command computes input-pair sensitivity ");
printf("indices using the\n");
printf("response surface constructed from the loaded sample.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ get RS type from user
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
//**/ set up for analysis
int analysisMethod = PSUADE_ANA_RSSOBOL2;
AnalysisManager *anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
psuadeIO->getParameter("ana_diagnostics",pPtr);
int saveDiag = pPtr.intData_;
psuadeIO->getParameter("ana_rstype", pPtr);
int saveRS = pPtr.intData_;
psuadeIO->updateAnalysisSection(-1,-1,faType,outputLevel,-1,-1);
anaManager->analyze(psuadeIO, 0, NULL, outputID);
psuadeIO->updateAnalysisSection(-1,-1,saveRS,saveDiag,-1,-1);
//**/ get the statistics
pData *pdata = psuadeIO->getAuxData();
if (pdata->nDbles_ >= nInputs)
{
if (pdata->dbleData_ > 0)
{
#if 0
printEquals(PL_INFO, 0);
printf("Two-way Interaction Effect Statistics (variance = %e): \n",
pdata->dbleData_);
for (ii = 0; ii < nInputs; ii++)
{
for (jj = ii+1; jj < nInputs; jj++)
{
printf("Inputs %4d %4d: Sobol' interaction effect = ",
ii+1,jj+1);
printf("%12.4e (normalized)\n",
pdata->dbleArray_[ii*nInputs+jj]/pdata->dbleData_);
}
}
#endif
if (plotScilab())
{
fp = fopen("scilabrssobol2.sci", "w");
if (fp == NULL)
printf("ERROR : cannot open file scilabrssobol2.sci\n");
}
else
{
fp = fopen("matlabrssobol2.m", "w");
if (fp == NULL)
printf("ERROR : cannot open file matlabrssobol2.m\n");
}
if (fp != NULL)
{
strcpy(pString,"This file contains Sobol' 2nd order indices");
fwriteComment(fp, pString);
strcpy(pString,"set sortFlag = 1 and set nn to be the number");
fwriteComment(fp, pString);
strcpy(pString,"of inputs to display.");
fwriteComment(fp, pString);
fprintf(fp, "sortFlag = 0;\n");
fprintf(fp, "nn = %d;\n", nInputs);
fprintf(fp, "Mids = [\n");
for (ii = 0; ii < nInputs; ii++)
{
for (jj = 0; jj <= ii; jj++) fprintf(fp,"0.0\n");
for (jj = ii+1; jj < nInputs; jj++)
fprintf(fp,"%24.16e\n",
pdata->dbleArray_[ii*nInputs+jj]/pdata->dbleData_);
}
fprintf(fp, "];\n");
fprintf(fp, "Mids = Mids';\n");
if (inputNames == NULL)
{
if (plotScilab()) fprintf(fp, "Str = [");
else fprintf(fp, "Str = {");
for (ii = 0; ii < nInputs-1; ii++)
fprintf(fp,"'X%d',",ii+1);
if (plotScilab()) fprintf(fp,"'X%d'];\n",nInputs);
else fprintf(fp,"'X%d'};\n",nInputs);
}
else
{
if (plotScilab()) fprintf(fp, "Str = [");
else fprintf(fp, "Str = {");
for (ii = 0; ii < nInputs-1; ii++)
{
if (inputNames[ii] != NULL)
fprintf(fp,"'%s',",inputNames[ii]);
else fprintf(fp,"'X%d',",ii+1);
}
if (plotScilab())
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'];\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'];\n",nInputs);
}
else
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'};\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'};\n",nInputs);
}
}
fwriteHold(fp, 0);
fprintf(fp, "ymin = min(Mids);\n");
fprintf(fp, "ymax = max(Mids);\n");
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
if (plotScilab())
{
fprintf(fp, "Mids = matrix(Mids, %d, %d);\n",
nInputs,nInputs);
fprintf(fp, "Mids = Mids';\n");
fprintf(fp, "drawlater\n");
fprintf(fp, "hist3d(Mids);\n");
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, 0, 0; %d+1, %d+1, ymax];\n",
nInputs,nInputs);
fprintf(fp, "newtick = a.x_ticks;\n");
fprintf(fp, "newtick(2) = [1:%d]';\n",nInputs);
fprintf(fp, "newtick(3) = Str';\n");
fprintf(fp, "a.x_ticks = newtick;\n");
fprintf(fp, "a.x_label.font_size = 3;\n");
fprintf(fp, "a.x_label.font_style = 4;\n");
fprintf(fp, "a.y_ticks = newtick;\n");
fprintf(fp, "a.y_label.font_size = 3;\n");
fprintf(fp, "a.y_label.font_style = 4;\n");
fprintf(fp, "a.rotation_angles = [5 -70];\n");
fprintf(fp, "drawnow\n");
}
else
{
fprintf(fp, "Mids = reshape(Mids, %d, %d);\n",nInputs,nInputs);
fprintf(fp, "Mids = Mids';\n");
fprintf(fp, "ymin = min(min(Mids));\n");
fprintf(fp, "ymax = max(max(Mids));\n");
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
fprintf(fp, "hh = bar3(Mids,0.8);\n");
fprintf(fp, "alpha = 0.2;\n");
fprintf(fp, "set(hh,'FaceColor','b','facea',alpha);\n");
fprintf(fp, "axis([0.5 %d+0.5 0.5 %d+0.5 0 ymax])\n",
nInputs,nInputs);
//fprintf(fp, "bar3(Mids,0.8);\n");
//fprintf(fp, "axis([0 %d+1 0 %d+1 0 ymax])\n",nInputs,nInputs);
fprintf(fp, "set(gca,'XTickLabel',Str);\n");
fprintf(fp, "set(gca,'YTickLabel',Str);\n");
fwritePlotAxesNoGrid(fp);
}
fwritePlotAxes(fp);
fwritePlotTitle(fp,"Sobol Second Order Indices (+first order)");
fwritePlotZLabel(fp, "Sobol Indices");
fwritePlotXLabel(fp, "Inputs");
fwritePlotYLabel(fp, "Inputs");
fclose(fp);
if (plotScilab())
printf("rssobol2 plot file = scilabrssobol2.sci\n");
else printf("rssobol2 plot file = matlabrssobol2.m\n");
}
}
else
{
printf("Total variance = 0. Hence, no interaction effect plot.\n");
}
pdata->clean();
}
delete anaManager;
}
//**/ -------------------------------------------------------------
// +++ rssoboltsi
//**/ Sobol total sensitivity effect
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssoboltsi"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssoboltsi: compute RS-based Sobol' total-order indices\n");
printf("Syntax: rssoboltsi (no argument needed)\n");
printf("NOTE: to compute error bars for indices, use rssoboltsib\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
if (nInputs < 2)
{
printf("INFO: no point doing this for nInputs < 2.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command computes total-order sensitivity ");
printf("indices using the\n");
printf("response surface constructed from the loaded sample.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
int analysisMethod = PSUADE_ANA_RSSOBOLTSI;
AnalysisManager *anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
psuadeIO->getParameter("ana_diagnostics",pPtr);
int saveDiag = pPtr.intData_;
psuadeIO->getParameter("ana_rstype",pPtr);
int saveRS = pPtr.intData_;
psuadeIO->updateAnalysisSection(-1,-1,faType,outputLevel,-1,-1);
anaManager->analyze(psuadeIO, 0, NULL, outputID);
psuadeIO->updateAnalysisSection(-1,-1,saveRS,saveDiag,-1,-1);
delete anaManager;
}
//**/ -------------------------------------------------------------
// +++ rssobolg
//**/ Sobol group main effect
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssobolg"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssobolg: RS-based Sobol' group-order indices\n");
printf("Syntax: rssobolg (no argument needed)\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command computes group-order sensitivity ");
printf("indices using the\n");
printf("response surface constructed from the loaded sample.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
int analysisMethod = PSUADE_ANA_RSSOBOLG;
AnalysisManager *anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
psuadeIO->getParameter("ana_diagnostics",pPtr);
int saveDiag = pPtr.intData_;
psuadeIO->getParameter("ana_rstype",pPtr);
int saveRS = pPtr.intData_;
psuadeIO->updateAnalysisSection(-1,-1,faType,outputLevel,-1,-1);
anaManager->analyze(psuadeIO, 0, NULL, outputID);
psuadeIO->updateAnalysisSection(-1,-1,saveRS,saveDiag,-1,-1);
delete anaManager;
}
//**/ -------------------------------------------------------------
// +++ rssobol1b
//**/ rssobol1 with bootstrap
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssobol1b"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssobol1b: compute RS-based Sobol' first-order indices\n");
printf("Syntax: rssobol1b (no argument needed)\n");
printf("NOTE: This command computes the first-order ");
printf("Sobol' indices using\n");
printf(" response surface constructed from the ");
printf("loaded sample. It \n");
printf(" estimates prediction uncertainty using ");
printf("bootstrapping.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
if (nSamples < 5)
{
printf("INFO: This command is not suitable for small samples.\n");
printf(" nSamples needs to be at least 5.\n");
return 1;
}
//**/ print usage information
printAsterisks(PL_INFO, 0);
printf("This command computes first-order sensitivity ");
printf("indices using an\n");
printf("ensemble of response surfaces constructed from ");
printf("the loaded sample.\n");
printf("Evaluations from the ensemble response surfaces ");
printf("give error estimates\n");
printf("for the sensitivity indices.\n");
#ifndef PSUADE_OMP
printf("Advice: this command can be accelerated if you use OpenMP.\n");
#endif
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ get which output to analyze
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ get which response surface to use
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
#ifdef PSUADE_OMP
if (faType == PSUADE_RS_MARS || faType == PSUADE_RS_GP1 ||
faType >= PSUADE_RS_ACOSSO || faType == PSUADE_RS_SVM ||
faType == PSUADE_RS_TGP || faType == PSUADE_RS_KR)
{
printf("These RS does not work in OpenMP mode. Select another one.\n");
printf("- MARS and MARS-based RS\n");
printf("- Multi-domain RS\n");
printf("- GP1, TGP, SVM\n");
printf("- SVM\n");
printf("- Kriging (it uses Fortran optimizer)\n");
faType = -1;
}
if (faType == PSUADE_RS_REGRL)
printf("Legendre polynomial of order=2\n");
#endif
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
if (faType == PSUADE_RS_MARSB)
{
printf("rssobol1b INFO: MarsBagg response surface selected but\n");
printf(" it is redundant - use MARS instead.\n");
faType = PSUADE_RS_MARS;
}
//**/ set up for iterations
psVector vecTT;
sprintf(pString,
"How many bootstrapped samples to use (5 - 300) : ");
int numBS = getInt(5, 300, pString);
vecTT.setLength(numBS*nInputs);
//**/ need to turn off expert modes, so save them first
psConfig_.AnaExpertModeSaveAndReset();
psConfig_.RSExpertModeSaveAndReset();
psConfig_.InteractiveSaveAndReset();
//**/ set up analysis manager
int analysisMethod = PSUADE_ANA_RSSOBOL1;
printEquals(PL_INFO, 0);
//**/ set up for bootstrapping
int nSamples2, ind;
psVector vecXT, vecYT;
psIVector vecIT, vecST;
PsuadeData *psIO = NULL;
AnalysisManager *anaManager;
pData pNames, pIpdfs, pImeans, pIstds, pIcor;
//**/ iterate
#pragma omp parallel shared(vecTT,sampleInputs,sampleStates,sampleOutputs,psuadeIO) \
private(kk,jj,ss,ii,nSamples2,ind,vecXT,vecYT,vecST,vecIT,psIO,anaManager,pNames,pIpdfs,pImeans,pIstds,pIcor)
#pragma omp for
for (kk = 0; kk < numBS; kk++)
{
vecXT.setLength(nSamples*nInputs);
vecYT.setLength(nSamples);
vecST.setLength(nSamples);
vecIT.setLength(nSamples);
anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
psIO = new PsuadeData();
//**/ random draw
for (jj = 0; jj < nSamples; jj++) vecIT[jj] = 0;
ss = nSamples2 = 0;
while (ss < nSamples)
{
ind = PSUADE_rand() % nSamples;
if (vecIT[ind] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecXT[nSamples2*nInputs+ii] = sampleInputs[ind*nInputs+ii];
vecYT[nSamples2] = sampleOutputs[ind*nOutputs+outputID];
vecST[nSamples2] = sampleStates[ind];
vecIT[ind] = 1;
nSamples2++;
}
ss++;
}
printf("rssobol1b: bootstrap %d begins (sample size = %d)\n",
kk+1,nSamples2);
psuadeIO->getParameter("input_names", pNames);
psuadeIO->getParameter("input_pdfs", pIpdfs);
psuadeIO->getParameter("input_means", pImeans);
psuadeIO->getParameter("input_stdevs", pIstds);
psuadeIO->getParameter("input_cor_matrix", pIcor);
psIO->updateInputSection(nSamples2,nInputs,NULL,iLowerB,
iUpperB,vecXT.getDVector(),pNames.strArray_,
pIpdfs.intArray_,pImeans.dbleArray_,pIstds.dbleArray_,
(psMatrix *) pIcor.psObject_);
psIO->updateOutputSection(nSamples2,1,vecYT.getDVector(),
vecST.getIVector(),&(outputNames[outputID]));
psIO->updateMethodSection(PSUADE_SAMP_MC,nSamples2,-1,-1,-1);
psIO->updateAnalysisSection(-1,-1,faType,-3,-1,-1);
//**/ analyze the result
anaManager->analyze(psIO, 0, NULL, 0);
//**/ get the statistics
pData *pdata = psIO->getAuxData();
if (pdata->dbleData_ > 0)
{
for (ii = 0; ii < nInputs; ii++)
vecTT[kk*nInputs+ii] =
pdata->dbleArray_[ii]/pdata->dbleData_;
}
else
{
for (ii = 0; ii < nInputs; ii++)
vecTT[kk*nInputs+ii] = pdata->dbleArray_[ii];
}
//**/ clean up
pdata->clean();
delete anaManager;
delete psIO;
}
//**/ postprocessing
psVector vecMT;
vecMT.setLength(nInputs);
for (ii = 0; ii < nInputs; ii++)
{
vecMT[ii] = vecTT[ii];
for (jj = 1; jj < numBS; jj++) vecMT[ii] += vecTT[jj*nInputs+ii];
vecMT[ii] /= (double) numBS;
}
psVector vecVT;
vecVT.setLength(nInputs);
for (ii = 0; ii < nInputs; ii++)
{
vecVT[ii] = pow(vecTT[ii]-vecMT[ii], 2.0);
for (jj = 1; jj < numBS; jj++)
vecVT[ii] += pow(vecTT[jj*nInputs+ii]-vecMT[ii],2.0);
vecVT[ii] /= (double) (numBS - 1);
vecVT[ii] = sqrt(vecVT[ii]);
}
printAsterisks(PL_INFO, 0);
printf("RSSobol1 Statistics (based on %d replications): \n",numBS);
printf("Quantities are normalized.\n");
printEquals(PL_INFO, 0);
for (ii = 0; ii < nInputs; ii++)
printf("RSSobol1 Input %4d: mean = %10.3e, std = %10.3e\n",ii+1,
vecMT[ii],vecVT[ii]);
printAsterisks(PL_INFO, 0);
//**/ generate matlab/scilab file
if (plotScilab()) fp = fopen("scilabrssobol1b.sci","w");
else fp = fopen("matlabrssobol1b.m","w");
if (fp == NULL) printf("ERROR: cannot open plot file.\n");
else
{
strcpy(pString," This file contains first order Sobol' indices");
fwriteComment(fp, pString);
strcpy(pString," with error bars coming from bootstrapping.");
fwriteComment(fp, pString);
strcpy(pString," to select the most important ones to display,");
fwriteComment(fp, pString);
strcpy(pString," set sortFlag = 1 and set nn to be the number");
fwriteComment(fp, pString);
strcpy(pString," of inputs to display.\n");
fwriteComment(fp, pString);
fprintf(fp, "sortFlag = 0;\n");
fprintf(fp, "nn = %d;\n", nInputs);
fprintf(fp, "Means = [\n");
for (ii = 0; ii < nInputs; ii++) fprintf(fp,"%24.16e\n",vecMT[ii]);
fprintf(fp, "];\n");
fprintf(fp, "Stds = [\n");
for (ii = 0; ii < nInputs; ii++) fprintf(fp,"%24.16e\n",vecVT[ii]);
fprintf(fp, "];\n");
if (inputNames == NULL)
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1);
if (plotScilab()) fprintf(fp,"'X%d'];\n",nInputs);
else fprintf(fp,"'X%d'};\n",nInputs);
}
else
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++)
{
if (inputNames[ii] != NULL)
fprintf(fp,"'%s',",inputNames[ii]);
else fprintf(fp,"'X%d',",ii+1);
}
if (plotScilab())
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'];\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'];\n",nInputs);
}
else
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'};\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'};\n",nInputs);
}
}
fwriteHold(fp, 0);
fprintf(fp, "if (sortFlag == 1)\n");
if (plotScilab())
fprintf(fp, " [Means, I2] = gsort(Means);\n");
else fprintf(fp, " [Means, I2] = sort(Means,'descend');\n");
fprintf(fp, " Stds = Stds(I2);\n");
fprintf(fp, " I2 = I2(1:nn);\n");
fprintf(fp, " Means = Means(1:nn);\n");
fprintf(fp, " Stds = Stds(1:nn);\n");
fprintf(fp, " Str = Str(I2);\n");
fprintf(fp, "end\n");
fprintf(fp, "ymin = min(Means-Stds);\n");
fprintf(fp, "if ymin < 0 \n");
fprintf(fp, " ymin = 0;\n");
fprintf(fp, "end;\n");
fprintf(fp, "ymax = max(Means+Stds);\n");
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
if (plotScilab()) fprintf(fp, "drawlater\n");
fprintf(fp, "bar(Means,0.8);\n");
fprintf(fp, "for ii = 1:nn\n");
fprintf(fp, " if (ii == 1)\n");
fwriteHold(fp, 1);
fprintf(fp, " end;\n");
fprintf(fp, " XX = [ii ii];\n");
fprintf(fp, " d1 = Means(ii)-Stds(ii);\n");
fprintf(fp, " d2 = Means(ii)+Stds(ii);\n");
fprintf(fp, " if (d1 < 0)\n");
fprintf(fp, " d1 = 0.0;\n");
fprintf(fp, " end;\n");
fprintf(fp, " YY = [d1 d2];\n");
fprintf(fp, " plot(XX,YY,'-ko','LineWidth',3.0,'MarkerEdgeColor',");
fprintf(fp, "'k','MarkerFaceColor','g','MarkerSize',13)\n");
fprintf(fp, "end;\n");
fwritePlotAxes(fp);
if (plotScilab())
{
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, ymin; nn+1, ymax];\n");
fprintf(fp, "newtick = a.x_ticks;\n");
fprintf(fp, "newtick(2) = [1:nn]';\n");
fprintf(fp, "newtick(3) = Str';\n");
fprintf(fp, "a.x_ticks = newtick;\n");
fprintf(fp, "a.x_label.font_size = 3;\n");
fprintf(fp, "a.x_label.font_style = 4;\n");
}
else
{
fprintf(fp,"axis([0 nn+1 ymin ymax])\n");
fprintf(fp,"set(gca,'XTickLabel',[]);\n");
fprintf(fp,"th=text(1:nn, repmat(ymin-0.05*(ymax-ymin),nn,1),Str,");
fprintf(fp,"'HorizontalAlignment','left','rotation',90);\n");
fprintf(fp,"set(th, 'fontsize', 12)\n");
fprintf(fp,"set(th, 'fontweight', 'bold')\n");
}
fwritePlotTitle(fp,"First Order Sobol Indices (with bootstrap)");
fwritePlotYLabel(fp, "First Order Sobol Index (Normalized)");
if (plotScilab())
{
fprintf(fp, "drawnow\n");
printf("rssobol1b plot file = scilabrssobol1b.sci\n");
}
else printf("rssobol1b plot file = matlabrssobol1b.m\n");
fclose(fp);
}
//**/ restore previous settings
psConfig_.AnaExpertModeRestore();
psConfig_.RSExpertModeRestore();
psConfig_.InteractiveRestore();
}
//**/ -------------------------------------------------------------
// +++ rssobol2b
//**/ rssobol2 with bootstrap
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssobol2b"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssobol2b: compute RS-based Sobol' second-order indices\n");
printf("Syntax: rssobol2b (no argument needed)\n");
printf("NOTE: This command computes the second-order ");
printf("Sobol' indices using\n");
printf(" response surface constructed from the ");
printf("loaded sample. It \n");
printf(" estimates prediction uncertainty using ");
printf("bootstrapping.\n");
return 0;
}
if (nInputs <= 0 || psuadeIO == NULL)
{
printf("ERROR: data file not loaded.\n");
return 1;
}
if (nInputs <= 2)
{
printf("INFO: no point doing this for nInputs <= 2.\n");
return 1;
}
if (nSamples < (nInputs+1)*5/3+1)
{
printf("INFO: This command is not suitable for small samples.\n");
printf(" nSamples needs to be at least %d.\n",(nInputs+1)/3+1);
printf(" nSamples needs to be at least %d.\n",(nInputs+1)/3+1);
return 1;
}
//**/ print usage information
printAsterisks(PL_INFO, 0);
printf("This command computes input-pair sensitivity ");
printf("indices using an\n");
printf("ensemble of response surfaces constructed from ");
printf("the loaded sample.\n");
printf("Evaluations from the ensemble response surfaces ");
printf("give error estimates\n");
printf("for the sensitivity indices.\n");
#ifndef PSUADE_OMP
printf("Advice: this command can be accelerated if you use OpenMP.\n");
#endif
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ get output
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ get which response surface to use
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
#ifdef PSUADE_OMP
if (faType == PSUADE_RS_MARS || faType == PSUADE_RS_GP1 ||
faType >= PSUADE_RS_ACOSSO || faType == PSUADE_RS_SVM ||
faType == PSUADE_RS_TGP || faType == PSUADE_RS_KR)
{
printf("These RS does not work in OpenMP mode. Select another one.\n");
printf("- MARS and MARS-based RS\n");
printf("- Multi-domain RS\n");
printf("- GP1, TGP, SVM\n");
printf("- SVM\n");
printf("- Kriging (it uses Fortran optimizer)\n");
faType = -1;
}
if (faType == PSUADE_RS_REGRL)
printf("Legendre polynomial of order=2\n");
#endif
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
if (faType == PSUADE_RS_MARSB)
{
printf("rssobol2b INFO: MarsBagg response surface selected but\n");
printf(" it is redundant - use MARS instead.\n");
faType = PSUADE_RS_MARS;
}
//**/ set up for iterations
sprintf(pString, "How many bootstrapped samples to use (5 - 300) : ");
int numBS = getInt(5, 300, pString);
//**/ need to turn off expert modes, so save them first
psConfig_.AnaExpertModeSaveAndReset();
psConfig_.RSExpertModeSaveAndReset();
psConfig_.InteractiveSaveAndReset();
//**/ set up analysis manager
int analysisMethod = PSUADE_ANA_RSSOBOL2;
printEquals(PL_INFO, 0);
//**/ set up storage for the response surface samples
int ind, nSamples2;
psVector vecXT, vecYT, vecTT;
psIVector vecIT, vecST;
PsuadeData *psIO=NULL;
vecTT.setLength((numBS+3)*nInputs*nInputs);
AnalysisManager *anaManager;
pData pNames, pIpdfs, pImeans, pIstds, pIcor;
//**/ iterate
#pragma omp parallel shared(vecTT,sampleInputs,sampleStates,sampleOutputs,psuadeIO) \
private(kk,jj,ss,ii,nSamples2,ind,vecXT,vecYT,vecST,vecIT,psIO,anaManager,pNames,pIpdfs,pImeans,pIstds,pIcor)
#pragma omp for
for (kk = 0; kk < numBS; kk++)
{
vecXT.setLength(nSamples*nInputs);
vecYT.setLength(nSamples);
vecIT.setLength(nSamples);
vecST.setLength(nSamples);
anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
psIO = new PsuadeData();
//**/ random draw
for (jj = 0; jj < nSamples; jj++) vecIT[jj] = 0;
ss = nSamples2 = 0;
while (ss < nSamples)
{
ind = PSUADE_rand() % nSamples;
if (vecIT[ind] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecXT[nSamples2*nInputs+ii] = sampleInputs[ind*nInputs+ii];
vecYT[nSamples2] = sampleOutputs[ind*nOutputs+outputID];
vecST[nSamples2] = sampleStates[ind];
vecIT[ind] = 1;
nSamples2++;
}
ss++;
}
printf("rssobol2b: bootstrap %d begins (sample size = %d)\n",
kk+1,nSamples2);
psuadeIO->getParameter("input_names", pNames);
psuadeIO->getParameter("input_pdfs", pIpdfs);
psuadeIO->getParameter("input_means", pImeans);
psuadeIO->getParameter("input_stdevs", pIstds);
psuadeIO->getParameter("input_cor_matrix", pIcor);
psIO->updateInputSection(nSamples2,nInputs,NULL,iLowerB,iUpperB,
vecXT.getDVector(),pNames.strArray_,pIpdfs.intArray_,
pImeans.dbleArray_,pIstds.dbleArray_,
(psMatrix *) pIcor.psObject_);
psIO->updateOutputSection(nSamples2,1,vecYT.getDVector(),
vecST.getIVector(),&(outputNames[outputID]));
psIO->updateMethodSection(PSUADE_SAMP_MC,nSamples2,-1,-1,-1);
psIO->updateAnalysisSection(-1,-1,faType,-3,-1,-1);
//**/ analyze
status = anaManager->analyze(psIO, 0, NULL, 0);
//**/ get statistics
pData *pdata = psIO->getAuxData();
if (pdata->dbleData_ > 0)
{
for (ii = 0; ii < nInputs*nInputs; ii++)
vecTT[kk*nInputs*nInputs+ii] =
pdata->dbleArray_[ii]/pdata->dbleData_;
}
else
{
for (ii = 0; ii < nInputs*nInputs; ii++)
vecTT[kk*nInputs*nInputs+ii] = pdata->dbleArray_[ii];
}
//**/ clean up
pdata->clean();
delete anaManager;
delete psIO;
}
//**/ compute mean and std dev
for (ii = 0; ii < nInputs; ii++)
{
for (jj = 0; jj <= ii; jj++)
vecTT[numBS*nInputs*nInputs+ii*nInputs+jj] = 0.0;
for (jj = ii+1; jj < nInputs; jj++)
{
ddata = 0.0;
for (kk = 0; kk < numBS; kk++)
ddata += vecTT[kk*nInputs*nInputs+ii*nInputs+jj];
vecTT[numBS*nInputs*nInputs+ii*nInputs+jj] = ddata/(double) numBS;
vecTT[(numBS+1)*nInputs*nInputs+ii*nInputs+jj] =
vecTT[ii*nInputs+jj];
vecTT[(numBS+2)*nInputs*nInputs+ii*nInputs+jj] =
vecTT[ii*nInputs+jj];
for (kk = 1; kk < numBS; kk++)
{
ddata = vecTT[kk*nInputs*nInputs+ii*nInputs+jj];
if (ddata < vecTT[(numBS+1)*nInputs*nInputs+ii*nInputs+jj])
vecTT[(numBS+1)*nInputs*nInputs+ii*nInputs+jj] = ddata;
if (ddata > vecTT[(numBS+2)*nInputs*nInputs+ii*nInputs+jj])
vecTT[(numBS+2)*nInputs*nInputs+ii*nInputs+jj] = ddata;
}
}
}
printAsterisks(PL_INFO, 0);
printf("RSSobol2b Statistics (based on %d replications): \n", numBS);
printf("Quantities are normalized.\n");
printEquals(PL_INFO, 0);
for (ii = 0; ii < nInputs; ii++)
{
for (jj = 0; jj <= ii; jj++) vecTT[ii*nInputs+jj] = 0.0;
for (jj = ii+1; jj < nInputs; jj++)
{
ddata = 0.0;
for (kk = 0; kk < numBS; kk++)
{
vecTT[kk*nInputs*nInputs+ii*nInputs+jj] -=
vecTT[numBS*nInputs*nInputs+ii*nInputs+jj];
ddata += pow(vecTT[kk*nInputs*nInputs+ii*nInputs+jj],2.0);
}
ddata /= (double) (numBS - 1);
vecTT[ii*nInputs+jj] = ddata;
printf("RSSobol2 Inputs (%4d %4d): mean = %10.3e, std = %10.3e\n",
ii+1,jj+1,vecTT[numBS*nInputs*nInputs+ii*nInputs+jj],ddata);
//printf("2Param Input (%4d %4d): min = %10.3e, max = %10.3e\n",ii+1,
// jj+1,vecTT[(numBS+1)*nInputs*nInputs+ii*nInputs+jj],
// vecTT[(numBS+2)*nInputs*nInputs+ii*nInputs+jj]);
}
}
printAsterisks(PL_INFO, 0);
if (plotScilab())
{
fp = fopen("scilabrssobol2b.sci", "w");
if (fp == NULL)
printf("ERROR : cannot open file scilabrssobol2b.sci\n");
}
else
{
fp = fopen("matlabrssobol2b.m", "w");
if (fp == NULL)
printf("ERROR : cannot open file matlabrssobol2b.sci\n");
}
if (fp != NULL)
{
strcpy(pString,"This file contains Sobol' 2nd order indices");
fwriteComment(fp, pString);
strcpy(pString,"set sortFlag = 1 and set nn to be the number");
fwriteComment(fp, pString);
strcpy(pString," of inputs to display.");
fwriteComment(fp, pString);
fprintf(fp, "sortFlag = 0;\n");
fprintf(fp, "nn = %d;\n", nInputs);
fprintf(fp, "Means = [\n");
for (ii = 0; ii < nInputs*nInputs; ii++)
fprintf(fp,"%24.16e\n", vecTT[numBS*nInputs*nInputs+ii]);
fprintf(fp, "];\n");
fprintf(fp, "Stds = [\n");
for (ii = 0; ii < nInputs*nInputs; ii++)
fprintf(fp,"%24.16e\n", vecTT[ii]);
fprintf(fp, "];\n");
fprintf(fp, "Lows = [\n");
for (ii = 0; ii < nInputs*nInputs; ii++)
fprintf(fp,"%24.16e\n", vecTT[(numBS+1)*nInputs*nInputs+ii]);
fprintf(fp, "];\n");
fprintf(fp, "Highs = [\n");
for (ii = 0; ii < nInputs*nInputs; ii++)
fprintf(fp,"%24.16e\n", vecTT[(numBS+2)*nInputs*nInputs+ii]);
fprintf(fp, "];\n");
if (inputNames == NULL)
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1);
if (plotScilab()) fprintf(fp,"'X%d'];\n",nInputs);
else fprintf(fp,"'X%d'};\n",nInputs);
}
else
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++)
{
if (inputNames[ii] != NULL)
fprintf(fp,"'%s',",inputNames[ii]);
else fprintf(fp,"'X%d',",ii+1);
}
if (plotScilab())
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'];\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'];\n",nInputs);
}
else
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'};\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'};\n",nInputs);
}
}
fwriteHold(fp, 0);
fprintf(fp, "ymin = min(Means-Stds);\n");
fprintf(fp, "ymax = max(Means+Stds);\n");
fprintf(fp, "ymin = min(Lows);\n");
fprintf(fp, "ymax = max(Highs);\n");
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
if (plotScilab())
{
fprintf(fp, "nn = %d;\n",nInputs);
fprintf(fp, "Means = matrix(Means, nn, nn);\n");
fprintf(fp, "Means = Means';\n");
fprintf(fp, "Stds = matrix(Stds, nn, nn);\n");
fprintf(fp, "Stds = Stds';\n");
fprintf(fp, "Lows = matrix(Lows, nn, nn);\n");
fprintf(fp, "Lows = Lows';\n");
fprintf(fp, "Highs = matrix(Highs, nn, nn);\n");
fprintf(fp, "Highs = Highs';\n");
fprintf(fp, "drawlater\n");
fprintf(fp, "hist3d(Means);\n");
fprintf(fp, "set(gca(),\"auto_clear\",\"off\")\n");
fprintf(fp, "//for ii = 1:nn\n");
fprintf(fp, "// for jj = ii+1:nn\n");
fprintf(fp, "// XX = [ii ii];\n");
fprintf(fp, "// YY = [jj jj];\n");
fprintf(fp, "// MM = Means(ii,jj);\n");
fprintf(fp, "// SS = Stds(ii,jj);\n");
fprintf(fp, "// ZZ = [MM-SS MM+SS];\n");
fprintf(fp, "// plot3d(XX,YY,ZZ,'-ko','LineWidth',3.0,");
fprintf(fp, "// 'MarkerEdgeColor','k','MarkerFaceColor',");
fprintf(fp, "// 'g','MarkerSize',13)\n");
fprintf(fp, "// end;\n");
fprintf(fp, "//end;\n");
fprintf(fp, "//a=gca();\n");
fprintf(fp, "//a.data_bounds=[0, 0, 0; nn, nn+1, ymax];\n");
fprintf(fp, "//newtick = a.x_ticks;\n");
fprintf(fp, "//newtick(2) = [1:nn]';\n");
fprintf(fp, "//drawlater\n");
fprintf(fp, "//hist3d(Means);\n");
fprintf(fp, "//set(gca(),\"auto_clear\",\"off\")\n");
fprintf(fp, "//for ii = 1:nn\n");
fprintf(fp, "// for jj = ii+1:nn\n");
fprintf(fp, "// XX = [ii ii];\n");
fprintf(fp, "// YY = [jj jj];\n");
fprintf(fp, "// MM = Means(ii,jj);\n");
fprintf(fp, "// SS = Stds(ii,jj);\n");
fprintf(fp, "// ZZ = [MM-SS MM+SS];\n");
fprintf(fp, "// plot3d(XX,YY,ZZ,'-ko','LineWidth',3.0,");
fprintf(fp, "// 'MarkerEdgeColor','k','MarkerFaceColor',");
fprintf(fp, "// 'g','MarkerSize',13)\n");
fprintf(fp, "// end;\n");
fprintf(fp, "//end;\n");
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, 0, 0; nn, nn+1, ymax];\n");
fprintf(fp, "newtick = a.x_ticks;\n");
fprintf(fp, "newtick(2) = [1:nn]';\n");
fprintf(fp, "newtick(3) = Str';\n");
fprintf(fp, "a.x_ticks = newtick;\n");
fprintf(fp, "a.x_label.font_size = 3;\n");
fprintf(fp, "a.x_label.font_style = 4;\n");
fprintf(fp, "a.y_ticks = newtick;\n");
fprintf(fp, "a.y_label.font_size = 3;\n");
fprintf(fp, "a.y_label.font_style = 4;\n");
fprintf(fp, "a.rotation_angles = [5 -70];\n");
fprintf(fp, "drawnow\n");
}
else
{
fprintf(fp, "nn = %d;\n",nInputs);
fprintf(fp, "Means = reshape(Means, nn, nn);\n");
fprintf(fp, "Means = Means';\n");
fprintf(fp, "Stds = reshape(Stds, nn, nn);\n");
fprintf(fp, "Stds = Stds';\n");
fprintf(fp, "Lows = reshape(Lows, nn, nn);\n");
fprintf(fp, "Lows = Lows';\n");
fprintf(fp, "Highs = reshape(Highs, nn, nn);\n");
fprintf(fp, "Highs = Highs';\n");
fprintf(fp, "hh = bar3(Means,0.8);\n");
fprintf(fp, "alpha = 0.2;\n");
fprintf(fp, "set(hh,'FaceColor','b','facea',alpha);\n");
fprintf(fp, "Lstds = Means - Stds;\n");
fprintf(fp, "Ustds = Means + Stds;\n");
fprintf(fp, "Lstds = Lows;\n");
fprintf(fp, "Ustds = Highs;\n");
fprintf(fp, "[X,Y] = meshgrid(1:nn,1:nn);\n");
fwriteHold(fp, 1);
fprintf(fp, "for k = 1:nn\n");
fprintf(fp, " for l = k:nn\n");
fprintf(fp, " mkl = Means(k,l);\n");
fprintf(fp, " ukl = Ustds(k,l);\n");
fprintf(fp, " lkl = Lstds(k,l);\n");
fprintf(fp, " if (mkl > .02 & (ukl-lkl)/mkl > .02)\n");
fprintf(fp, " xkl = [X(k,l), X(k,l)];\n");
fprintf(fp, " ykl = [Y(k,l), Y(k,l)];\n");
fprintf(fp, " zkl = [lkl, ukl];\n");
fprintf(fp, " plot3(xkl,ykl,zkl,'-mo',...\n");
fprintf(fp, " 'LineWidth',5,'MarkerEdgeColor','k',...\n");
fprintf(fp, " 'MarkerFaceColor','k','MarkerSize',10);\n");
fprintf(fp, " end\n");
fprintf(fp, " end\n");
fprintf(fp, "end\n");
fwriteHold(fp, 0);
fprintf(fp, "axis([0.5 nn+0.5 0.5 nn+0.5 0 ymax])\n");
fprintf(fp, "set(gca,'XTickLabel',Str);\n");
fprintf(fp, "set(gca,'YTickLabel',Str);\n");
fprintf(fp, "set(gca, 'fontsize', 12)\n");
fprintf(fp, "set(gca, 'fontweight', 'bold')\n");
fprintf(fp, "set(gca, 'linewidth', 2)\n");
}
fwritePlotAxes(fp);
fwritePlotTitle(fp,"Sobol 1st+2nd Order Indices (with bootstrap)");
fwritePlotZLabel(fp, "Sobol Indices (Normalized)");
fwritePlotXLabel(fp, "Inputs");
fwritePlotYLabel(fp, "Inputs");
fclose(fp);
if (plotScilab())
printf("rssobol2b plot file = scilabrssobol2b.sci\n");
else printf("rssobol2b plot file = matlabrssobol2b.m\n");
}
//**/ restore previous settings
psConfig_.AnaExpertModeRestore();
psConfig_.RSExpertModeRestore();
psConfig_.InteractiveRestore();
}
//**/ -------------------------------------------------------------
// +++ rssoboltsib
//**/ rssoboltsi with bootstrap
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssoboltsib"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssoboltsib: compute RS-based Sobol' total-order indices\n");
printf("Syntax: rssoboltsib (no argument needed)\n");
printf("NOTE: This command computes the total-order ");
printf("Sobol' indices using\n");
printf(" response surface constructed from the ");
printf("loaded sample. It \n");
printf(" estimates prediction uncertainty using ");
printf("bootstrapping.\n");
return 0;
}
if (nInputs <= 0 || psuadeIO == NULL)
{
printf("ERROR: data file not loaded.\n");
return 1;
}
if (nInputs < 2)
{
printf("INFO: no point doing this for nInputs < 2.\n");
return 1;
}
if (nSamples < 10)
{
printf("WARNING: your sample size is quite small.\n");
printf(" Bootstrapped samples will be smaller.\n");
return 1;
}
//**/ print usage information
printAsterisks(PL_INFO, 0);
printf("This command computes total-order sensitivity ");
printf("indices using an\n");
printf("ensemble of response surfaces constructed from ");
printf("the loaded sample.\n");
printf("Evaluations from the ensemble response surfaces ");
printf("give error estimates\n");
printf("for the sensitivity indices.\n");
#ifndef PSUADE_OMP
printf("Advice: this command can be accelerated if you use OpenMP.\n");
#endif
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ get output information
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ get which response surface to use
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
#ifdef PSUADE_OMP
if (faType == PSUADE_RS_MARS || faType == PSUADE_RS_GP1 ||
faType >= PSUADE_RS_ACOSSO || faType == PSUADE_RS_SVM ||
faType == PSUADE_RS_TGP || faType == PSUADE_RS_KR)
{
printf("These RS does not work in OpenMP mode. Select another one.\n");
printf("- MARS and MARS-based RS\n");
printf("- Multi-domain RS\n");
printf("- GP1, TGP, SVM\n");
printf("- SVM\n");
printf("- Kriging (it uses Fortran optimizer)\n");
faType = -1;
}
if (faType == PSUADE_RS_REGRL)
printf("Legendre polynomial of order=2\n");
#endif
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
if (faType == PSUADE_RS_MARSB)
{
printf("rssoboltsib INFO: MarsBagg response surface selected but\n");
printf(" it is redundant - use MARS instead.\n");
faType = PSUADE_RS_MARS;
}
//**/ set up for iterations
sprintf(pString, "How many bootstrapped samples to use (5 - 300) : ");
int numBS = getInt(5, 300, pString);
//**/ need to turn off expert modes, so save them first
psConfig_.AnaExpertModeSaveAndReset();
psConfig_.RSExpertModeSaveAndReset();
psConfig_.InteractiveSaveAndReset();
//**/ set up analysis manager
int analysisMethod = PSUADE_ANA_RSSOBOLTSI;
printEquals(PL_INFO, 0);
//**/ set up storage for the response surface samples
int ind, nSamples2;
psVector vecXT, vecYT, vecTT;
psIVector vecIT, vecST;
PsuadeData *psIO=NULL;
AnalysisManager *anaManager;
pData pNames, pIpdfs, pImeans, pIstds, pIcor;
vecTT.setLength(numBS*nInputs);
//**/ iterate
#pragma omp parallel shared(vecTT,sampleInputs,sampleStates,sampleOutputs,psuadeIO) \
private(kk,jj,ss,ii,nSamples2,ind,vecXT,vecYT,vecST,vecIT,psIO,anaManager,pNames,pIpdfs,pImeans,pIstds,pIcor)
#pragma omp for
for (kk = 0; kk < numBS; kk++)
{
vecXT.setLength(nSamples*nInputs);
vecYT.setLength(nSamples);
vecIT.setLength(nSamples);
vecST.setLength(nSamples);
anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
psIO = new PsuadeData();
//**/ random draw
for (jj = 0; jj < nSamples; jj++) vecIT[jj] = 0;
ss = nSamples2 = 0;
while (ss < nSamples)
{
ind = PSUADE_rand() % nSamples;
if (vecIT[ind] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecXT[nSamples2*nInputs+ii] =
sampleInputs[ind*nInputs+ii];
vecYT[nSamples2] = sampleOutputs[ind*nOutputs+outputID];
vecST[nSamples2] = sampleStates[ind];
vecIT[ind] = 1;
nSamples2++;
}
ss++;
}
printf("rssoboltsib: bootstrap %d begins (sample size = %d)\n",
kk+1,nSamples2);
psuadeIO->getParameter("input_names", pNames);
psuadeIO->getParameter("input_pdfs", pIpdfs);
psuadeIO->getParameter("input_means", pImeans);
psuadeIO->getParameter("input_stdevs", pIstds);
psuadeIO->getParameter("input_cor_matrix", pIcor);
psIO->updateInputSection(nSamples2,nInputs,NULL,iLowerB,iUpperB,
vecXT.getDVector(),pNames.strArray_,pIpdfs.intArray_,
pImeans.dbleArray_,pIstds.dbleArray_,
(psMatrix *) pIcor.psObject_);
psIO->updateOutputSection(nSamples2,1,vecYT.getDVector(),
vecST.getIVector(),&(outputNames[outputID]));
psIO->updateMethodSection(PSUADE_SAMP_MC,nSamples2,-1,-1,-1);
psIO->updateAnalysisSection(-1,-1,faType,-3,-1,-1);
//**/ analyze the result
anaManager->analyze(psIO, 0, NULL, 0);
//**/ get the statistics
pData *pdata = psIO->getAuxData();
if (pdata->dbleData_ > 0)
{
for (ii = 0; ii < nInputs; ii++)
vecTT[kk*nInputs+ii] =
pdata->dbleArray_[ii]/pdata->dbleData_;
}
else
{
for (ii = 0; ii < nInputs; ii++)
vecTT[kk*nInputs+ii] = pdata->dbleArray_[ii];
}
//**/ clean up
pdata->clean();
delete anaManager;
delete psIO;
}
//**/ postprocessing
psVector vecMT, vecVT;
vecMT.setLength(nInputs);
for (ii = 0; ii < nInputs; ii++)
{
vecMT[ii] = vecTT[ii];
for (jj = 1; jj < numBS; jj++) vecMT[ii] += vecTT[jj*nInputs+ii];
vecMT[ii] /= (double) numBS;
}
vecVT.setLength(nInputs);
for (ii = 0; ii < nInputs; ii++)
{
vecVT[ii] = pow(vecTT[ii]-vecMT[ii], 2.0);
for (jj = 1; jj < numBS; jj++)
vecVT[ii] += pow(vecTT[jj*nInputs+ii]-vecMT[ii],2.0);
vecVT[ii] /= (double) (numBS - 1);
vecVT[ii] = sqrt(vecVT[ii]);
}
printAsterisks(PL_INFO, 0);
printf("RSSobolTSIb' Statistics (based on %d replications): \n",
numBS);
printf("Quantities are normalized.\n");
printEquals(PL_INFO, 0);
for (ii = 0; ii < nInputs; ii++)
printf("RSSobolTSI Input %4d: mean = %10.3e, std = %10.3e\n",
ii+1,vecMT[ii],vecVT[ii]);
printAsterisks(PL_INFO, 0);
//**/ generate matlab/scilab file
if (plotScilab())
{
fp = fopen("scilabrssoboltsib.sci","w");
if (fp == NULL)
printf("ERROR : cannot open file scilabrssoboltsib.sci\n");
else
{
fprintf(fp,"// This file contains total order Sobol' indices\n");
fprintf(fp,"// with error bars coming from bootstrapping.\n");
fprintf(fp,"// to select the most important ones to display,\n");
fprintf(fp,"// set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"// of inputs to display.\n");
}
}
else
{
fp = fopen("matlabrssoboltsib.m","w");
if (fp == NULL)
printf("ERROR : cannot open file matlabrssoboltsib.sci\n");
else
{
fprintf(fp,"%% This file contains total order Sobol' indices\n");
fprintf(fp,"%% with error bars coming from bootstrapping.\n");
fprintf(fp,"%% to select the most important ones to display,\n");
fprintf(fp,"%% set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"%% of inputs to display.\n");
}
}
if (fp != NULL)
{
fprintf(fp, "sortFlag = 0;\n");
fprintf(fp, "nn = %d;\n", nInputs);
fprintf(fp, "Means = [\n");
for (ii = 0; ii < nInputs; ii++) fprintf(fp,"%24.16e\n",vecMT[ii]);
fprintf(fp, "];\n");
fprintf(fp, "Stds = [\n");
for (ii = 0; ii < nInputs; ii++) fprintf(fp,"%24.16e\n",vecVT[ii]);
fprintf(fp, "];\n");
if (inputNames == NULL)
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1);
if (plotScilab()) fprintf(fp,"'X%d'];\n",nInputs);
else fprintf(fp,"'X%d'};\n",nInputs);
}
else
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++)
{
if (inputNames[ii] != NULL)
fprintf(fp,"'%s',",inputNames[ii]);
else fprintf(fp,"'X%d',",ii+1);
}
if (plotScilab())
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'];\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'];\n",nInputs);
}
else
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'};\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'};\n",nInputs);
}
}
fwriteHold(fp, 0);
fprintf(fp, "if (sortFlag == 1)\n");
if (plotScilab())
fprintf(fp, " [Means, I2] = gsort(Means);\n");
else fprintf(fp, " [Means, I2] = sort(Means,'descend');\n");
fprintf(fp, " Stds = Stds(I2);\n");
fprintf(fp, " I2 = I2(1:nn);\n");
fprintf(fp, " Means = Means(1:nn);\n");
fprintf(fp, " Stds = Stds(1:nn);\n");
fprintf(fp, " Str = Str(I2);\n");
fprintf(fp, "end\n");
fprintf(fp, "ymin = min(Means-Stds);\n");
fprintf(fp, "if ymin < 0 \n");
fprintf(fp, " ymin = 0;\n");
fprintf(fp, "end;\n");
fprintf(fp, "ymax = max(Means+Stds);\n");
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
if (plotScilab()) fprintf(fp, "drawlater\n");
fprintf(fp, "bar(Means,0.8);\n");
fprintf(fp, "for ii = 1:nn\n");
fprintf(fp, " if (ii == 1)\n");
fwriteHold(fp, 1);
fprintf(fp, " end;\n");
fprintf(fp, " XX = [ii ii];\n");
fprintf(fp, " YY = [Means(ii)-Stds(ii) Means(ii)+Stds(ii)];\n");
fprintf(fp, " if YY(1) < 0 \n");
fprintf(fp, " YY(1) = 0;\n");
fprintf(fp, " end;\n");
fprintf(fp, " plot(XX,YY,'-ko','LineWidth',3.0,'MarkerEdgeColor',");
fprintf(fp, "'k','MarkerFaceColor','g','MarkerSize',12)\n");
fprintf(fp, "end;\n");
fwritePlotAxes(fp);
if (plotScilab())
{
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, ymin; nn+1, ymax];\n");
fprintf(fp, "newtick = a.x_ticks;\n");
fprintf(fp, "newtick(2) = [1:nn]';\n");
fprintf(fp, "newtick(3) = Str';\n");
fprintf(fp, "a.x_ticks = newtick;\n");
fprintf(fp, "a.x_label.font_size = 3;\n");
fprintf(fp, "a.x_label.font_style = 4;\n");
}
else
{
fprintf(fp,"axis([0 nn+1 ymin ymax])\n");
fprintf(fp,"set(gca,'XTickLabel',[]);\n");
fprintf(fp,"th=text(1:nn, repmat(ymin-0.05*(ymax-ymin),nn,1),");
fprintf(fp,"Str,'HorizontalAlignment','left','rotation',90);\n");
fprintf(fp,"set(th, 'fontsize', 12)\n");
fprintf(fp,"set(th, 'fontweight', 'bold')\n");
}
fwritePlotTitle(fp,"Total Order Sobol Indices (with bootstrap)");
fwritePlotYLabel(fp, "Total Order Sobol Index (Normalized)");
fwriteHold(fp, 0);
if (plotScilab())
{
fprintf(fp, "drawnow\n");
printf("rssoboltsib plot file = scilabrssoboltsib.sci\n");
}
else printf("rssoboltsib plot file = matlabrssoboltsib.m\n");
fclose(fp);
}
//**/ restore previous settings
psConfig_.AnaExpertModeRestore();
psConfig_.RSExpertModeRestore();
psConfig_.InteractiveRestore();
}
//**/ -------------------------------------------------------------
// +++ rsua2
//**/ uncertainty analysis on fuzzy response surface
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsua2") || !strcmp(command, "rs_ua"))
{
printf("This command has been replaced by rsua\n");
return 0;
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsua2: uncertainty analysis on response surface\n");
printf("Syntax: rsua2 (no argument needed)\n");
printf("This command perform uncertainty analysis on the response\n");
printf("surface built from the loaded sample. If you select a\n");
printf("stochastic response surface type (Kriging, MARSB, or\n");
printf("polynomial regression, the effect of response surface\n");
printf("uncertainty (in the average sense) will be shown on the \n");
printf("PDF and CDF plots.\n");
printf("NOTE: This analysis supports non-uniform distributions for\n");
printf(" the inputs. Simply prescribe PDF in the data file\n");
printf(" and turn on use_input_pdfs in ANALYSIS.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
//**/ query user
Sampling *samPtr;
FuncApprox *faPtr;
PDFManager *pdfman;
psVector vecOut, vecLower, vecUpper;
psuadeIO->getParameter("ana_rstype", pPtr);
faType = pPtr.intData_;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
sprintf(pString,
"Sample size for generating distribution? (10000 - 100000) ");
int nSamp = getInt(10000, 100000, pString);
int saveFlag = 0;
printf("Save the generated sample in a file? (y or n) ");
fgets(winput,10,stdin);
if (winput[0] == 'y') saveFlag = 1;
int rsUncertaintyFlag = 0;
printf("Include RS uncertainty in uncertainty analysis? (y or n) ");
fgets(winput,10,stdin);
if (winput[0] == 'y') rsUncertaintyFlag = 1;
//**/ create response surface ==> faPtr
printf("Phase 1 of 4: create response surface\n");
faType = -1;
faPtr = genFA(faType, nInputs, -1, nSamples);
faPtr->setNPtsPerDim(32);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
psVector vecYT;
if (nOutputs > 1)
{
vecYT.setLength(nSamples);
for (ss = 0; ss < nSamples; ss++)
vecYT[ss] = sampleOutputs[ss*nOutputs+outputID];
}
else vecYT.load(nSamples, sampleOutputs);
faPtr->initialize(sampleInputs,vecYT.getDVector());
//**/ create a MC sample => nSamp, samInputs
printf("Phase 2 of 4: create MC sample\n");
psVector vecSamInps, vecSamOuts;
vecSamInps.setLength(nInputs*nSamp);
vecSamOuts.setLength(nSamp);
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
int usePDFs = pPtr.intData_;
if (usePDFs == 1)
{
printf("NOTE: Some inputs have non-uniform PDFs.\n");
printf(" A MC sample will be created with these PDFs.\n");
psuadeIO->getParameter("method_sampling", pPtr);
kk = pPtr.intData_;
psuadeIO->updateMethodSection(PSUADE_SAMP_MC,-1,-1,-1,-1);
pdfman = new PDFManager();
pdfman->initialize(psuadeIO);
vecOut.setLength(nSamp*nInputs);
vecUpper.load(nInputs, iUpperB);
vecLower.load(nInputs, iLowerB);
pdfman->genSample(nSamp, vecOut, vecLower, vecUpper);
for (ii = 0; ii < nSamp*nInputs; ii++) vecSamInps[ii] = vecOut[ii];
psuadeIO->updateMethodSection(kk,-1,-1,-1,-1);
delete pdfman;
}
else
{
printf("NOTE: Uniform distributions will be used for all inputs.\n");
printf(" To use other than uniform distributions, prescribe\n");
printf(" them in the data file and set use_input_pdfs in the\n");
printf(" ANALYSIS section.\n");
if (nInputs < 51)
samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LPTAU);
else samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LHS);
samPtr->setPrintLevel(0);
samPtr->setInputBounds(nInputs, iLowerB, iUpperB);
samPtr->setOutputParams(1);
samPtr->setSamplingParams(nSamp, -1, -1);
samPtr->initialize(0);
psIVector vecSamStates;
vecSamStates.setLength(nSamp);
samPtr->getSamples(nSamp,nInputs,1,vecSamInps.getDVector(),
vecSamOuts.getDVector(),vecSamStates.getIVector());
delete samPtr;
samPtr = NULL;
}
//**/ evaluate the sample => samOutputs, samStds
psVector vecSamStds;
vecSamStds.setLength(nSamp);
printf("Phase 3 of 4: evaluate sample\n");
if (rsUncertaintyFlag == 1)
faPtr->evaluatePointFuzzy(nSamp,vecSamInps.getDVector(),
vecSamOuts.getDVector(),vecSamStds.getDVector());
else
faPtr->evaluatePoint(nSamp, vecSamInps.getDVector(),
vecSamOuts.getDVector());
delete faPtr;
faPtr = NULL;
if (saveFlag == 1)
{
if (!strcmp(command, "rsua2")) fp = fopen("rsua2_sample","w");
else fp = fopen("rsua_sample","w");
fprintf(fp, "%% inputs, output, output-3 sigma, output+3sigma\n");
fprintf(fp, "%d %d 3\n", nSamp, nInputs);
for (ss = 0; ss < nSamp; ss++)
{
for (ii = 0; ii < nInputs; ii++)
fprintf(fp, "%e ", vecSamInps[ss*nInputs+ii]);
fprintf(fp, "%e ", vecSamOuts[ss]);
fprintf(fp, "%e ", vecSamOuts[ss]-3*vecSamStds[ss]);
fprintf(fp, "%e\n", vecSamOuts[ss]+3*vecSamStds[ss]);
}
fclose(fp);
if (!strcmp(command, "rsua2"))
printf("A MC sample has been written to the file 'rsua2_sample'\n");
else
printf("A MC sample has been written to the file 'rsua_sample'\n");
}
//**/ get the bounds for binning purposes => Fcounts
int nbins = 100, ntimes, **Fcounts;
double mean=0, stdev=0;
double FmaxO=-PSUADE_UNDEFINED, FminO=PSUADE_UNDEFINED;
printf("Phase 4 of 4: binning\n");
//**/ bin the original sample and compute statistics
if (rsUncertaintyFlag == 0) ntimes = 1;
else ntimes = 21;
Fcounts = new int*[ntimes+1];
for (ii = 0; ii <= ntimes; ii++)
{
Fcounts[ii] = new int[nbins];
for (kk = 0; kk < nbins; kk++) Fcounts[ii][kk] = 0;
}
for (ss = 0; ss < nSamp; ss++)
{
if (vecSamOuts[ss] > FmaxO) FmaxO = vecSamOuts[ss];
if (vecSamOuts[ss] < FminO) FminO = vecSamOuts[ss];
if (vecSamOuts[ss] > FmaxO) FmaxO = vecSamOuts[ss];
if (vecSamOuts[ss] < FminO) FminO = vecSamOuts[ss];
}
FmaxO = FmaxO + 0.1 * (FmaxO - FminO);
FminO = FminO - 0.1 * (FmaxO - FminO);
if (FmaxO == FminO)
{
FmaxO = FmaxO + 0.1 * PABS(FmaxO);
FminO = FminO - 0.1 * PABS(FminO);
}
for (ss = 0; ss < nSamp; ss++)
{
ddata = vecSamOuts[ss] - FminO;
if (FmaxO > FminO) ddata = ddata / ((FmaxO - FminO) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ntimes][kk]++;
}
for (ss = 0; ss < nSamp; ss++) mean += vecSamOuts[ss];
mean /= (double) nSamp;
for (ss = 0; ss < nSamp; ss++)
stdev += pow(vecSamOuts[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) nSamp);
printAsterisks(PL_INFO, 0);
printf("Sample mean = %e (RS uncertainties not included)\n",mean);
printf("Sample std dev = %e (RS uncertainties not included)\n",stdev);
printEquals(PL_INFO, 0);
//**/ bin the rest
double mean2=0, stdev2=0;
double Fmax=-PSUADE_UNDEFINED, Fmin=PSUADE_UNDEFINED;
if (rsUncertaintyFlag == 1)
{
psVector vecSamFuzzy, vecSamOutSave;
PDFNormal *rsPDF;
vecSamFuzzy.setLength(ntimes*nInputs);
vecSamOutSave.setLength(nSamp*ntimes);
for (ss = 0; ss < nSamp; ss++)
{
if (vecSamStds[ss] == 0)
{
for (ii = 0; ii < ntimes; ii++)
vecSamFuzzy[ii] = vecSamOuts[ss];
}
else
{
ddata = 6.0 * vecSamStds[ss] / (ntimes - 1.0);
for (ii = 0; ii < ntimes; ii++)
vecSamFuzzy[ii] = vecSamOuts[ss]+ii*ddata-3*vecSamStds[ss];
}
for (ii = 0; ii < ntimes; ii++)
vecSamOutSave[ss*ntimes+ii] = vecSamFuzzy[ii];
if (ss % (nSamp / 8) == 0)
{
printf(".");
fflush(stdout);
}
}
for (ss = 0; ss < nSamp*ntimes; ss++)
{
if (vecSamOutSave[ss] < Fmin) Fmin = vecSamOutSave[ss];
if (vecSamOutSave[ss] > Fmax) Fmax = vecSamOutSave[ss];
}
Fmax = Fmax + 0.1 * (Fmax - Fmin);
Fmin = Fmin - 0.1 * (Fmax - Fmin);
if (Fmax == Fmin)
{
Fmax = Fmax + 0.1 * PABS(Fmax);
Fmin = Fmin - 0.1 * PABS(Fmin);
}
for (ss = 0; ss < nSamp; ss++)
{
for (ii = 0; ii < ntimes; ii++)
{
ddata = vecSamOutSave[ss*ntimes+ii] - Fmin;
ddata = ddata / ((Fmax - Fmin) / nbins);
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ii][kk]++;
}
}
for (ss = 0; ss < nSamp*ntimes; ss++) mean2 += vecSamOutSave[ss];
mean2 /= (double) (nSamp*ntimes);
for (ss = 0; ss < nSamp*ntimes; ss++)
stdev2 += pow(vecSamOutSave[ss] - mean2, 2.0);
stdev2 = sqrt(stdev2/(double) (nSamp*ntimes));
printf("Sample mean = %e (RS uncertainties included)\n",mean2);
printf("Sample std dev = %e (RS uncertainties included)\n",stdev2);
printAsterisks(PL_INFO, 0);
}
//**/ generate matlab/scilab file
if (plotScilab())
{
if (!strcmp(command, "rsua2")) fp = fopen("scilabrsua2.sci", "w");
else fp = fopen("scilabrsua.sci", "w");
if (fp == NULL)
{
printf("rsua2 ERROR: cannot open scilab file.\n");
for (ii = 0; ii <= ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
return 1;
}
}
else
{
if (!strcmp(command, "rsua2")) fp = fopen("matlabrsua2.m", "w");
else fp = fopen("matlabrsua.m", "w");
if (fp == NULL)
{
printf("rsua2 ERROR: cannot open matlab file.\n");
for (ii = 0; ii <= ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
return 1;
}
}
fwriteHold(fp, 0);
fprintf(fp, "subplot(2,2,1)\n");
fprintf(fp, "XO = [\n");
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%e\n", (FmaxO-FminO)/nbins*(0.5+kk)+FminO);
fprintf(fp, "];\n");
fprintf(fp, "X = [\n");
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%e\n", (Fmax-Fmin)/nbins*(0.5+kk)+Fmin);
fprintf(fp, "];\n");
for (ii = 0; ii <= ntimes; ii++)
{
fprintf(fp, "N%d = [\n", ii+1);
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%d\n", Fcounts[ii][kk]);
fprintf(fp, "];\n");
}
fprintf(fp, "N = [");
for (ii = 0; ii <= ntimes; ii++)
fprintf(fp, "N%d/sum(N%d) ", ii+1, ii+1);
fprintf(fp, "];\n");
fprintf(fp, "NA = N(:,%d+1);\n",ntimes);
fprintf(fp, "NA = NA / sum(NA);\n");
fprintf(fp, "bar(XO,NA,1.0)\n");
fprintf(fp, "ymin = 0;\n");
fprintf(fp, "ymax = max(NA);\n");
fprintf(fp, "axis([min(XO) max(XO) ymin ymax])\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (means of RS)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities)");
if (plotMatlab())
{
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",mean);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev);
}
if (rsUncertaintyFlag == 1)
{
fprintf(fp, "NB = sum(N(:,1:%d)');\n",ntimes);
fprintf(fp, "NB = NB' / sum(NB);\n");
fprintf(fp, "subplot(2,2,3)\n");
fprintf(fp, "bar(X,NB,1.0)\n");
fprintf(fp, "ymax = max(max(NA),max(NB));\n");
fprintf(fp, "axis([min(X) max(X) ymin ymax])\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (RS with uncertainties)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities)");
if (plotMatlab())
{
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",
mean2);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev2);
}
}
else
{
printf("Deterministic RS used ==> no RS uncertainties.\n");
fprintf(fp, "subplot(2,2,3)\n");
fwritePlotTitle(fp, "Prob. Dist. (RS with uncertainties)");
sprintf(pString, "Deterministic RS: no RS uncertainties");
fwriteComment(fp, pString);
}
if (faType == PSUADE_RS_MARS || faType == PSUADE_RS_RBF ||
rsUncertaintyFlag == 0)
{
fprintf(fp, "subplot(2,2,[2 4])\n");
fprintf(fp, "plot(X,NA,'linewidth',3)\n");
fwritePlotTitle(fp,"Cum. Dist.: (*) uncertainties unavailable");
}
else
{
for (ii = 0; ii <= ntimes; ii++)
{
fprintf(fp, "for ii = 2 : %d\n", nbins);
fprintf(fp, " N%d(ii) = N%d(ii) + N%d(ii-1);\n",ii+1,ii+1,ii+1);
fprintf(fp, "end;\n");
}
fprintf(fp, "N = [");
for (ii = 0; ii <= ntimes; ii++)
fprintf(fp, "N%d/N%d(%d) ", ii+1, ii+1, nbins);
fprintf(fp, "];\n");
fprintf(fp, "subplot(2,2,[2 4])\n");
fwriteHold(fp, 1);
fprintf(fp, "for ii = 1 : %d\n", ntimes);
fprintf(fp, " if (ii == %d)\n", (ntimes+1)/2);
fprintf(fp, " plot(X,N(:,ii),'b-','linewidth',3)\n");
fprintf(fp, " else\n");
fprintf(fp, " plot(X,N(:,ii),'r-','linewidth',1)\n");
fprintf(fp, " end\n");
fprintf(fp, "end\n");
fwritePlotTitle(fp,"Cum. Dist.: (b) mean; (r) with uncertainties");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
if (!strcmp(command, "rsua2"))
{
if (plotScilab())
printf("Output distribution plots is in scilabrsua2.sci.\n");
else printf("Output distribution plots is in matlabrsua2.m.\n");
}
else
{
if (plotScilab())
printf("Output distribution plots is in scilabrsua.sci.\n");
else printf("Output distribution plots is in matlabrsua.m.\n");
}
for (ii = 0; ii < ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
}
//**/ -------------------------------------------------------------
// +++ rsuab2
//**/ uncertainty analysis on fuzzy response surface (New 2/2014)
//**/ This is similar to rsuab but support psuadeData format
//**/ This will be replaced by rsua + rsuab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsuab2"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsuab2: uncertainty analysis on response surface\n");
printf("Syntax: rsuab2 (no argument needed)\n");
printf("This command performs uncertainty analysis on the ");
printf("response surface\n");
printf("constructed from the LOADED sample. Uncertainty analysis ");
printf("is performed\n");
printf("using a user-provided sample in PSUADE data format ");
printf("(created by running\n");
printf("psuade on an input file). If you select a stochastic ");
printf("response surface\n");
printf("(Kriging, MARSB, or polynomial regression), the effect ");
printf("of response\n");
printf("surface uncertainty will be shown on the PDF and CDF plots.)\n");
printf("NOTE: This command is more general than rsua and rsuab by ");
printf("allowing\n");
printf(" users to add a discrepancy model.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
int discFile=0, nInps, nOuts, dnInps;
char discFileName[1001], uaFileName[1001];
PsuadeData *discIO=NULL, *sampleIO=NULL;
FuncApprox **faPtrsRsEval=NULL;
//**/ query user for output ID
sscanf(lineIn,"%s %s", command, winput);
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ optional: discrepancy model
faPtrsRsEval = new FuncApprox*[2];
faPtrsRsEval[0] = NULL;
faPtrsRsEval[1] = NULL;
printf("Use discrepancy model (in PSUADE data format)? ('y' or 'n') ");
scanf("%s", winput);
fgets(lineIn2, 500, stdin);
if (winput[0] == 'y')
{
discFile = 1;
printf("Enter discrepancy model file (in PSUADE data format): ");
scanf("%s", discFileName);
fgets(lineIn2, 500, stdin);
discIO = new PsuadeData();
status = discIO->readPsuadeFile(discFileName);
if (status != 0)
{
printf("ERROR: cannot read discrepancy model file.\n");
delete [] faPtrsRsEval;
delete discIO;
return 1;
}
discIO->getParameter("input_ninputs", pPtr);
dnInps = pPtr.intData_;
if (dnInps < nInputs)
{
printf("Discrepancy model has %d inputs. So the first\n", dnInps);
printf("%d inputs in the model file will be assumed to\n", dnInps);
printf("be associated with the inputs of the discrepancy model.\n");
}
discIO->getParameter("output_noutputs", pPtr);
nOuts = pPtr.intData_;
if (nOuts > 1)
{
printf("The discrepancy model has nOutputs > 1.\n");
printf("This is currently not supported.\n");
printf("Use 'odelete' to modify your discrepancy model file.\n");
delete [] faPtrsRsEval;
delete discIO;
return 1;
}
printf("** CREATING RESPONSE SURFACE FOR DISCREPANCY MODEL\n");
faPtrsRsEval[1] = genFAInteractive(discIO, 3);
delete discIO;
discIO = NULL;
}
//**/ request or generate a sample for evaluation
printf("A sample is needed from you to propagate through the RS.\n");
printf("Select between the two options below: \n");
printf("1. PSUADE will generate the sample\n");
printf("2. User will provide the sample (in PSUADE data format)\n");
sprintf(pString, "Enter 1 or 2 : ");
int samSrc = getInt(1, 2, pString);
//**/ generate a sample or get from user a sample for evaluation
//**/ ==> usNSams, vecUAInps
int uaNSams;
psVector vecUAInps, vecUAOuts;
psIVector vecUAStas;
if (samSrc == 1)
{
printf("PSUADE will generate a sample for uncertainty analysis.\n");
sprintf(pString, "Sample size ? (10000 - 100000) ");
uaNSams = getInt(10000, 100000, pString);
vecUAInps.setLength(uaNSams * nInputs);
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
int usePDFs = pPtr.intData_;
if (usePDFs == 1)
{
printf("NOTE: Some inputs have non-uniform PDFs.\n");
printf(" A MC sample will be created with these PDFs.\n");
psuadeIO->getParameter("method_sampling", pPtr);
kk = pPtr.intData_;
psuadeIO->updateMethodSection(PSUADE_SAMP_MC,-1,-1,-1,-1);
PDFManager *pdfman = new PDFManager();
pdfman->initialize(psuadeIO);
vecUAInps.setLength(uaNSams*nInputs);
psVector vecLs, vecUs;
vecUs.load(nInputs, iUpperB);
vecLs.load(nInputs, iLowerB);
pdfman->genSample(uaNSams, vecUAInps, vecLs, vecUs);
psuadeIO->updateMethodSection(kk,-1,-1,-1,-1);
delete pdfman;
}
else
{
printAsterisks(PL_INFO, 0);
printf("NOTE: Uniform distribution is assumed for all inputs. ");
printf("To use other\n");
printf(" than uniform distributions, prescribe them in ");
printf("the sample file\n");
printf(" and set use_input_pdfs in the ANALYSIS section.\n");
printAsterisks(PL_INFO, 0);
Sampling *samPtr;
if (nInputs < 51)
samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LPTAU);
else samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LHS);
samPtr->setPrintLevel(0);
samPtr->setInputBounds(nInputs, iLowerB, iUpperB);
samPtr->setOutputParams(1);
samPtr->setSamplingParams(uaNSams, -1, -1);
samPtr->initialize(0);
vecUAOuts.setLength(uaNSams);
vecUAStas.setLength(uaNSams);
samPtr->getSamples(uaNSams,nInputs,1,vecUAInps.getDVector(),
vecUAOuts.getDVector(),vecUAStas.getIVector());
delete samPtr;
}
}
else
{
printf("Enter UA sample file name (in PSUADE data format): ");
char uaFileName[1001];
scanf("%s", uaFileName);
fgets(lineIn2, 500, stdin);
PsuadeData *sampleIO = new PsuadeData();
status = sampleIO->readPsuadeFile(uaFileName);
if (status != 0)
{
printf("ERROR: cannot read sample file.\n");
delete sampleIO;
if (faPtrsRsEval[1] == NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
return 1;
}
sampleIO->getParameter("input_ninputs", pPtr);
kk = pPtr.intData_;
if (kk != nInputs)
{
printf("ERROR: sample nInputs mismatch.\n");
printf(": input size in workspace = %d.\n",nInputs);
printf(": input size from your sample = %d.\n",kk);
delete sampleIO;
if (faPtrsRsEval[1] == NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
return 1;
}
sampleIO->getParameter("method_nsamples", pPtr);
uaNSams = pPtr.intData_;
if (uaNSams < 1000)
{
printf("ERROR: Your sample size should be at least 1000 to give\n");
printf(" any reasonable UA results.\n");
delete sampleIO;
if (faPtrsRsEval[0] == NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] == NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
return 1;
}
sampleIO->getParameter("input_sample", pPtr);
vecUAInps.load(uaNSams * nInputs, pPtr.dbleArray_);
pPtr.clean();
delete sampleIO;
}
//**/ ask for how to do UQ
int uaMethod=0;
int includeRSErr=0, numBS=1;
printf("Include response surface uncertainties in UA? (y or n) ");
scanf("%s", winput);
fgets(lineIn2, 500, stdin);
if (winput[0] == 'y')
{
includeRSErr = 1;
printf("Three options are available for including RS uncertainties:\n");
printf("1. use bootstrapping + RS (or deterministic RS, e.g. MARS)\n");
printf("2. use stochastic RS (Kriging, MARS+Bootstrap, regression)\n");
printf("3. use (2) but perform worst-case analysis (2 - average case)\n");
sprintf(pString, "Select 1, 2, or 3 : ");
uaMethod = getInt(1, 3, pString);
if (uaMethod == 1)
{
sprintf(pString, "How many bootstrapped samples to use (10 - 300) : ");
numBS = getInt(10, 300, pString);
}
}
//**/ ====================================================================
// perform UA
//**/ ====================================================================
psVector vecUAStds;
vecUAOuts.setLength(uaNSams);
vecUAStds.setLength(uaNSams);
//**/ ----------------------------------------------
// use deterministic
//**/ ----------------------------------------------
if (uaMethod == 0)
{
//**/ generate response surface
printf("** CREATING RESPONSE SURFACE FOR PRIMARY MODEL\n");
faPtrsRsEval[0] = genFA(-1, nInputs, -1, nSamples);
if (faPtrsRsEval[0] == NULL)
{
printf("ERROR: cannot generate response surface.\n");
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
faPtrsRsEval[0]->setBounds(iLowerB, iUpperB);
faPtrsRsEval[0]->setOutputLevel(0);
psConfig_.InteractiveSaveAndReset();
status = faPtrsRsEval[0]->initialize(sampleInputs,sampleOutputs);
psConfig_.InteractiveRestore();
if (status != 0)
{
printf("ERROR: cannot initialize response surface.\n");
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
//**/ evaluate response surface at the user sample points
faPtrsRsEval[0]->evaluatePoint(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector());
//**/ add discrepancy, if available
double *UAInps = vecUAInps.getDVector();
if (discFile == 1)
{
for (ss = 0; ss < uaNSams; ss++)
{
ddata = faPtrsRsEval[1]->evaluatePoint(&UAInps[ss*nInputs]);
vecUAOuts[ss] += ddata;
}
}
//**/ compute statistics
double mean=0, stdev=0;
for (ss = 0; ss < uaNSams; ss++) mean += vecUAOuts[ss];
mean /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
stdev += pow(vecUAOuts[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) uaNSams);
printAsterisks(PL_INFO, 0);
printf("Sample mean = %e (without RS uncertainties)\n", mean);
printf("Sample std dev = %e (without RS uncertainties)\n", stdev);
printEquals(PL_INFO, 0);
//**/ generate matlab file
fp = NULL;
fp = fopen("matlabrsuab2.m", "w");
if (fp != NULL)
{
fprintf(fp,"Y = [\n");
for (ss = 0; ss < uaNSams; ss++)
fprintf(fp,"%e\n",vecUAOuts[ss]);
fprintf(fp, "];\n");
fwriteHold(fp, 0);
fprintf(fp,"subplot(1,2,1);\n");
fprintf(fp,"[nk,xk] = hist(Y,50);\n");
fprintf(fp,"nk = nk / %d;\n", uaNSams);
fprintf(fp,"bar(xk,nk,1.0);\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Probability Distribution");
fwritePlotXLabel(fp,"Output Value");
fwritePlotYLabel(fp,"Probabilities");
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",
mean);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev);
fprintf(fp,"subplot(1,2,2);\n");
fprintf(fp, "Y = sort(Y);\n");
fprintf(fp, "X = (1 : %d)' / %d;\n", uaNSams, uaNSams);
fprintf(fp,"plot(Y, X, 'lineWidth',3)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Cumulative Distribution");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Cum. Prob.");
fclose(fp);
printf("Output distribution plots are in matlabrsuab2.m.\n");
}
}
//**/ ----------------------------------------------
// bootstrapped method
//**/ ----------------------------------------------
if (uaMethod == 1)
{
int bsnSams, rsMethod;
//**/ create response surface place holder
printf("** CREATING RESPONSE SURFACE FOR PRIMARY MODEL\n");
faPtrsRsEval[0] = genFA(-1, nInputs, -1, nSamples);
if (faPtrsRsEval[0] == NULL)
{
printf("ERROR: cannot generate primary response surface.\n");
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
rsMethod = faPtrsRsEval[0]->getID();
delete faPtrsRsEval[0];
faPtrsRsEval[0] = NULL;
//**/ for each bootstrap, initialize and evaluate response surface
int its;
psVector vecBsSamInps, vecBsSamOuts, vecBsMeans, vecBsStds;
vecBsSamInps.setLength(nSamples*nInputs);
vecBsSamOuts.setLength(nSamples);
vecBsMeans.setLength(numBS);
vecBsStds.setLength(numBS);
psIVector vecUseFlags;
vecUseFlags.setLength(nSamples);
fp = NULL;
fp = fopen("matlabrsbua.m", "w");
for (its = 0; its < numBS; its++)
{
for (ss = 0; ss < nSamples; ss++) vecUseFlags[ss] = 0;
//**/ generate bootstrapped sample
bsnSams = 0;
for (ss = 0; ss < nSamples; ss++)
{
jj = PSUADE_rand() % nSamples;
if (vecUseFlags[jj] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecBsSamInps[bsnSams*nInputs+ii] = sampleInputs[jj*nInputs+ii];
vecBsSamOuts[bsnSams] = sampleOutputs[jj*nOutputs+outputID];
vecUseFlags[jj] = 1;
bsnSams++;
}
}
printf("Bootstrap %d has sample size = %d (%d)\n",its+1,bsnSams,
nSamples);
//**/ initialize response surface
psConfig_.InteractiveSaveAndReset();
faPtrsRsEval[0] = genFA(rsMethod, nInputs, -1, bsnSams);
faPtrsRsEval[0]->setBounds(iLowerB, iUpperB);
faPtrsRsEval[0]->setOutputLevel(0);
status = faPtrsRsEval[0]->initialize(vecBsSamInps.getDVector(),
vecBsSamOuts.getDVector());
psConfig_.InteractiveRestore();
if (status != 0)
{
printf("ERROR: in initializing response surface (1).\n");
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
//**/ evaluate the user sample
faPtrsRsEval[0]->evaluatePoint(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector());
delete faPtrsRsEval[0];
faPtrsRsEval[0] = NULL;
//**/ add discrepancy to evaluated sample
double *UAInps = vecUAInps.getDVector();
if (discFile == 1)
{
for (ss = 0; ss < uaNSams; ss++)
{
ddata = faPtrsRsEval[1]->evaluatePoint(&UAInps[ss*nInputs]);
vecUAOuts[ss] += ddata;
}
}
//**/ compute statistics
vecBsMeans[its] = vecBsStds[its] = 0.0;
for (ss = 0; ss < uaNSams; ss++)
vecBsMeans[its] += vecUAOuts[ss];
vecBsMeans[its] /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
vecBsStds[its] += pow(vecUAOuts[ss] - vecBsMeans[its], 2.0);
vecBsStds[its] = sqrt(vecBsStds[its] / uaNSams);
if (fp != NULL)
{
fprintf(fp, "%% bootstrapped samples\n");
fprintf(fp, "Y = [\n");
for (ss = 0; ss < uaNSams; ss++) fprintf(fp,"%e\n",vecUAOuts[ss]);
fprintf(fp, "];\n");
fprintf(fp, "Y%d = sort(Y);\n",its+1);
fprintf(fp, "X%d = (1 : %d)';\n", its+1, uaNSams);
fprintf(fp, "X%d = X%d / %d;\n", its+1, its+1, uaNSams);
if (its == 0)
{
fprintf(fp, "YY = Y%d;\n", its+1);
fprintf(fp, "XX = X%d;\n", its+1);
}
else
{
fprintf(fp, "YY = [YY Y%d];\n", its+1);
fprintf(fp, "XX = [XX X%d];\n", its+1);
}
}
}
//**/ compute statistics
printAsterisks(PL_INFO, 0);
double mean, stdev;
mean = stdev = 0.0;
for (its = 0; its < numBS; its++) mean += vecBsMeans[its];
mean /= (double) numBS;
for (ss = 0; ss < numBS; ss++) stdev += pow(vecBsMeans[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) numBS);
printf("Sample mean = %e (std = %e)\n", mean, stdev);
mean = stdev = 0.0;
for (its = 0; its < numBS; its++) mean += vecBsStds[its];
mean /= (double) numBS;
for (ss = 0; ss < numBS; ss++) stdev += pow(vecBsStds[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) numBS);
printf("Sample std dev = %e (std = %e)\n", mean, stdev);
printEquals(PL_INFO, 0);
if (fp != NULL)
{
fwriteHold(fp, 0);
fprintf(fp,"subplot(1,2,1);\n");
fprintf(fp,"[nk,xk] = hist(YY,50);\n");
fprintf(fp,"plot(xk,nk, 'lineWidth',2)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Probability Distribution");
fwritePlotXLabel(fp,"Output Value");
fwritePlotYLabel(fp,"Probabilities");
fprintf(fp,"subplot(1,2,2);\n");
fprintf(fp,"plot(YY, XX, 'lineWidth',3)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Cumulative Distribution");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
printf("Output distribution plots are in matlabrsbua2.m.\n");
}
}
//**/ ----------------------------------------------
// use stochastic response surface with average case analysis
//**/ ----------------------------------------------
if (uaMethod == 2)
{
//**/ create response surface
psConfig_.InteractiveSaveAndReset();
printf("** CREATING RESPONSE SURFACE FOR PRIMARY MODEL\n");
faPtrsRsEval[0] = genFA(-1, nInputs, -1, nSamples);
if (faPtrsRsEval[0] == NULL)
{
printf("ERROR: cannot generate response surface.\n");
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
faPtrsRsEval[0]->setBounds(iLowerB, iUpperB);
faPtrsRsEval[0]->setOutputLevel(0);
status = faPtrsRsEval[0]->initialize(sampleInputs,sampleOutputs);
psConfig_.InteractiveRestore();
if (status != 0)
{
printf("ERROR: cannot initialize response surface.\n");
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
//**/ evaluate response surface
faPtrsRsEval[0]->evaluatePointFuzzy(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector(),vecUAStds.getDVector());
//**/ add discrepancy to original sample
double discSamStd, *UAInps = vecUAInps.getDVector();
if (discFile == 1)
{
for (ss = 0; ss < uaNSams; ss++)
{
vecUAOuts[ss] +=
faPtrsRsEval[1]->evaluatePointFuzzy(&UAInps[ss*nInputs],
discSamStd);
ddata = pow(vecUAStds[ss],2.0) + discSamStd * discSamStd;
vecUAStds[ss] = sqrt(ddata);
}
}
fp = fopen("rsuab2_sample","w");
if (fp != NULL)
{
fprintf(fp,"%% This file is primarily for diagnostics and\n");
fprintf(fp,"%% expert analysis\n");
fprintf(fp,"%% First line: nSamples nInputs\n");
fprintf(fp,"%% All inputs, output, output-3*sigma, output+3*sigma\n");
fprintf(fp,"%d %d 3\n", uaNSams, nInputs);
for (ss = 0; ss < uaNSams; ss++)
{
for (ii = 0; ii < nInputs; ii++)
fprintf(fp, "%e ", vecUAInps[ss*nInputs+ii]);
fprintf(fp, "%e ", vecUAOuts[ss]);
fprintf(fp, "%e ", vecUAOuts[ss]-3*vecUAStds[ss]);
fprintf(fp, "%e\n", vecUAOuts[ss]+3*vecUAStds[ss]);
}
fclose(fp);
printf("The outputs and stds of your sample has been written ");
printf("to 'rsuab2_sample'.\n");
}
//**/ first set of statistics
double mean=0, stdev=0;
for (ss = 0; ss < uaNSams; ss++) mean += vecUAOuts[ss];
mean /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
stdev += pow(vecUAOuts[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) uaNSams);
printAsterisks(PL_INFO, 0);
printf("Sample mean = %e (RS uncertainties not included)\n", mean);
printf("Sample std dev = %e (RS uncertainties not included)\n", stdev);
printEquals(PL_INFO, 0);
//**/ initialize for binning
int nbins = 100, ntimes=20;
int **Fcounts = new int*[ntimes+1];
double Fmax=-PSUADE_UNDEFINED;
double Fmin=PSUADE_UNDEFINED;
PDFNormal *rsPDF=NULL;
for (ss = 0; ss < uaNSams; ss++)
{
if (vecUAOuts[ss]+3*vecUAStds[ss] > Fmax)
Fmax = vecUAOuts[ss] + 3 * vecUAStds[ss];
if (vecUAOuts[ss]-3*vecUAStds[ss] < Fmin)
Fmin = vecUAOuts[ss] - 3 * vecUAStds[ss];
}
Fmax = Fmax + 0.1 * (Fmax - Fmin);
Fmin = Fmin - 0.1 * (Fmax - Fmin);
if (Fmax == Fmin)
{
Fmax = Fmax + 0.1 * PABS(Fmax);
Fmin = Fmin - 0.1 * PABS(Fmin);
}
for (ii = 0; ii <= ntimes; ii++)
{
Fcounts[ii] = new int[nbins];
for (kk = 0; kk < nbins; kk++) Fcounts[ii][kk] = 0;
}
//**/ generate stochastic RS and bin
double d1, d2;
psVector vecSamOutTime, vecSamOutSave;
vecSamOutTime.setLength(ntimes*nInputs);
vecSamOutSave.setLength(ntimes*uaNSams);
for (ss = 0; ss < uaNSams; ss++)
{
if (vecUAStds[ss] == 0)
{
for (ii = 0; ii < ntimes; ii++)
vecSamOutTime[ii] = vecUAOuts[ss];
}
else
{
rsPDF = new PDFNormal(vecUAOuts[ss],vecUAStds[ss]);
d1 = vecUAOuts[ss] - 3.0 * vecUAStds[ss];
d2 = vecUAOuts[ss] + 3.0 * vecUAStds[ss];
rsPDF->genSample(ntimes,vecSamOutTime.getDVector(),&d1,&d2);
delete rsPDF;
}
for (ii = 0; ii < ntimes; ii++)
vecSamOutSave[ss*ntimes+ii] = vecSamOutTime[ii];
//**/ bin the original sample
ddata = vecUAOuts[ss] - Fmin;
if (Fmax > Fmin) ddata = ddata / ((Fmax - Fmin) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ntimes][kk]++;
//**/ bin the perturbed sample
for (ii = 0; ii < ntimes; ii++)
{
ddata = vecSamOutTime[ii] - Fmin;
if (Fmax > Fmin)
ddata = ddata / ((Fmax - Fmin) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ii][kk]++;
}
}
double mean2=0, stdev2=0;
for (ss = 0; ss < uaNSams*ntimes; ss++) mean2 += vecSamOutSave[ss];
mean2 /= (double) (uaNSams*ntimes);
stdev2 = 0.0;
for (ss = 0; ss < uaNSams*ntimes; ss++)
stdev2 += pow(vecSamOutSave[ss] - mean2, 2.0);
stdev2 = sqrt(stdev2/(double) (uaNSams*ntimes));
printf("Sample mean = %e (RS uncertainties included)\n", mean2);
printf("Sample std dev = %e (RS uncertainties included)\n", stdev2);
printAsterisks(PL_INFO, 0);
//**/ write to file
fp = fopen("matlabrsuab2.m", "w");
if (fp == NULL)
{
printf("INFO: cannot write the PDFs/CDFs to matlab file.\n");
}
else
{
fwriteHold(fp, 0);
fprintf(fp, "subplot(2,2,1)\n");
fprintf(fp, "X = [\n");
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%e\n",(Fmax-Fmin)/nbins*(0.5+kk)+Fmin);
fprintf(fp, "];\n");
for (ii = 0; ii <= ntimes; ii++)
{
fprintf(fp, "N%d = [\n", ii+1);
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%d\n", Fcounts[ii][kk]);
fprintf(fp, "];\n");
}
fprintf(fp, "N = [");
for (ii = 0; ii <= ntimes; ii++)
fprintf(fp, "N%d/sum(N%d) ", ii+1, ii+1);
fprintf(fp, "];\n");
fprintf(fp, "NA = N(:,%d+1);\n",ntimes);
fprintf(fp, "NA = NA / sum(NA);\n");
fprintf(fp, "NB = sum(N(:,1:%d)');\n",ntimes);
fprintf(fp, "NB = NB' / sum(NB);\n");
fprintf(fp, "NN = [NA NB];\n");
fprintf(fp, "bar(X,NA,1.0)\n");
fprintf(fp, "ymin = min(min(NA),min(NB));\n");
fprintf(fp, "ymax = max(max(NA),max(NB));\n");
fprintf(fp, "axis([min(X) max(X) ymin ymax])\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (means of RS)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities)");
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",
mean);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev);
if (faType == PSUADE_RS_MARS)
{
printf("Deterministic RS used ==> no RS uncertainties.\n");
}
else
{
fprintf(fp,"subplot(2,2,3)\n");
fprintf(fp,"bar(X,NB,1.0)\n");
fprintf(fp,"axis([min(X) max(X) ymin ymax])\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp,"Prob. Dist. (RS with uncertainties)");
fwritePlotXLabel(fp,"Output Value");
fwritePlotYLabel(fp,"Probabilities)");
fprintf(fp,"text(0.05,0.9,'Mean = %12.4e','sc','FontSize',11)\n",
mean2);
fprintf(fp,"text(0.05,0.85,'Std = %12.4e','sc','FontSize',11)\n",
stdev2);
}
for (ii = 0; ii <= ntimes; ii++)
{
fprintf(fp,"for ii = 2 : %d\n", nbins);
fprintf(fp," N%d(ii) = N%d(ii) + N%d(ii-1);\n",ii+1,ii+1,ii+1);
fprintf(fp,"end;\n");
}
fprintf(fp, "N = [");
for (ii = 0; ii <= ntimes; ii++)
fprintf(fp,"N%d/N%d(%d) ", ii+1, ii+1, nbins);
fprintf(fp, "];\n");
fprintf(fp, "subplot(2,2,[2 4])\n");
fprintf(fp, "NA = N(:,%d+1);\n",ntimes);
fprintf(fp, "NA = NA / NA(%d);\n",nbins);
fprintf(fp, "NB = sum(N(:,1:%d)');\n",ntimes);
fprintf(fp, "NB = NB' / NB(%d);\n", nbins);
fprintf(fp, "NN = [NA NB];\n");
if (faType == PSUADE_RS_MARS)
{
fprintf(fp, "plot(X,NA,'linewidth',3)\n");
fwritePlotTitle(fp,"Cum. Dist.: (b) mean; (g) with uncertainties");
}
else
{
fprintf(fp, "plot(X,NN,'linewidth',3)\n");
fwritePlotTitle(fp,"Cum. Dist.: (*) uncertainties unavailable");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
printf("Output distribution plots are in matlabrsbua.m.\n");
}
for (ii = 0; ii <= ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
}
//**/ ----------------------------------------------
// use stochastic response surface with worst case analysis
//**/ ----------------------------------------------
if (uaMethod == 3)
{
//**/ create response surface
printf("** CREATING RESPONSE SURFACE FOR PRIMARY MODEL\n");
psConfig_.InteractiveSaveAndReset();
faPtrsRsEval[0] = genFA(-1, nInputs, -1, nSamples);
if (faPtrsRsEval[0] == NULL)
{
printf("ERROR: cannot generate response surface.\n");
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
faPtrsRsEval[0]->setBounds(iLowerB, iUpperB);
faPtrsRsEval[0]->setOutputLevel(0);
status = faPtrsRsEval[0]->initialize(sampleInputs,sampleOutputs);
psConfig_.InteractiveRestore();
if (status != 0)
{
printf("ERROR: cannot initialize response surface.\n");
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
delete sampleIO;
return 1;
}
//**/ create response surface
faPtrsRsEval[0]->evaluatePointFuzzy(uaNSams,vecUAInps.getDVector(),
vecUAOuts.getDVector(),vecUAStds.getDVector());
//**/ add discrepancy to original sample
double discSamStd, *UAInps = vecUAInps.getDVector();
if (discFile == 1)
{
for (ss = 0; ss < uaNSams; ss++)
{
vecUAOuts[ss] +=
faPtrsRsEval[1]->evaluatePointFuzzy(&UAInps[ss*nInputs],
discSamStd);
ddata = pow(vecUAStds[ss],2.0) + discSamStd * discSamStd;
vecUAStds[ss] = sqrt(ddata);
}
}
//**/ first set of statistics
double mean=0, stdev=0;
for (ss = 0; ss < uaNSams; ss++) mean += vecUAOuts[ss];
mean /= (double) uaNSams;
for (ss = 0; ss < uaNSams; ss++)
stdev += pow(vecUAOuts[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) uaNSams);
printAsterisks(PL_INFO, 0);
printf("Sample mean = %e (RS uncertainties not included)\n",mean);
printf("Sample std dev = %e (RS uncertainties not included)\n",stdev);
printEquals(PL_INFO, 0);
fp = fopen("rsuab2_sample","w");
fprintf(fp, "%% This file is primarily for diagnostics and \n");
fprintf(fp, "%% expert analysis\n");
fprintf(fp, "%% First line: nSamples nInputs\n");
fprintf(fp, "%% All inputs, output, output-3*sigma, output+3*sigma\n");
fprintf(fp, "%d %d 3\n", uaNSams, nInputs);
for (ss = 0; ss < uaNSams; ss++)
{
for (ii = 0; ii < nInputs; ii++)
fprintf(fp, "%e ", vecUAInps[ss*nInputs+ii]);
fprintf(fp, "%e ", vecUAOuts[ss]);
fprintf(fp, "%e ", vecUAOuts[ss]-3*vecUAStds[ss]);
fprintf(fp, "%e\n", vecUAOuts[ss]+3*vecUAStds[ss]);
}
fclose(fp);
//**/ initialize for binning
int nbins = 100, ntimes=7;
int **Fcounts = new int*[ntimes+1];
double Fmax=-PSUADE_UNDEFINED;
double Fmin=PSUADE_UNDEFINED;
PDFNormal *rsPDF=NULL;
for (ss = 0; ss < uaNSams; ss++)
{
if (vecUAOuts[ss]+3*vecUAStds[ss] > Fmax)
Fmax = vecUAOuts[ss] + 3 * vecUAStds[ss];
if (vecUAOuts[ss]-3*vecUAStds[ss] < Fmin)
Fmin = vecUAOuts[ss] - 3 * vecUAStds[ss];
}
Fmax = Fmax + 0.1 * (Fmax - Fmin);
Fmin = Fmin - 0.1 * (Fmax - Fmin);
if (Fmax == Fmin)
{
Fmax = Fmax + 0.1 * PABS(Fmax);
Fmin = Fmin - 0.1 * PABS(Fmin);
}
for (ii = 0; ii <= ntimes; ii++)
{
Fcounts[ii] = new int[nbins];
for (kk = 0; kk < nbins; kk++) Fcounts[ii][kk] = 0;
}
//**/ binning
for (ss = 0; ss < uaNSams; ss++)
{
for (ii = 0; ii < ntimes; ii++)
{
ddata = vecUAOuts[ss]+vecUAStds[ss]*(ii-3) - Fmin;
if (Fmax > Fmin)
ddata = ddata / ((Fmax - Fmin) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ii][kk]++;
}
}
fp = fopen("matlabrsuab2.m", "w");
if (fp == NULL)
{
printf("INFO: cannot write the PDFs/CDFs to matlab file.\n");
}
else
{
fwriteHold(fp, 0);
fprintf(fp, "%% worst case analysis\n");
fprintf(fp, "X = [\n");
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%e\n", (Fmax-Fmin)/nbins*(0.5+kk)+Fmin);
fprintf(fp, "];\n");
for (ii = 0; ii < ntimes; ii++)
{
fprintf(fp, "E%d = [\n", ii+1);
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%d\n",Fcounts[ii][kk]);
fprintf(fp, "];\n");
}
fprintf(fp, "EE = [");
for (ii = 0; ii < ntimes; ii++)
fprintf(fp, "E%d/sum(E%d) ", ii+1, ii+1);
fprintf(fp, "];\n");
fprintf(fp, "subplot(1,2,1)\n");
fprintf(fp, "plot(X,EE,'lineWidth',2)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (-3,2,1,0,1,2,3 std.)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fprintf(fp, "subplot(1,2,2)\n");
for (ii = 0; ii < ntimes; ii++)
{
fprintf(fp, "for ii = 2 : %d\n", nbins);
fprintf(fp, " E%d(ii) = E%d(ii) + E%d(ii-1);\n",ii+1,ii+1,ii+1);
fprintf(fp, "end;\n");
}
fprintf(fp, "EE = [");
for (ii = 0; ii < ntimes; ii++)
fprintf(fp, "E%d/E%d(%d) ", ii+1, ii+1, nbins);
fprintf(fp, "];\n");
fprintf(fp, "plot(X,EE,'linewidth',2)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Cum. Dist. (-3,2,1,0,1,2,3 std.)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
printf("Output distribution plots are in matlabrsuab2.m.\n");
for (ii = 0; ii < ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
}
}
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
if (sampleIO != NULL) delete sampleIO;
}
//**/ -------------------------------------------------------------
// +++ rs_ua2
//**/ uncertainty analysis on fuzzy response surface (worst case)
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs_ua2"))
{
printf("This command has been replaced by rsua or rsuab.\n");
return 0;
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs_ua2: uncertainty analysis on response surface (worst case)\n");
printf("syntax: rs_ua2 (no argument needed)\n");
printf("This command perform uncertainty analysis on the response\n");
printf("surface built from the loaded sample. If you select a\n");
printf("stochastic response surface type (Kriging, MARSB, or\n");
printf("polynomial regression, the effect of response surface\n");
printf("uncertainty will be shown on the PDF and CDF plots.\n");
printf("This is a worst case analysis in the sense that the each\n");
printf("histogram is constructed from perturbing each sample point\n");
printf("with the same fraction of its standard deviation.\n");
printf("NOTE: This analysis supports non-uniform distributions\n");
printf(" for the inputs. Simply prescribe the distributions in\n");
printf(" the data file and turn on use_input_pdfs in ANALYSIS.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
//**/ fetch sample information
Sampling *samPtr;
FuncApprox *faPtr;
PDFManager *pdfman;
psVector vecOut, vecLower, vecUpper;
psuadeIO->getParameter("ana_rstype", pPtr);
faType = pPtr.intData_;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
sprintf(pString,
"Sample size for generating distribution? (10000 - 100000) ");
int nSamp = getInt(10000, 100000, pString);
flag = 0;
printf("Save the generated sample in a file? (y or n) ");
fgets(winput,10,stdin);
if (winput[0] == 'y') flag = 1;
//**/ create response surface ==> faPtr
printf("Phase 1 of 4: create response surface\n");
printf("NOTE: the response surface type is taken from your data file.\n");
faPtr = genFA(faType, nInputs, -1, nSamples);
faPtr->setNPtsPerDim(32);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
psVector vecYT;
if (nOutputs > 1)
{
vecYT.setLength(nSamples);
for (ss = 0; ss < nSamples; ss++)
vecYT[ss] = sampleOutputs[ss*nOutputs+outputID];
}
else vecYT.load(nSamples,sampleOutputs);
faPtr->initialize(sampleInputs,vecYT.getDVector());
//**/ create a MC sample => nSamp, samInputs
printEquals(PL_INFO, 0);
printf("Phase 2 of 4: create MC sample\n");
psVector vecSamInps, vecSamOuts, vecSamStds;
vecSamInps.setLength(nSamp*nInputs);
vecSamOuts.setLength(nSamp);
vecSamStds.setLength(nSamp);
double *samInputs = new double[nInputs*nSamp];
double *samOutputs = new double[nSamp];
double *samStds = new double[nSamp];
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
int usePDFs = pPtr.intData_;
if (usePDFs == 1)
{
printf("NOTE: Some inputs have non-uniform PDFs.\n");
printf(" A MC sample will be created with these PDFs.\n");
psuadeIO->getParameter("method_sampling", pPtr);
kk = pPtr.intData_;
psuadeIO->updateMethodSection(PSUADE_SAMP_MC,-1,-1,-1,-1);
pdfman = new PDFManager();
pdfman->initialize(psuadeIO);
vecOut.setLength(nSamp*nInputs);
vecUpper.load(nInputs, iUpperB);
vecLower.load(nInputs, iLowerB);
pdfman->genSample(nSamp, vecOut, vecLower, vecUpper);
for (ii = 0; ii < nSamp*nInputs; ii++) vecSamInps[ii] = vecOut[ii];
psuadeIO->updateMethodSection(kk,-1,-1,-1,-1);
}
else
{
printf("NOTE: Uniform distributions will be used for all inputs.\n");
printf(" To use other than uniform distributions, prescribe\n");
printf(" them in the data file and set use_input_pdfs in the\n");
printf(" ANALYSIS section.\n");
psIVector vecSamStas;
vecSamStas.setLength(nSamp);
if (nInputs < 51)
samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LPTAU);
else samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LHS);
samPtr->setPrintLevel(0);
samPtr->setInputBounds(nInputs, iLowerB, iUpperB);
samPtr->setOutputParams(1);
samPtr->setSamplingParams(nSamp, -1, -1);
samPtr->initialize(0);
samPtr->getSamples(nSamp,nInputs,1,vecSamInps.getDVector(),
vecSamOuts.getDVector(),vecSamStas.getIVector());
delete samPtr;
samPtr = NULL;
}
//**/ evaluate the sample => samOutputs, samStds
printf("Phase 3 of 4: evaluate sample\n");
faPtr->evaluatePointFuzzy(nSamp,vecSamInps.getDVector(),
vecSamOuts.getDVector(),vecSamStds.getDVector());
delete faPtr;
faPtr = NULL;
if (flag == 1)
{
fp = fopen("rsua2_sample","w");
fprintf(fp, "%% inputs, output, output-3 sigma, output+3sigma\n");
fprintf(fp, "%d %d 3\n", nSamp, nInputs);
for (ss = 0; ss < nSamp; ss++)
{
for (ii = 0; ii < nInputs; ii++)
fprintf(fp, "%e ", vecSamInps[ss*nInputs+ii]);
fprintf(fp, "%e ", vecSamOuts[ss]);
fprintf(fp, "%e ", vecSamOuts[ss]-3*vecSamStds[ss]);
fprintf(fp, "%e\n", vecSamOuts[ss]+3*vecSamStds[ss]);
}
fclose(fp);
printf("A MC sample has been written to the file 'rsua2_sample'.\n");
}
//**/ compute statistics
double mean=0, stdev=0;
for (ss = 0; ss < nSamp; ss++) mean += vecSamOuts[ss];
mean /= (double) nSamp;
for (ss = 0; ss < nSamp; ss++)
stdev += pow(vecSamOuts[ss]-mean, 2.0);
stdev = sqrt(stdev/(double) nSamp);
printAsterisks(PL_INFO, 0);
printf("Sample mean = %e (RS uncertainties not included)\n", mean);
printf("Sample std dev = %e (RS uncertainties not included)\n", stdev);
printEquals(PL_INFO, 0);
printf("Phase 4 of 4: binning\n");
//**/ get the bounds for binning purposes => Fcounts
int nbins = 100, ntimes=7;
int **Fcounts = new int*[ntimes];
double Fmax=-PSUADE_UNDEFINED;
double Fmin=PSUADE_UNDEFINED;
for (ss = 0; ss < nSamp; ss++)
{
if (vecSamOuts[ss] > Fmax) Fmax = vecSamOuts[ss];
if (vecSamOuts[ss] < Fmin) Fmin = vecSamOuts[ss];
if (vecSamOuts[ss]+3*vecSamStds[ss] > Fmax)
Fmax = vecSamOuts[ss] + 3 * vecSamStds[ss];
if (vecSamOuts[ss]-3*vecSamStds[ss] < Fmin)
Fmin = vecSamOuts[ss] - 3 * vecSamStds[ss];
}
Fmax = Fmax + 0.1 * (Fmax - Fmin);
Fmin = Fmin - 0.1 * (Fmax - Fmin);
if (Fmax == Fmin)
{
Fmax = Fmax + 0.1 * PABS(Fmax);
Fmin = Fmin - 0.1 * PABS(Fmin);
}
for (ii = 0; ii < ntimes; ii++)
{
Fcounts[ii] = new int[nbins];
for (kk = 0; kk < nbins; kk++) Fcounts[ii][kk] = 0;
}
//**/ get the worst case envelope
for (ss = 0; ss < nSamp; ss++)
{
//**/ bin the samples from stochastic RS
for (ii = 0; ii < ntimes; ii++)
{
ddata = vecSamOuts[ss]+vecSamStds[ss]*(ii-3) - Fmin;
if (Fmax > Fmin)
ddata = ddata / ((Fmax - Fmin) / nbins);
else ddata = nbins / 2;
kk = (int) ddata;
if (kk < 0) kk = 0;
if (kk >= nbins) kk = nbins - 1;
Fcounts[ii][kk]++;
}
}
//**/ partial clean up : everything except Fcounts
//**/ generate matlab/scilab file
if (plotScilab())
{
fp = fopen("scilabrsua2.sci", "w");
if (fp == NULL)
{
printf("rs_ua2 ERROR: cannot open scilab file.\n");
for (ii = 0; ii < ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
return 1;
}
}
else
{
fp = fopen("matlabrsua2.m", "w");
if (fp == NULL)
{
printf("rs_ua2 ERROR: cannot open matlab file.\n");
for (ii = 0; ii < ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
return 1;
}
}
fprintf(fp, "X = [\n");
for (kk = 0; kk < nbins; kk++)
fprintf(fp, "%e\n", (Fmax-Fmin)/nbins*(0.5+kk)+Fmin);
fprintf(fp, "];\n");
fwriteHold(fp,0);
for (ii = 0; ii < ntimes; ii++)
{
fprintf(fp, "E%d = [\n", ii+1);
for (kk = 0; kk < nbins; kk++) fprintf(fp, "%d\n", Fcounts[ii][kk]);
fprintf(fp, "];\n");
}
fprintf(fp, "EE = [");
for (ii = 0; ii < ntimes; ii++)
fprintf(fp, "E%d/sum(E%d) ", ii+1, ii+1);
fprintf(fp, "];\n");
fprintf(fp, "subplot(1,2,1)\n");
fprintf(fp, "plot(X,EE,'lineWidth',2)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prob. Dist. (-3,2,1,0,1,2,3 std.)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fprintf(fp, "subplot(1,2,2)\n");
for (ii = 0; ii < ntimes; ii++)
{
fprintf(fp, "for ii = 2 : %d\n", nbins);
fprintf(fp, " E%d(ii) = E%d(ii) + E%d(ii-1);\n",ii+1,ii+1,ii+1);
fprintf(fp, "end;\n");
}
fprintf(fp, "EE = [");
for (ii = 0; ii < ntimes; ii++)
fprintf(fp, "E%d/E%d(%d) ", ii+1, ii+1, nbins);
fprintf(fp, "];\n");
fprintf(fp, "plot(X,EE,'linewidth',2)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Cum. Dist. (-3,2,1,0,1,2,3 std.)");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
if (plotScilab())
printf("Output distribution plots is in scilabrsua2.sci.\n");
else printf("Output distribution plots is in matlabrsua2.m.\n");
for (ii = 0; ii < ntimes; ii++) delete [] Fcounts[ii];
delete [] Fcounts;
}
//**/ -------------------------------------------------------------
// +++ rsuab3
//**/ RS-based UA with bootstrap and can be used with posterior
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsuab3"))
{
printf("This command has been replaced by rsua or rsuab.\n");
return 0;
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsuab3: This is a generic RS-based command that ");
printf("can accommodate a\n");
printf(" discrepancy model, a pre-generated sample ");
printf("(in a file), and\n");
printf(" bootstrapping. The sample file should ");
printf("have the following format: \n");
printf("PSUADE_BEGIN \n");
printf("<nPts> <nInputs> \n");
printf("1 <input 1> <input 2> ... \n");
printf("2 <input 1> <input 2> ... \n");
printf("...... \n");
printf("PSUADE_END \n");
printf("syntax: rs_uab (no argument needed)\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
if (nOutputs > 1)
{
printf("Currently this command does not support nOutputs > 1.\n");
printf("Use 'write' to generate a one-output data file first.\n");
return 1;
}
else
{
int discFile=1,nInps,nOuts,dnSamp,it,ind,nSamples2,*tempI, nbs;
double mean=0.0, stdev=0.0, dtemp;
double *outVals, *tempX, *tempY, *tempV, *tempW, *inputVals=NULL;
PsuadeData *localIO = NULL;
FuncApprox **faPtrsRsEval=NULL;
//**/ first set up for response surfaces (2- original and discrepancy)
outputID = 0;
faPtrsRsEval = new FuncApprox*[2];
faPtrsRsEval[0] = NULL;
faPtrsRsEval[1] = NULL;
//**/ read the discrepancy model file
printf("Enter discrepancy model PSUADE file (if none, just 'n'): ");
scanf("%s", winput);
fgets(lineIn2,500,stdin);
if (winput[0] == 'n') discFile = 0;
else
{
localIO = new PsuadeData();
status = localIO->readPsuadeFile(winput);
if (status == 0)
{
localIO->getParameter("input_ninputs", pPtr);
nInps = pPtr.intData_;
if (nInps < nInputs)
{
printf("Discrepancy model has %d inputs.\n", nInps);
printf("So the first %d inputs in the model file ",nInps);
printf("are assumed to associate with the inputs of\n");
printf("the discrepancy model.\n");
}
localIO->getParameter("output_noutputs", pPtr);
nOuts = pPtr.intData_;
if (nOuts > 1)
{
printf("The discrepancy model has nOutputs > 1.\n");
printf("This is currently not supported.\n");
delete [] faPtrsRsEval;
delete localIO;
return 1;
}
printf("** CREATING RESPONSE SURFACE FOR DISCREPANCY MODEL\n");
faPtrsRsEval[1] = genFAInteractive(localIO, 3);
delete localIO;
localIO = NULL;
}
else
{
printf("ERROR: in reading the discrepancy model file %s.\n",
winput);
discFile = 0;
delete [] faPtrsRsEval;
faPtrsRsEval = NULL;
delete localIO;
localIO = NULL;
return 1;
}
}
//**/ read the user-generated sample
printf("Enter sample file (in some standard format): ");
scanf("%s", dataFile);
fgets(lineIn2,500,stdin);
fp = fopen(dataFile, "r");
if (fp == NULL)
{
printf("ERROR: sample data file %s not found.\n", dataFile);
if (discFile == 1) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
faPtrsRsEval = NULL;
if (localIO != NULL) delete localIO;
localIO = NULL;
return 1;
}
else
{
fscanf(fp, "%s", winput);
if (strcmp(winput, "PSUADE_BEGIN"))
{
printf("ERROR: file must begin with PSUADE_BEGIN\n");
fclose(fp);
printf("File format: \n");
printf("PSUADE_BEGIN \n");
printf("<nPts> <nInputs> \n");
printf("1 <input 1> <input 2> ... \n");
printf("2 <input 1> <input 2> ... \n");
printf("...... \n");
printf("PSUADE_END \n");
delete [] faPtrsRsEval;
faPtrsRsEval = NULL;
if (localIO != NULL) delete localIO;
localIO = NULL;
return 1;
}
else
{
fscanf(fp, "%d %d", &dnSamp, &kk);
if (dnSamp <= 0)
{
printf("ERROR: invalid sample size\n");
fclose(fp);
delete [] faPtrsRsEval;
faPtrsRsEval = NULL;
if (localIO != NULL) delete localIO;
localIO = NULL;
return 1;
}
if (kk != nInputs)
{
printf("ERROR: input size does not match nInputs.\n");
printf(": input size in local memory = %d.\n",
nInputs);
printf(": input size from file = %d.\n",kk);
fclose(fp);
delete [] faPtrsRsEval;
if (localIO != NULL) delete localIO;
faPtrsRsEval = NULL;
localIO = NULL;
return 1;
}
psVector vecInpVals;
vecInpVals.setLength(dnSamp*nInputs);
inputVals = vecInpVals.getDVector();
for (jj = 0; jj < dnSamp; jj++)
{
fscanf(fp, "%d", &ind);
if (ind != (jj+1))
{
printf("ERROR: input index mismatch (%d,%d)\n",jj+1,ind);
printf(" read index = %d\n", ind);
printf(" expected index = %d\n", jj+1);
printf("File format: \n");
printf("PSUADE_BEGIN \n");
printf("<nPts> <nInputs> \n");
printf("1 <input 1> <input 2> ... \n");
printf("2 <input 1> <input 2> ... \n");
printf("...... \n");
printf("PSUADE_END \n");
delete [] faPtrsRsEval;
if (localIO != NULL) delete localIO;
faPtrsRsEval = NULL;
localIO = NULL;
fclose(fp);
return 1;
}
for (ii = 0; ii < nInputs; ii++)
fscanf(fp, "%lg", &(inputVals[jj*nInputs+ii]));
}
if (jj != dnSamp)
{
fscanf(fp, "%s", winput);
fscanf(fp, "%s", winput);
if (strcmp(winput, "PSUADE_END"))
{
fclose(fp);
printf("ERROR: file must end with PSUADE_END\n");
delete [] faPtrsRsEval;
if (localIO != NULL) delete localIO;
faPtrsRsEval = NULL;
localIO = NULL;
return 1;
}
}
fclose(fp);
}
//**/ set up for iterations
sprintf(pString, "How many bootstrapped samples to use (10 - 300) : ");
nbs = getInt(1, 300, pString);
printf("Write the CDFs to a matlab/scilab file? (y or n) ");
scanf("%s", winput);
fgets(lineIn,500,stdin);
flag = 0;
fp = NULL;
if (winput[0] == 'y')
{
if (dnSamp > 50000)
{
printf("INFO: sample size %d too large (>50000) for matlab\n",
dnSamp);
printf(" plot. CDF plots not to be generated.\n");
}
else
{
flag = 1;
if (plotScilab())
{
fp = fopen("scilabrsuab_cdf.sci", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file.\n");
flag = 0;
}
else
{
fprintf(fp, "// CDFs for rs_uab\n");
fwritePlotCLF(fp);
}
}
else
{
fp = fopen("matlabrsuab_cdf.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file.\n");
flag = 0;
}
else
{
fprintf(fp, "%% CDFs for rs_uab\n");
fwritePlotCLF(fp);
}
}
}
}
//**/ iterate
if (nbs == 1) nSamples2 = nSamples;
else
{
nSamples2 = (int) (0.9 * nSamples);
if ((double) nSamples2 / (double) nSamples < 0.9) nSamples2++;
}
faPtrsRsEval[0] = genFA(-1, nInputs, -1, nSamples2);
if (faPtrsRsEval[0] == NULL)
{
printf("ERROR: cannot generate response surface.\n");
delete [] faPtrsRsEval;
faPtrsRsEval = NULL;
if (localIO != NULL) delete localIO;
localIO = NULL;
return 1;
}
faPtrsRsEval[0]->setBounds(iLowerB, iUpperB);
faPtrsRsEval[0]->setOutputLevel(0);
psVector vecOutVals, vecXT, vecYT, vecWT, vecVT;
psIVector vecIT;
vecOutVals.setLength(dnSamp);
vecXT.setLength(nSamples*nInputs);
vecYT.setLength(nSamples);
vecWT.setLength(nbs);
vecVT.setLength(nbs);
for (it = 0; it < nbs; it++)
{
printf("rs_uab: ITERATION %d\n", it+1);
//**/ random draw
if (nbs == 1)
{
for (jj = 0; jj < nSamples*nInputs; jj++)
vecXT[jj] = sampleInputs[jj];
for (jj = 0; jj < nSamples; jj++)
vecYT[jj] = sampleOutputs[jj*nOutputs+outputID];
}
else
{
for (jj = 0; jj < nSamples; jj++) vecIT[jj] = 0;
kk = 0;
while (kk < nSamples2)
{
ind = PSUADE_rand() % nSamples;
if (vecIT[ind] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecXT[kk*nInputs+ii] = sampleInputs[ind*nInputs+ii];
vecYT[kk] = sampleOutputs[ind*nOutputs+outputID];
vecIT[ind] = 1;
kk++;
}
}
}
//**/ add discrepancy to sample
if (discFile == 1)
{
for (jj = 0; jj < nSamples2; jj++)
{
double *tx = vecXT.getDVector();
dtemp = faPtrsRsEval[1]->evaluatePoint(tx);
vecYT[jj] += dtemp;
}
}
//**/ generate response surface
status = faPtrsRsEval[0]->initialize(vecXT.getDVector(),
vecYT.getDVector());
//**/ evaluate the response surface using the user example
faPtrsRsEval[0]->evaluatePoint(dnSamp, inputVals,
vecOutVals.getDVector());
mean = stdev = 0.0;
for (jj = 0; jj < dnSamp; jj++) mean += vecOutVals[jj];
mean /= (double) dnSamp;
for (jj = 0; jj < dnSamp; jj++)
stdev += pow(vecOutVals[jj] - mean, 2.0);
stdev = sqrt(stdev / dnSamp);
vecVT[it] = mean;
vecWT[it] = stdev;
if (fp != NULL && flag == 1)
{
fprintf(fp, "Y = [\n");
for (jj = 0; jj < dnSamp; jj++)
fprintf(fp,"%e\n",vecOutVals[jj]);
fprintf(fp, "];\n");
fprintf(fp, "Y%d = sort(Y);\n",it+1);
fprintf(fp, "X%d = (1 : %d)';\n", it+1, dnSamp);
fprintf(fp, "X%d = X%d / %d;\n", it+1, it+1, dnSamp);
if (it == 0)
{
fprintf(fp, "YY = Y%d;\n", it+1);
fprintf(fp, "XX = X%d;\n", it+1);
}
else
{
fprintf(fp, "YY = [YY Y%d];\n", it+1);
fprintf(fp, "XX = [XX X%d];\n", it+1);
}
}
}
if (fp != NULL)
{
fprintf(fp, "plot(YY, XX, 'lineWidth',3)\n");
fwritePlotTitle(fp, "Cumulative Distribution");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
if (plotScilab())
printf("rs_uab: scilabrsuab_cdf.sci has the CDF plots.\n");
else printf("rs_uab: matlabrsuab_cdf.m has the CDF plots.\n");
}
delete faPtrsRsEval[0];
faPtrsRsEval[0] = NULL;
if (discFile == 1) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
faPtrsRsEval = NULL;
if (it == nbs && nbs > 1)
{
mean = 0.0;
for (jj = 0; jj < nbs; jj++) mean += vecVT[jj];
mean /= (double) nbs;
for (jj = 0; jj < nbs; jj++)
stdev += pow(vecVT[jj] - mean, 2.0);
stdev = sqrt(stdev / nbs);
printf("rs_uab: Sample Mean = %e (%e)\n", mean, stdev);
mean = 0.0;
for (jj = 0; jj < nbs; jj++) mean += vecWT[jj];
mean /= (double) nbs;
for (jj = 0; jj < nbs; jj++)
stdev += pow(vecWT[jj] - mean, 2.0);
stdev = sqrt(stdev / nbs);
printf("rs_uab: Sample Stdev = %e (%e)\n", mean, stdev);
}
else if (kk == nbs && nbs == 1)
{
printf("rs_uab: Sample Mean = %e\n", vecVT[0]);
printf("rs_uab: Sample Stdev = %e\n", vecWT[0]);
}
}
}
}
//**/ -------------------------------------------------------------
// +++ rsuap
//**/ RS-based UA with posterior sample
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsuap_disable"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsuap: This command is similar to 'rsua' except that ");
printf("it is especially\n");
printf(" made for uncertainty analyis using a ");
printf("posterior sample (e.g.\n");
printf(" MCMCPostSample) and optionally a discrepancy model ");
printf("produced by\n");
printf(" the 'rsmcmc' command.\n");
printf("Syntax: rsuap (no argument needed)\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
if (nOutputs > 1)
{
printf("Currently this command does not support nOutputs > 1.\n");
printf("Use 'write' to choose one output for processing.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("* Response surface-based Post-MCMC Uncertainty Analysis\n");
printDashes(PL_INFO, 0);
printf("This command is similar to 'rsua' except that ");
printf("it is especially made for\n");
printf("uncertainty analyis using a posterior sample ");
printf("(e.g. MCMCPostSample) and\n");
printf("optionally a discrepancy model produced by 'rsmcmc'.\n");
printAsterisks(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ construct response surface
int discFile=1, nInps, nOuts, faFlag;
FuncApprox **faPtrsRsEval=NULL;
PsuadeData *localIO=NULL;
faFlag = 3;
psuadeIO->getParameter("ana_outputid", pPtr);
kk = pPtr.intData_;
outputID = 0;
faPtrsRsEval = new FuncApprox*[2];
psuadeIO->updateAnalysisSection(-1, -1, -1, -1, outputID, -1);
faPtrsRsEval[0] = genFAInteractive(psuadeIO, faFlag);
faPtrsRsEval[1] = NULL;
psuadeIO->updateAnalysisSection(-1, -1, -1, -1, kk, -1);
//**/ read the discrepancy model file
printf("Enter discrepancy model PSUADE file (if none, enter NONE): ");
scanf("%s", winput);
fgets(lineIn2,500,stdin);
if (!strcmp(winput, "NONE") || !strcmp(winput,"none") ||
winput[0] == 'n') discFile = 0;
else
{
localIO = new PsuadeData();
status = localIO->readPsuadeFile(winput);
if (status == 0)
{
localIO->getParameter("input_ninputs", pPtr);
nInps = pPtr.intData_;
if (nInps < nInputs)
{
printf("Discrepancy model has %d inputs.\n", nInps);
printf("So the first %d inputs in the model file ",nInps);
printf("are assumed to associate with the inputs of\n");
printf("the discrepancy model.\n");
}
localIO->getParameter("output_noutputs", pPtr);
nOuts = pPtr.intData_;
if (nOuts > 1)
{
printf("The discrepancy model has nOutputs > 1.\n");
printf("This is currently not supported.\n");
delete localIO;
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
delete [] faPtrsRsEval;
return 1;
}
printf("** CREATING RESPONSE SURFACE FOR DISCREPANCY MODEL\n");
faPtrsRsEval[1] = genFAInteractive(localIO, 3);
delete localIO;
}
else
{
printf("ERROR: in reading the discrepancy model file %s.\n",
winput);
discFile = 0;
delete localIO;
delete faPtrsRsEval[0];
delete [] faPtrsRsEval;
return 1;
}
localIO = NULL;
}
//**/ read the sample
int dnInps, dnSamp, ind;
double *inputVals=NULL;
char dataFile[1001];
psVector vecInpVals, vecOutVals;
printf("Enter sample file (in iread format): ");
scanf("%s", dataFile);
fgets(lineIn2,500,stdin);
fp = fopen(dataFile, "r");
if (fp == NULL)
{
printf("ERROR: sample data file %s not found.\n", dataFile);
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
return 1;
}
else
{
fscanf(fp, "%s", winput);
if (strcmp(winput, "PSUADE_BEGIN"))
{
printf("INFO: no first line found with PSUADE_BEGIN\n");
fclose(fp);
fp = fopen(dataFile, "r");
}
while (1)
{
kk = getc(fp);
if (kk != '#')
{
ungetc(kk, fp);
break;
}
}
fscanf(fp, "%d %d", &dnSamp, &dnInps);
if (dnSamp <= 0)
{
printf("ERROR: invalid sample size\n");
fclose(fp);
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
return 1;
}
printf("Sample size read = %d\n", dnSamp);
if (dnInps != nInputs)
{
printf("ERROR: input size does not match nInputs.\n");
printf(": input size in local memory = %d.\n",nInputs);
printf(": input size from file = %d.\n",dnInps);
fclose(fp);
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
return 1;
}
fgets(lineIn2, 500, fp);
while (1)
{
kk = getc(fp);
if (kk != '#')
{
ungetc(kk, fp);
break;
}
else fgets(lineIn2, 500, fp);
}
vecInpVals.setLength(dnSamp*dnInps);
vecOutVals.setLength(dnSamp);
inputVals = vecInpVals.getDVector();
for (jj = 0; jj < dnSamp; jj++)
{
fscanf(fp, "%d", &ind);
if (ind != (jj+1))
{
printf("ERROR: input index mismatch (%d,%d)\n",jj+1,ind);
printf(" read index = %d\n", ind);
printf(" expected index = %d\n", jj+1);
if (faPtrsRsEval[0] != NULL) delete faPtrsRsEval[0];
if (faPtrsRsEval[1] != NULL) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
return 1;
}
for (ii = 0; ii < nInputs; ii++)
fscanf(fp, "%lg", &(inputVals[jj*dnInps+ii]));
}
fgets(lineIn2, 500, fp);
fscanf(fp, "%s", winput);
if (strcmp(winput, "PSUADE_END"))
printf("INFO: PSUADE_END not found as the last line\n");
fclose(fp);
}
//**/ now the sample has been read (inputVals, dnSamp)
//**/ the response surface is ready (faPtrsRsEval[0])
//**/ the discrepancy response surface is ready (faPtrsRsEval[1])
faPtrsRsEval[0]->evaluatePoint(dnSamp, inputVals,
vecOutVals.getDVector());
if (discFile == 1)
{
for (jj = 0; jj < dnSamp; jj++)
{
ddata = faPtrsRsEval[1]->evaluatePoint(&inputVals[jj*nInputs]);
vecOutVals[jj] += ddata;
}
}
double mean=0.0, stdev=0.0;
for (ss = 0; ss < dnSamp; ss++) mean += vecOutVals[ss];
mean /= (double) dnSamp;
for (ss = 0; ss < dnSamp; ss++) stdev += pow(vecOutVals[ss]-mean,2.0);
stdev = sqrt(stdev / dnSamp);
if (plotScilab())
{
fp = fopen("scilabrsuap.sci", "w");
if (fp == NULL)
printf("rsuap ERROR: cannot open scilabrsuap.sci file.\n");
}
else
{
fp = fopen("matlabrsuap.m", "w");
if (fp == NULL)
printf("rsuap ERROR: cannot open matlabrsuap.m file.\n");
}
if (fp != NULL)
{
fprintf(fp, "Y = [ \n");
for (jj = 0; jj < dnSamp; jj++)
fprintf(fp, "%16.8e\n", vecOutVals[jj]);
fprintf(fp, "];\n");
if (plotScilab())
{
fprintf(fp, "histplot(10, Y, style=2);\n");
fprintf(fp, "a = gce();\n");
fprintf(fp, "a.children.fill_mode = \"on\";\n");
fprintf(fp, "a.children.thickness = 2;\n");
fprintf(fp, "a.children.foreground = 0;\n");
fprintf(fp, "a.children.background = 2;\n");
}
else
{
fprintf(fp, "[nk,xk]=hist(Y,10);\n");
fprintf(fp, "bar(xk,nk/%d,1.0)\n",dnSamp);
}
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Probability Distribution");
fwritePlotXLabel(fp, "Output Value");
fwritePlotYLabel(fp, "Probabilities");
fclose(fp);
if (plotScilab())
printf("rsuap: distribution in scilabrsuap.sci\n");
else printf("rsuap: distribution in matlabrsuap.m.\n");
printAsterisks(PL_INFO, 0);
printf("** Summary Statistics\n");
printEquals(PL_INFO, 0);
printf("** Sample mean = %e\n", mean);
printf("** Sample stdev = %e\n", stdev);
printAsterisks(PL_INFO, 0);
delete faPtrsRsEval[0];
if (discFile == 1) delete faPtrsRsEval[1];
delete [] faPtrsRsEval;
faPtrsRsEval = NULL;
}
}
//**/ -------------------------------------------------------------
// several qsa methods
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs_qsa"))
{
printf("This command has been replaced by rsmeb, rssobol1b and\n");
printf("rssoboltsib.\n");
return 0;
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs_qsa: RS-based quantitative sensitivity analysis\n");
printf("Syntax: rs_qsa (no argument needed)\n");
printf("Note: to facilitate processing, all expert modes have\n");
printf(" been suppressed.\n");
printf("Note: This command differs from rssobol1, rssoboltsi,\n");
printf(" and the command 'me' in that it uses bootstrapped\n");
printf(" samples multiple times to get the errors in Sobol'\n");
printf(" indices due to response surface errors.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command computes first-order sensitivity ");
printf("indices using the\n");
printf("response surface constructed from the loaded ");
printf("sample (with bootstrapping).\n");
printf("This is an alternative to rssobol1b (for cross-checking).\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ get output information
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
//**/ set up analysis manager
printf("Which main or total effect analyzer ? \n");
printf("1. Sobol' main effect using McKay's method (replicated LH).\n");
printf("2. Sobol' main effect method using on numerical integration. \n");
printf("3. Sobol' total sensitivity using numerical integration.\n");
sprintf(pString, "Which method (1, 2, or 3) ? ");
int method = getInt(1, 3, pString);
int analysisMethod, iOne=1;
if (method == 1) analysisMethod = PSUADE_ANA_ME;
else if (method == 2) analysisMethod = PSUADE_ANA_RSSOBOL1;
else if (method == 3) analysisMethod = PSUADE_ANA_RSSOBOLTSI;
AnalysisManager *anaManager = new AnalysisManager();
anaManager->setup(analysisMethod, 0);
//**/ set up MARS response surface
FuncApprox *faPtr;
if (method == 1)
{
faType = -1;
faPtr = genFA(faType, nInputs, iOne, nSamples);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(0);
}
//**/ save parameters resident in psuadeIO (to be restored later)
psuadeIO->getParameter("ana_diagnostics",pPtr);
int saveDiag = pPtr.intData_;
psuadeIO->updateAnalysisSection(-1,-1,-1,-1,-1,-1);
psConfig_.AnaExpertModeSaveAndReset();
psuadeIO->getParameter("method_sampling", pPtr);
int saveMethod = pPtr.intData_;
//**/ set up storage for the response surface samples
int usePDFs, ind, count2=100000, nReps=200;
Sampling *sampPtr;
psVector vecUpper, vecLower, vecOut;
psVector vecMT, vecVT, vecXT, vecYT, vecTT;
psIVector vecIT, vecST;
vecMT.setLength(nSamples*nInputs);
vecVT.setLength(nSamples*nInputs);
vecXT.setLength(count2*nInputs);
vecYT.setLength(count2);
vecST.setLength(nSamples);
vecIT.setLength(count2);
for (ii = 0; ii < count2*nInputs; ii++) vecXT[ii] = 0.0;
for (ii = 0; ii < count2; ii++) vecYT[ii] = 0.0;
for (ii = 0; ii < count2; ii++) vecIT[ii] = 1;
//**/ set up for iterations
sprintf(pString, "How many times to run it (10 - 1000) : ");
int count = getInt(10, 1000, pString);
vecTT.setLength(count*nInputs);
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
usePDFs = pPtr.intData_;
PDFManager *pdfman = NULL;
if (usePDFs == 1 && method == 1)
{
printf("NOTE: Some inputs have non-uniform distributions.\n");
pdfman = new PDFManager();
pdfman->initialize(psuadeIO);
vecOut.setLength(count2*nInputs);
vecUpper.load(nInputs, iUpperB);
vecLower.load(nInputs, iLowerB);
}
//**/ iterate
for (kk = 0; kk < count; kk++)
{
printf("rq_qsa: ITERATION %d\n", kk+1);
//**/ random draw
for (ss = 0; ss < nSamples; ss++)
{
ind = PSUADE_rand() % nSamples;
for (ii = 0; ii < nInputs; ii++)
vecMT[ss*nInputs+ii] = sampleInputs[ind*nInputs+ii];
vecVT[ss] = sampleOutputs[ind*nOutputs+outputID];
vecST[ss] = sampleStates[ss];
}
//**/ only for McKay's main effect, not rssobol1 and others
if (method == 1)
{
//**/ use sample to create a response surface
status = faPtr->initialize(vecMT.getDVector(),vecVT.getDVector());
//**/ generate a LH sample
sampPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LHS);
sampPtr->setPrintLevel(0);
sampPtr->setInputBounds(nInputs, iLowerB, iUpperB);
sampPtr->setOutputParams(1);
sampPtr->setSamplingParams(count2, nReps, 1);
sampPtr->initialize(0);
sampPtr->getSamples(count2,nInputs,1,vecXT.getDVector(),
vecYT.getDVector(), vecIT.getIVector());
//**/ if use_input_pdfs set in analysis section
if (usePDFs == 1)
{
pdfman->invCDF(count2, vecXT, vecOut, vecLower, vecUpper);
vecXT = vecOut;
}
//**/ evaluate the LH sample
faPtr->evaluatePoint(count2,vecXT.getDVector(),vecXT.getDVector());
//**/ write the LH sample into a PsuadeData object
psuadeIO->updateInputSection(count2,nInputs,NULL,NULL,NULL,
vecXT.getDVector(),NULL,NULL,NULL,NULL,NULL);
psuadeIO->updateOutputSection(count2,1,vecYT.getDVector(),
vecIT.getIVector(),NULL);
psuadeIO->updateMethodSection(PSUADE_SAMP_LHS,count2,
nReps,-1,-1);
}
else
{
psuadeIO->updateInputSection(nSamples,nInputs,NULL,NULL,
NULL,vecMT.getDVector(),NULL,NULL,NULL,NULL,NULL);
psuadeIO->updateOutputSection(nSamples,1,vecVT.getDVector(),
vecST.getIVector(), outputNames);
psuadeIO->updateMethodSection(PSUADE_SAMP_MC,nSamples,
-1,-1,-1);
}
//**/ analyze the result
anaManager->analyze(psuadeIO, 0, NULL, 0);
pData *pdata = psuadeIO->getAuxData();
if (pdata->nDbles_ != nInputs)
{
printf("ERROR: nInputs do not match (%d, %d).\n",
pdata->nDbles_, nInputs);
printf(" Consult PSUADE developers.\n");
if (method == 1) delete sampPtr;
return 1;
}
//**/ get the statistics
if (pdata->dbleData_ > 0)
for (ii = 0; ii < nInputs; ii++)
vecTT[kk*nInputs+ii] =
pdata->dbleArray_[ii]/pdata->dbleData_;
else
for (ii = 0; ii < nInputs; ii++)
vecTT[kk*nInputs+ii] = pdata->dbleArray_[ii];
//**/ clean up
pdata->clean();
if (method == 1) delete sampPtr;
}
if (usePDFs == 1 && method == 1) delete pdfman;
vecMT.setLength(nInputs);
for (ii = 0; ii < nInputs; ii++)
{
vecMT[ii] = vecTT[ii];
for (jj = 1; jj < count; jj++) vecMT[ii] += vecTT[jj*nInputs+ii];
vecMT[ii] /= (double) count;
}
vecVT.setLength(nInputs);
for (ii = 0; ii < nInputs; ii++)
{
vecVT[ii] = pow(vecTT[ii]-vecMT[ii], 2.0);
for (jj = 1; jj < count; jj++)
vecVT[ii] += pow(vecTT[jj*nInputs+ii]-vecMT[ii],2.0);
vecVT[ii] /= (double) (count - 1);
vecVT[ii] = sqrt(vecVT[ii]);
}
printEquals(PL_INFO, 0);
printf("Statistics (based on %d replications): \n", count);
for (ii = 0; ii < nInputs; ii++)
printf("Input %4d: mean = %16.8e, std = %16.8e\n",ii+1,
vecMT[ii],vecVT[ii]);
delete anaManager;
if (faPtr != NULL) delete faPtr;
//**/ restore previous settings
psuadeIO->updateInputSection(nSamples,nInputs,NULL,NULL,NULL,
sampleInputs,NULL,NULL,NULL,NULL,NULL);
psuadeIO->updateOutputSection(nSamples,nOutputs,sampleOutputs,
sampleStates,outputNames);
psuadeIO->updateMethodSection(saveMethod,nSamples,-1,-1,-1);
psuadeIO->updateAnalysisSection(-1,-1,-1,saveDiag,-1,-1);
psConfig_.AnaExpertModeRestore();
}
//**/ -------------------------------------------------------------
// +++ rs1
//**/ generate response surface of any one inputs and write the
//**/ grid data to file for display with matlab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs1"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs1: response surface plot in one parameter\n");
printf("syntax: rs1 (no argument needed)\n");
return 1;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
if (plotMatlab())
printf("This command creates a Matlab 2D plot (1 input/1 output).\n");
else
printf("This command creates a Scilab 2D plot (1 input/1 output).\n");
printf("The selected input will be in the X axis.\n");
printf("The selected output will be in the Y axis.\n");
printf("The other inputs are set at their midpoints or user-specified.\n");
printf("You will be asked to select a response surface type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ set up the function approximator
int nPtsPerDim = 256;
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
int iplot1, iInd1, jplot, sInd;
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
if (nInputs > 1)
{
sprintf(pString,"Set other inputs at their mid points? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1)
{
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
}
jplot = 0;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
//**/ generate 1D data
int faLeng=0;
double *faXOut=NULL, *faYOut=NULL;
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
faPtr->gen1DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,
vecInpSettings.getDVector(), &faLeng, &faXOut,&faYOut);
//**/ write to scilab file
if (plotScilab())
{
fp = fopen("scilabrs1.sci", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file scilabrs1.sci.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
fwritePlotCLF(fp);
if (nInputs == 1)
{
fprintf(fp, "XX = [\n");
for (sInd = 0; sInd < nSamples; sInd++)
fprintf(fp, "%e\n", sampleInputs[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "YY = [\n");
for (sInd = 0; sInd < nSamples; sInd++)
fprintf(fp, "%e\n", vecFaYIn[sInd]);
fprintf(fp, "];\n");
}
fprintf(fp, "A = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faYOut[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "X = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faXOut[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "plot(X,A,'-')\n");
fprintf(fp, "a = gca();\n");
fprintf(fp, "a.children.children.thickness = 4;\n");
if (nInputs == 1)
{
fwriteHold(fp,1);
fprintf(fp,"plot(XX,YY,'*');\n");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, outputNames[jplot]);
sprintf(winput, "Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fclose(fp);
printf("scilabrs1.sci is now available.\n");
}
else
{
//**/ write to matlab file
fp = fopen("matlabrs1.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrs1.m.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
fwritePlotCLF(fp);
if (nInputs == 1)
{
fprintf(fp, "XX = [\n");
for (sInd = 0; sInd < nSamples; sInd++)
fprintf(fp, "%e\n", sampleInputs[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "YY = [\n");
for (sInd = 0; sInd < nSamples; sInd++)
fprintf(fp, "%e\n", vecFaYIn[sInd]);
fprintf(fp, "];\n");
}
fprintf(fp, "A = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faYOut[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "X = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faXOut[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "plot(X,A,'-','lineWidth',4)\n");
fprintf(fp, "hold on\n");
double Ymin = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] < Ymin) Ymin = faYOut[sInd];
double Ymax = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] > Ymax) Ymax = faYOut[sInd];
printf("Ymin and Ymax found = %e %e.\n", Ymin, Ymax);
printf("You can set thresholds to cut out certain regions.\n");
sprintf(pString,"Set lower threshold for output? (y or n) : ");
getString(pString, winput);
fprintf(fp, "yminFlag = 0;\n");
double thresh;
if (winput[0] == 'y')
{
sprintf(pString,"Enter the lower threshold (min = %e) : ",
Ymin);
thresh = getDouble(pString);
fprintf(fp, "ymin = %e;\n", thresh);
fprintf(fp, "plot(X,ones(%d,1)*ymin,'r-')\n",faLeng);
}
sprintf(pString,"Set upper threshold for output? (y or n) : ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the upper threshold (max = %e) : ",
Ymax);
thresh = getDouble(pString);
fprintf(fp, "ymax = %e;\n", thresh);
fprintf(fp, "plot(X,ones(%d,1)*ymax,'r-')\n",faLeng);
}
if (nInputs == 1)
{
fwriteHold(fp,1);
fprintf(fp,"plot(XX,YY,'k*','markersize',13);\n");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, outputNames[jplot]);
sprintf(winput, "Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fclose(fp);
printf("matlabrs1.m is now available.\n");
}
delete [] faXOut;
delete [] faYOut;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rs1s
//**/ generate response surface of any one inputs and write the
//**/ grid data to file for display with matlab (include uncertainties)
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs1s"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs1s: 1-parameter response surface (with uncertainty) plot\n");
printf("Syntax: rs1s (no argument needed)\n");
return 1;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
if (plotMatlab())
printf("Create a Matlab plot (1 input + output with uncertainty).\n");
else printf("Create a Scilab plot (1 input + output with uncertainty).\n");
printEquals(PL_INFO, 0);
//**/ set up the function approximator
int nPtsPerDim = 128;
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
int iplot1, iInd1, jplot, sInd;
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
if (nInputs > 1)
{
sprintf(pString,"Set other inputs at their mid points? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1)
{
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
}
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
//**/ generate 1D data
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
faPtr->initialize(sampleInputs,vecFaYIn.getDVector());
double hx = (iUpperB[iplot1]-iLowerB[iplot1])/(double) (nPtsPerDim-1.0);
psVector vecFaXOut, vecFaYOut, vecFaYStd;
vecFaXOut.setLength(nPtsPerDim*nInputs);
for (ii = 0; ii < nPtsPerDim; ii++)
{
for (jj = 0; jj < nInputs; jj++)
vecFaXOut[ii*nInputs+jj] = vecInpSettings[jj];
vecFaXOut[ii*nInputs+iplot1] = hx * ii + iLowerB[iplot1];
}
vecFaYOut.setLength(nPtsPerDim);
vecFaYStd.setLength(nPtsPerDim);
faPtr->evaluatePointFuzzy(nPtsPerDim, vecFaXOut.getDVector(),
vecFaYOut.getDVector(),vecFaYStd.getDVector());
//**/ write to scilab file
if (plotScilab())
{
fp = fopen("scilabrs1s.sci", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file scilabrs1s.sci.\n");
delete faPtr;
return 1;
}
fwritePlotCLF(fp);
fprintf(fp, "A = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%16.8e %16.8e\n", vecFaYOut[sInd], vecFaYStd[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "X = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%e\n", vecFaXOut[sInd*nInputs+iplot1]);
fprintf(fp, "];\n");
fprintf(fp, "plot(X,A(:,1),'k-')\n");
fprintf(fp, "a = gca();\n");
fprintf(fp, "a.children.children.thickness = 4;\n");
fwriteHold(fp, 1);
fprintf(fp, "for ii = 1 : %d\n", nPtsPerDim);
fprintf(fp, " xx = [X(ii) X(ii)];\n");
fprintf(fp, " yy = [A(ii,1)-2*A(ii,2) A(ii,1)+2*A(ii,2)];\n");
fprintf(fp, " plot(xx,yy,'b-','lineWidth',1)\n");
fprintf(fp, "end\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, outputNames[jplot]);
sprintf(winput, "Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fclose(fp);
printf("scilabrs1s.sci is now available.\n");
}
else
{
//**/ write to matlab file
fp = fopen("matlabrs1s.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrs1s.m.\n");
delete faPtr;
return 1;
}
fwritePlotCLF(fp);
fprintf(fp, "%% 1D plot with +/- 2 std dev\n");
fprintf(fp, "A = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%16.8e %16.8e\n", vecFaYOut[sInd], vecFaYStd[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "X = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%e\n", vecFaXOut[sInd*nInputs+iplot1]);
fprintf(fp, "];\n");
fprintf(fp, "plot(X,A(:,1),'-','lineWidth',4)\n");
fprintf(fp, "hold on\n");
fprintf(fp, "for ii = 1 : %d\n", nPtsPerDim);
fprintf(fp, " xx = [X(ii) X(ii)];\n");
fprintf(fp, " yy = [A(ii,1)-2*A(ii,2) A(ii,1)+2*A(ii,2)];\n");
fprintf(fp, " plot(xx,yy,'b-','lineWidth',1)\n");
fprintf(fp, "end\n");
double Ymin = vecFaYOut[0];
for (sInd = 1; sInd < nPtsPerDim; sInd++)
if (vecFaYOut[sInd] < Ymin) Ymin = vecFaYOut[sInd];
double Ymax = vecFaYOut[0];
for (sInd = 1; sInd < nPtsPerDim; sInd++)
if (vecFaYOut[sInd] > Ymax) Ymax = vecFaYOut[sInd];
printf("Ymin and Ymax found = %e %e.\n", Ymin, Ymax);
printf("You can set thresholds to cut out certain regions.\n");
sprintf(pString,"Set lower threshold for output? (y or n) : ");
getString(pString, winput);
fprintf(fp, "yminFlag = 0;\n");
double thresh;
if (winput[0] == 'y')
{
sprintf(pString,"Enter the lower threshold (min = %e) : ",
Ymin);
thresh = getDouble(pString);
fprintf(fp, "ymin = %e;\n", thresh);
fprintf(fp, "plot(X,ones(%d,1)*ymin,'r-')\n",nPtsPerDim);
}
sprintf(pString,"Set upper threshold for output? (y or n) : ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the upper threshold (max = %e) : ",
Ymax);
thresh = getDouble(pString);
fprintf(fp, "ymax = %e;\n", thresh);
fprintf(fp, "plot(X,ones(%d,1)*ymax,'r-')\n",nPtsPerDim);
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, outputNames[jplot]);
sprintf(winput, "Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fclose(fp);
printf("matlabrs1s.m is now available.\n");
}
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rs2
//**/ generate response surface of any two inputs and write the
//**/ grid data to file for display with matlab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs2"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs2: response surface plot in two parameters\n");
printf("syntax: rs2 (no argument needed)\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
if (nInputs < 2)
{
printf("ERROR: rs2 requires 2 or more inputs.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
if (plotMatlab())
printf("This command creates a Matlab 3D plot (2 inputs/1 output).\n");
else
printf("This command creates a Scilab 3D plot (2 inputs/1 output).\n");
printf("The selected inputs will be in the X and Y axes.\n");
printf("The selected output will be in the Z axis.\n");
printf("The other inputs are set at their midpoints or user-specified.\n");
printf("You will be asked to select a response surface type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ set up the function approximator
int nPtsPerDim = 64;
sprintf(pString, "Grid resolution ? (32 - 256) ");
nPtsPerDim = getInt(32, 256, pString);
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
int iplot1, iplot2, iInd1, sInd, jplot;
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
sprintf(pString, "Enter the input for y axis (1 - %d) : ", nInputs);
iplot2 = getInt(1, nInputs, pString);
iplot2--;
int p2cnt=1;
if (iplot1 != iplot2) p2cnt++;
if (nInputs-p2cnt > 0)
{
sprintf(pString,
"Set other inputs at their mid points? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2)
{
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
}
jplot = 0;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
//**/ generate 2D data
int faLeng=0;
double *faXOut=NULL, *faYOut=NULL;
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
if (outputLevel_ > 1)
printf("Please wait while generating RS ....\n");
faPtr->gen2DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
vecInpSettings.getDVector(), &faLeng, &faXOut,&faYOut);
//**/ write to matlab/scilab file
if (plotScilab())
{
fp = fopen("scilabrs2.sci", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file scilabrs2.sci.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
fprintf(fp,"twoPlots = 1;\n");
fprintf(fp,"A = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faYOut[sInd]);
fprintf(fp,"];\n");
fprintf(fp,"A = matrix(A,%d,%d);\n", nPtsPerDim, nPtsPerDim);
fprintf(fp,"x = [\n");
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*2]);
fprintf(fp,"];\n");
fprintf(fp,"y = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%e\n", faXOut[sInd*2+1]);
fprintf(fp,"];\n");
fwritePlotCLF(fp);
fprintf(fp,"if twoPlots == 1\n");
fprintf(fp,"drawlater\n");
fprintf(fp,"subplot(1,2,1)\n");
fprintf(fp,"mesh(x,y,A)\n");
fprintf(fp,"h = get(\"hdl\");\n");
fprintf(fp,"h.color_flag=1;\n");
fprintf(fp,"h.color_mode=-2;\n");
fprintf(fp,"bmin = min(min(A)); bmax = max(max(A));\n");
fprintf(fp,"xset(\"colormap\",jetcolormap(64));\n");
fprintf(fp,"colorbar(bmin,bmax);\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
fwritePlotZLabel(fp, outputNames[jplot]);
sprintf(winput, "Mesh Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp,"a=gca();\n");
fprintf(fp,"a.data_bounds=[%e,%e;%e,%e];\n",iLowerB[iplot1],
iLowerB[iplot2], iUpperB[iplot1], iUpperB[iplot2]);
fprintf(fp,"a.axes_visible=\"on\";\n");
fprintf(fp,"drawnow\n");
fprintf(fp,"subplot(1,2,2)\n");
fprintf(fp,"end;\n");
fprintf(fp,"drawlater\n");
fprintf(fp,"B = A;\n");
fprintf(fp,"nX = length(x);\n");
fprintf(fp,"nY = length(y);\n");
fprintf(fp,"for ii = 1 : nX\n");
fprintf(fp,"for jj = 1 : nY\n");
fprintf(fp,"B(ii,jj) = A(nX-ii+1,jj);\n");
fprintf(fp,"end;\n");
fprintf(fp,"end;\n");
fprintf(fp,"a=gca();\n");
fprintf(fp,"a.data_bounds=[%e,%e;%e,%e];\n",iLowerB[iplot1],
iLowerB[iplot2], iUpperB[iplot1], iUpperB[iplot2]);
fprintf(fp,"bmin = min(min(B)); bmax = max(max(B));\n");
fprintf(fp,"Matplot1((B-bmin)/(bmax-bmin)*64,[%e,%e,%e,%e])\n",
iLowerB[iplot1],iLowerB[iplot2],iUpperB[iplot1],
iUpperB[iplot2]);
fprintf(fp,"set(gca(),\"auto_clear\",\"off\")\n");
fprintf(fp,"//contour2d(x,y,flipdim(B',1),6);\n");
fprintf(fp,"xset(\"colormap\",jetcolormap(64));\n");
fprintf(fp,"colorbar(bmin,bmax);\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
sprintf(winput, "Contour Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp,"drawnow\n");
fclose(fp);
printf("scilabrs2.sci is now available for response surface and ");
printf("contour plots\n");
}
else
{
fp = fopen("matlabrs2.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrs2.m.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
fwritePlotCLF(fp);
fprintf(fp, "twoPlots = 1;\n");
fprintf(fp, "A = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faYOut[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "A = reshape(A,%d,%d);\n", nPtsPerDim, nPtsPerDim);
fprintf(fp, "x = [\n");
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*2]);
fprintf(fp, "];\n");
fprintf(fp, "y = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%e\n", faXOut[sInd*2+1]);
fprintf(fp, "];\n");
if (nInputs == 2)
{
fprintf(fp, "xx = [\n");
for (sInd = 0; sInd < nSamples; sInd++)
fprintf(fp, "%e\n", sampleInputs[sInd*2+iplot1]);
fprintf(fp, "];\n");
fprintf(fp, "yy = [\n");
for (sInd = 0; sInd < nSamples; sInd++)
fprintf(fp, "%e\n", sampleInputs[sInd*2+iplot2]);
fprintf(fp, "];\n");
fprintf(fp, "zz = [\n");
for (sInd = 0; sInd < nSamples; sInd++)
fprintf(fp, "%e\n", vecFaYIn[sInd]);
fprintf(fp, "];\n");
}
fprintf(fp, "B = A;\n");
double Ymin = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] < Ymin) Ymin = faYOut[sInd];
double Ymax = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] > Ymax) Ymax = faYOut[sInd];
printf("Ymin and Ymax found = %e %e.\n", Ymin, Ymax);
printf("You can set thresholds to cut out certain regions.\n");
sprintf(pString,"Set lower threshold for output? (y or n) : ");
getString(pString, winput);
fprintf(fp, "n1 = 0;\n");
fprintf(fp, "n2 = 0;\n");
double thresh;
if (winput[0] == 'y')
{
sprintf(pString,"Enter the lower threshold (min = %e) : ",Ymin);
thresh = getDouble(pString);
fprintf(fp, "ymin = %e;\n", thresh);
fprintf(fp, "[ia,ja,aa] = find(A<ymin);\n");
fprintf(fp, "for ii = 1 : length(ia)\n");
//fprintf(fp, " B(ia(ii),ja(ii)) = %e;\n",Ymin-PABS(Ymin)*0.9);
fprintf(fp, " B(ia(ii),ja(ii)) = NaN;\n");
fprintf(fp, "end;\n");
fprintf(fp, "n1 = length(ia);\n");
}
sprintf(pString,"Set upper threshold for output? (y or n) : ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the upper threshold (max = %e) : ",Ymax);
thresh = getDouble(pString);
fprintf(fp, "ymax = %e;\n", thresh);
fprintf(fp, "[ia,ja,aa] = find(A>ymax);\n");
fprintf(fp, "for ii = 1 : length(ia)\n");
//fprintf(fp, " B(ia(ii),ja(ii)) = %e;\n",Ymin-PABS(Ymin)*0.9);
fprintf(fp, " B(ia(ii),ja(ii)) = NaN;\n");
fprintf(fp, "end;\n");
fprintf(fp, "n2 = length(ia);\n");
}
fprintf(fp, "nB = size(B,1);\n");
fprintf(fp, "if (n1 + n2 == nB * nB)\n");
fprintf(fp, " B(1,1) = 0;\n");
fprintf(fp, " B(%d,%d) = 1;\n",nPtsPerDim,nPtsPerDim);
fprintf(fp, "end\n");
fprintf(fp, "if twoPlots == 1\n");
fprintf(fp, "subplot(1,2,1), mesh(x,y,A)\n");
if (nInputs == 2)
{
fwriteHold(fp,1);
fprintf(fp,"plot3(xx,yy,zz,'k*','markersize',13);\n");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
fwritePlotZLabel(fp, outputNames[jplot]);
sprintf(winput, "Mesh Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp,"colorbar\n");
fprintf(fp,"subplot(1,2,2)\n");
fprintf(fp,"end\n");
fprintf(fp,"contourf(x,y,B)\n");
if (nInputs == 2)
{
fwriteHold(fp,1);
fprintf(fp,"plot(xx,yy,'k*','markersize',13);\n");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
fprintf(fp,"colorbar\n");
fprintf(fp,"colormap(jet)\n");
sprintf(winput,"Contour Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fclose(fp);
printf("matlabrs2.m is now available for response surface and ");
printf("contour plots\n");
}
delete [] faXOut;
delete [] faYOut;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rs3
//**/ generate response surface of any 3 inputs and write the
//**/ grid data to file for display with matlab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs3"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs3: response surface plot in three parameters\n");
printf("syntax: rs3 (no argument needed)\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
if (nInputs < 3)
{
printf("ERROR: rs3 requires 3 or more inputs.\n");
return 1;
}
if (plotScilab())
{
printf("INFO: rs3 is currently not available in scilab.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command creates a Matlab 3D plot (3 input/1 output).\n");
printf("The selected inputs will be in X, Y, and Z axes.\n");
printf("The output values will be displayed as different colors.\n");
printf("The other inputs are set at their midpoints or user-specified.\n");
printf("You will be asked to select a response surface type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ set up the function approximator
int nPtsPerDim = 16;
sprintf(pString, "Grid resolution ? (16 - 32) ");
nPtsPerDim = getInt(16, 32, pString);
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
//**/ ask users to specify the three inputs and one output
int iplot1, iplot2, iplot3;
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
sprintf(pString, "Enter the input for y axis (1 - %d) : ", nInputs);
iplot2 = getInt(1, nInputs, pString);
iplot2--;
sprintf(pString, "Enter the input for z axis (1 - %d) : ", nInputs);
iplot3 = getInt(1, nInputs, pString);
iplot3--;
int pcnt=1, iInd1, sInd, jplot;
if (iplot2 != iplot1) pcnt++;
if (iplot3 != iplot1 && iplot3 != iplot2) pcnt++;
if (nInputs-pcnt > 0)
{
sprintf(pString,
"Set other inputs at their mid points? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
{
vecInpSettings[iInd1] = iLowerB[iInd1] - 1.0;
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
while (vecInpSettings[iInd1] < iLowerB[iInd1] ||
vecInpSettings[iInd1] > iUpperB[iInd1])
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
}
sprintf(pString, "Enter the output number (1 - %d) : ", nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
int faLeng=0;
double *faXOut=NULL, *faYOut=NULL;
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
//**/ begin generating 3D data
printf("Please wait while generating the RS data \n");
faPtr->gen3DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
iplot3,vecInpSettings.getDVector(), &faLeng, &faXOut,&faYOut);
//**/ ask for lower and upper threshold only once
double GYmin = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] < GYmin) GYmin = faYOut[sInd];
double GYmax = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] > GYmax) GYmax = faYOut[sInd];
printf("\nYmin and Ymax found = %e %e.\n", GYmin, GYmax);
double threshL = GYmin - 0.2 * PABS(GYmax-GYmin);
double gamma = threshL;
printf("You can set thresholds to cut out certain regions.\n");
sprintf(pString,"Set lower threshold for output? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the lower threshold (min = %e): ",GYmin);
threshL = getDouble(pString);
if (threshL < GYmin)
{
threshL = GYmin;
printf("rs3 INFO: lower threshold set to %e.\n", threshL);
}
}
int ind;
double threshU = GYmax + 0.2 * PABS(GYmax-GYmin);
sprintf(pString,"Set upper threshold for output? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the upper threshold (max = %e): ",GYmax);
threshU = getDouble(pString);
if (threshU > GYmax)
{
threshU = GYmax;
printf("rs3 INFO: upper threshold set to %e.\n", threshU);
}
}
if (threshL >= threshU)
{
printf("rs3 ERROR: lower threshold (%e) >= upper threshold (%e)\n",
threshL, threshU);
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
fp = fopen("matlabrs3.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrs3.m.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
fwritePlotCLF(fp);
fprintf(fp,"xlo = %e; \n", iLowerB[iplot2]);
fprintf(fp,"xhi = %e; \n", iUpperB[iplot2]);
fprintf(fp,"ylo = %e; \n", iLowerB[iplot1]);
fprintf(fp,"yhi = %e; \n", iUpperB[iplot1]);
fprintf(fp,"zlo = %e; \n", iLowerB[iplot3]);
fprintf(fp,"zhi = %e; \n", iUpperB[iplot3]);
fprintf(fp,"X=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Y=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Z=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"V=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp,"Y(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
fprintf(fp,"%e ", faXOut[ind*3]);
}
fprintf(fp,"\n");
}
fprintf(fp, "];\n");
fprintf(fp, "X(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3+1]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
fprintf(fp, "Z(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3+2]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
int count=0;
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp, "V(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
if (faYOut[ind] < threshL)
{
fprintf(fp, "%e ", gamma);
count++;
}
else if (faYOut[ind] > threshU)
{
fprintf(fp, "%e ", gamma);
count++;
}
else fprintf(fp, "%e ", faYOut[ind]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
if (count == nPtsPerDim*nPtsPerDim*nPtsPerDim)
{
fprintf(fp, "V(1,1,1)=0;\n");
fprintf(fp, "V(%d,%d,%d)=1;\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
}
fprintf(fp,"xt = [%e:%e:%e];\n", iLowerB[iplot2],
(iUpperB[iplot2]-iLowerB[iplot2])*0.01, iUpperB[iplot2]);
fprintf(fp,"yt = [%e:%e:%e];\n", iLowerB[iplot1],
(iUpperB[iplot1]-iLowerB[iplot1])*0.01, iUpperB[iplot1]);
fprintf(fp,"zt = [%e:%e:%e];\n", iLowerB[iplot3],
(iUpperB[iplot3]-iLowerB[iplot3])*0.01, iUpperB[iplot3]);
fprintf(fp,"isoval = %e;\n", gamma);
fprintf(fp,"h = patch(isosurface(X,Y,Z,V,isoval),... \n");
fprintf(fp," 'FaceColor', 'blue', ... \n");
fprintf(fp," 'EdgeColor', 'none', ... \n");
fprintf(fp," 'AmbientStrength', 0.2, ... \n");
fprintf(fp," 'SpecularStrength', 0.7, ... \n");
fprintf(fp," 'DiffuseStrength', 0.4);\n");
fprintf(fp,"isonormals(X,Y,Z,V,h);\n");
fprintf(fp,"patch(isocaps(X,Y,Z,V,isoval), ...\n");
fprintf(fp," 'FaceColor', 'interp', ... \n");
fprintf(fp," 'EdgeColor', 'none'); \n");
fprintf(fp,"axis([xlo xhi ylo yhi zlo zhi])\n");
fprintf(fp,"daspect([%e,%e,%e])\n",iUpperB[iplot2]-iLowerB[iplot2],
iUpperB[iplot1]-iLowerB[iplot1],
iUpperB[iplot3]-iLowerB[iplot3]);
fprintf(fp," xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp," ylabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp," zlabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot3]);
fprintf(fp," title('%s','Fontsize',12,'FontWeight','bold')\n",
outputNames[jplot]);
fwritePlotAxes(fp);
fprintf(fp,"colormap('default'); colorbar\n");
fprintf(fp,"%%axis tight\n");
fprintf(fp,"view(3) \n");
fprintf(fp,"set(gcf,'Renderer','zbuffer')\n");
fprintf(fp,"lighting phong\n");
fprintf(fp,"cin = input('generate slices ? (y or n) ','s');\n");
fprintf(fp,"if (cin == 'y')\n");
fprintf(fp,"xin = input('axis to slide through ? (x,y,z) ','s');\n");
fprintf(fp,"for i = 1 : 101\n");
fprintf(fp," display(['displaying ' int2str(i) ' of 100'])\n");
fprintf(fp," if (xin == 'y')\n");
fprintf(fp," h = slice(X,Y,Z,V,xt(i),[],[]);\n");
fprintf(fp," elseif (xin == 'x')\n");
fprintf(fp," h = slice(X,Y,Z,V,[],yt(i),[]);\n");
fprintf(fp," elseif (xin == 'z')\n");
fprintf(fp," h = slice(X,Y,Z,V,[],[],zt(i));\n");
fprintf(fp," end\n");
fprintf(fp," axis([%11.4e %11.4e %11.4e %11.4e %11.4e %11.4e ",
iLowerB[iplot2], iUpperB[iplot2], iLowerB[iplot1],
iUpperB[iplot1], iLowerB[iplot3], iUpperB[iplot3]);
fprintf(fp,"%11.4e %11.4e])\n",
threshL-0.2*(threshU-threshL),threshU+0.2*(threshU-threshL));
fwritePlotAxes(fp);
fprintf(fp," xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp," ylabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp," zlabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot3]);
fprintf(fp," title('3D Contour Plot',");
fprintf(fp,"'FontWeight','bold','FontSize',12)\n");
fprintf(fp," view(3)\n");
fprintf(fp," colorbar\n");
fprintf(fp," pause(1)\n");
fprintf(fp," if (i < 101)\n");
fprintf(fp," clf\n");
fprintf(fp," end\n");
fprintf(fp,"end\n");
fprintf(fp,"end\n");
fclose(fp);
printf("\nmatlabrs3.m is now available.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rs3m
//**/ generate response surface of any 3 inputs and write the
//**/ grid data to file for display with matlab (movie)
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs3m"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs3m: response surface plot in 3 parameters using movie mode\n");
printf("syntax: rs3m (no argument needed)\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
if (nInputs < 3)
{
printf("ERROR: rs3m requires 3 or more inputs.\n");
return 1;
}
if (plotScilab())
{
printf("INFO: rs3m is currently not available in scilab.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command creates a Matlab 3D movie (3 inputs/1 output).\n");
printf("The selected inputs will be in X, Y, and Z axes.\n");
printf("The output will be displayed in the time axis.\n");
printf("The other inputs are set at their midpoints or user-specified.\n");
printf("You will be asked to select a response surface type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ set up the function approximator
int nPtsPerDim = 16;
sprintf(pString, "Grid resolution ? (16 - 32) ");
nPtsPerDim = getInt(16, 32, pString);
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
//**/ ask users to specify the three inputs and one output
int iplot1, iplot2, iplot3, jplot, iInd1, sInd;
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
sprintf(pString, "Enter the input for y axis (1 - %d) : ", nInputs);
iplot2 = getInt(1, nInputs, pString);
iplot2--;
sprintf(pString, "Enter the input for z axis (1 - %d) : ", nInputs);
iplot3 = getInt(1, nInputs, pString);
iplot3--;
int pmcnt=1;
if (iplot2 != iplot1) pmcnt++;
if (iplot3 != iplot1 && iplot3 != iplot2) pmcnt++;
if (nInputs-pmcnt > 0)
{
sprintf(pString,"Set other inputs at their mid points ? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
{
sprintf(pString,"Enter setting for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
}
sprintf(pString,"Enter the output number (1 - %d) : ", nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
//**/ begin generating 2D data
fp = fopen("matlabrs3m.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrs3m.m.\n");
delete faPtr;
return 1;
}
//**/ begin generating 3D data
int faLeng=0;
double *faXOut=NULL, *faYOut=NULL;
faPtr->gen3DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
iplot3,vecInpSettings.getDVector(), &faLeng, &faXOut,&faYOut);
double GYmin = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] < GYmin) GYmin = faYOut[sInd];
double GYmax = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] > GYmax) GYmax = faYOut[sInd];
printf("\nYmin and Ymax found = %e %e.\n", GYmin, GYmax);
double threshL = GYmin - 0.2 * PABS(GYmin);
printf("You can set thresholds to cut out certain regions.\n");
sprintf(pString, "Set lower threshold for output? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the lower threshold (min = %e): ",GYmin);
threshL = getDouble(pString);
}
double threshU = GYmax + 0.2 * PABS(GYmax);
sprintf(pString, "Set upper threshold for output? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the upper threshold (min = %e): ",GYmax);
threshU = getDouble(pString);
}
fprintf(fp,"twoPlots = 1;\n");
fprintf(fp,"disp(\'Please wait while loading data.\')\n");
fprintf(fp,"hold off\n");
fwritePlotCLF(fp);
//**/ generating visualization data
for (ii = 0; ii < nPtsPerDim; ii++)
{
vecInpSettings[iplot3] = (iUpperB[iplot3] - iLowerB[iplot3]) /
(nPtsPerDim - 1.0) * ii + iLowerB[iplot3];
//**/ x and y data only needed to output once
fprintf(fp,"x = [\n");
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim*nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*3]);
fprintf(fp,"];\n");
fprintf(fp,"y = [\n");
for (sInd = 0; sInd < nPtsPerDim*nPtsPerDim; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*3+1]);
fprintf(fp,"];\n");
//**/ output the response data data
fprintf(fp,"A%d = [\n", ii + 1);
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faYOut[sInd+ii]);
fprintf(fp,"];\n");
fprintf(fp,"A%d = reshape(A%d,%d,%d);\n", ii+1, ii+1,
nPtsPerDim, nPtsPerDim);
fprintf(fp,"disp(\'Plotting frame %d of %d\')\n",ii+1,nPtsPerDim);
fprintf(fp,"B%d = A%d;\n", ii+1, ii+1);
fprintf(fp,"yLo = %e;\n", threshL);
fprintf(fp,"yHi = %e;\n", threshU);
fprintf(fp,"nA = size(A%d,1);\n", ii+1);
fprintf(fp,"[ia,ja,aa] = find(A%d<yLo);\n", ii+1);
fprintf(fp,"for ii = 1 : length(ia)\n");
fprintf(fp," B%d(ia(ii),ja(ii)) = NaN;\n", ii+1);
fprintf(fp,"end;\n");
fprintf(fp,"n1 = length(ia);\n");
fprintf(fp,"[ia,ja,aa] = find(A%d>yHi);\n", ii+1);
fprintf(fp,"for ii = 1 : length(ia)\n");
fprintf(fp," B%d(ia(ii),ja(ii)) = NaN;\n", ii+1);
fprintf(fp,"end;\n");
fprintf(fp,"n2 = length(ia);\n");
fprintf(fp,"if (n1 + n2 == nA*nA)\n");
fprintf(fp," B%d(1,1) = 0;\n",ii+1);
fprintf(fp," B%d(%d,%d) = 1;\n",ii+1,nPtsPerDim,nPtsPerDim);
fprintf(fp,"end;\n");
fprintf(fp,"if twoPlots == 1\n");
fprintf(fp,"subplot(1,2,1), surf(x,y,A%d)\n", ii+1);
fprintf(fp,"axis([%e %e %e %e %e %e])\n",iLowerB[iplot1],
iUpperB[iplot1],iLowerB[iplot2],iUpperB[iplot2],GYmin, GYmax);
fwritePlotAxes(fp);
fprintf(fp,"xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp,"ylabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp,"zlabel('%s','Fontsize',12,'FontWeight','bold')\n",
outputNames[jplot]);
fprintf(fp,"colorbar\n");
fprintf(fp,"title(\'%s Mesh plot, val(3) = %14.7e\',",
outputNames[jplot], vecInpSettings[iplot3]);
fprintf(fp,"'FontWeight','bold','FontSize',12)\n");
fprintf(fp,"subplot(1,2,2)\n");
fprintf(fp,"end\n");
fprintf(fp,"contourf(x,y,B%d)\n",ii+1);
fprintf(fp,"axis([%e %e %e %e])\n",iLowerB[iplot1],
iUpperB[iplot1],iLowerB[iplot2],iUpperB[iplot2]);
fwritePlotAxes(fp);
fprintf(fp,"colorbar\n");
fprintf(fp,"colormap(jet)\n");
fprintf(fp,"caxis([%e %e])\n",GYmin, GYmax);
fprintf(fp,"title(\'%s contour plot, val(3) = %14.7e\',",
outputNames[jplot], vecInpSettings[iplot3]);
fprintf(fp,"'FontWeight','bold','FontSize',12)\n");
fprintf(fp,"pause(1)\n");
}
fprintf(fp,"rotate3d on\n");
fclose(fp);
printf("matlabrs3m.m is now available for response surface and ");
printf("contour plots\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rs4
//**/ generate response surface of any 4 inputs and write the
//**/ grid data to file for display with matlab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rs4"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rs4: response surface plot in 4 parameters\n");
printf("syntax: rs4 (no argument needed)\n");
return 0;
}
if (nInputs <= 0 || psuadeIO == NULL)
{
printf("ERROR: data not loaded yet.\n");
return 1;
}
if (nInputs < 4)
{
printf("ERROR: rs4 requires 4 or more inputs.\n");
return 1;
}
if (plotScilab())
{
printf("INFO: rs4 is currently not available in scilab.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command creates a Matlab 3D movie (4 inputs/1 output).\n");
printf("3 selected inputs will be in X, Y, and Z axes.\n");
printf("The 4th input and output will be displayed in the time axis.\n");
printf("The other inputs are set at their midpoints or user-specified.\n");
printf("You will be asked to select a response surface type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ set up the function approximator
int nPtsPerDim = 16;
printf("NOTE: if matlab crashes, it may be due to high grid resolution\n");
sprintf(pString, "Grid resolution ? (16 - 32) ");
nPtsPerDim = getInt(16, 32, pString);
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
//**/ ask users to specify the three inputs and one output
int iplot1, iplot2, iplot3, iplot4, iInd1;
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
sprintf(pString, "Enter the input for y axis (1 - %d) : ", nInputs);
iplot2 = getInt(1, nInputs, pString);
iplot2--;
sprintf(pString, "Enter the input for z axis (1 - %d) : ", nInputs);
iplot3 = getInt(1, nInputs, pString);
iplot3--;
sprintf(pString, "Enter the input for t axis (1 - %d) : ", nInputs);
iplot4 = getInt(1, nInputs, pString);
iplot4--;
int p4cnt=1;
if (iplot2 != iplot1) p4cnt++;
if (iplot3 != iplot1 && iplot3 != iplot2) p4cnt++;
if (iplot4 != iplot1 && iplot4 != iplot2 && iplot4 != iplot3) p4cnt++;
if (nInputs-p4cnt > 0)
{
sprintf(pString,"Set other inputs at their mid points ? (y/n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3 &&
iInd1 != iplot4)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3 &&
iInd1 != iplot4)
{
vecInpSettings[iInd1] = iLowerB[iInd1] - 1.0;
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
while (vecInpSettings[iInd1] < iLowerB[iInd1] ||
vecInpSettings[iInd1] > iUpperB[iInd1])
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
}
int jplot=0, sInd;
sprintf(pString, "Enter the output number (1 - %d) : ", nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
//**/ search for extrema
int faLeng=0;
double *faXOut=NULL, *faYOut=NULL;
faPtr->gen4DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
iplot3,iplot4,vecInpSettings.getDVector(),&faLeng,&faXOut,
&faYOut);
double GYmin = PSUADE_UNDEFINED;
double GYmax = - PSUADE_UNDEFINED;
for (sInd = 0; sInd < faLeng; sInd++)
if (faYOut[sInd] < GYmin) GYmin = faYOut[sInd];
for (sInd = 0; sInd < faLeng; sInd++)
if (faYOut[sInd] > GYmax) GYmax = faYOut[sInd];
printf("\nYmin and Ymax found = %e %e.\n", GYmin, GYmax);
double threshL = GYmin - 0.2 * PABS(GYmax - GYmin);
printf("You can set thresholds to cut out certain regions.\n");
sprintf(pString,"Set lower threshold for output? (y or n) ");
double gamma = threshL;
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the lower threshold (min = %e): ",GYmin);
threshL = getDouble(pString);
}
double threshU = GYmax + 0.2 * PABS(GYmax - GYmin);
sprintf(pString,"Set upper threshold for output? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
sprintf(pString,"Enter the upper threshold (max = %e): ",GYmax);
threshU = getDouble(pString);
}
//**/ begin generating data
fp = fopen("matlabrs4.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrs4.m.\n");
if (faXOut != NULL) delete [] faXOut;
if (faYOut != NULL) delete [] faYOut;
if (faPtr != NULL) delete faPtr;
return 1;
}
fprintf(fp,"%% user adjustable parameter section begins *****\n");
fprintf(fp,"%% use nSubplots, nSubNx and nSubNy to spread \n");
fprintf(fp,"%% the movie frames into a number of subplots.\n");
fprintf(fp,"nSubplots = 1;\n");
fprintf(fp,"nSubNx = 1;\n");
fprintf(fp,"nSubNy = 1;\n");
fprintf(fp,"%% user adjustable parameter section ends *****\n");
fwritePlotCLF(fp);
fprintf(fp,"nFrames = %d;\n", nPtsPerDim);
fprintf(fp,"nSubCnt = 0;\n");
fprintf(fp,"isoval = %e;\n", threshL);
fprintf(fp,"xlo = %e; \n", iLowerB[iplot2]);
fprintf(fp,"xhi = %e; \n", iUpperB[iplot2]);
fprintf(fp,"ylo = %e; \n", iLowerB[iplot1]);
fprintf(fp,"yhi = %e; \n", iUpperB[iplot1]);
fprintf(fp,"zlo = %e; \n", iLowerB[iplot3]);
fprintf(fp,"zhi = %e; \n", iUpperB[iplot3]);
fprintf(fp,"X=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Y=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Z=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"V=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
int ind;
for (ii = 0; ii < nPtsPerDim; ii++)
{
//**/ x and y data only needed to output once
fprintf(fp,"Y(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind = (sInd*nPtsPerDim*nPtsPerDim+jj*nPtsPerDim+ii)*nPtsPerDim;
fprintf(fp, "%e ", faXOut[ind*4]);
}
fprintf(fp, "\n");
}
fprintf(fp,"];\n");
fprintf(fp,"X(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind = (sInd*nPtsPerDim*nPtsPerDim+jj*nPtsPerDim+ii)*nPtsPerDim;
fprintf(fp, "%e ", faXOut[ind*4+1]);
}
fprintf(fp, "\n");
}
fprintf(fp,"];\n");
fprintf(fp,"Z(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind = (sInd*nPtsPerDim*nPtsPerDim+jj*nPtsPerDim+ii)*nPtsPerDim;
fprintf(fp,"%e ", faXOut[ind*4+2]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
//**/fprintf(fp, "xt = [%e:%e:%e];\n", iLowerB[iplot2],
//**/ (iUpperB[iplot2]-iLowerB[iplot2])*0.05, iUpperB[iplot2]);
//**/fprintf(fp, "yt = [%e:%e:%e];\n", iLowerB[iplot1],
//**/ (iUpperB[iplot1]-iLowerB[iplot1])*0.05, iUpperB[iplot1]);
//**/fprintf(fp, "zt = [%e:%e:%e];\n", iLowerB[iplot3],
//**/ (iUpperB[iplot3]-iLowerB[iplot3])*0.05, iUpperB[iplot3]);
int count, ll;
for (ll = 0; ll < nPtsPerDim; ll++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
count = 0;
//**/ x and y data only needed to output once
fprintf(fp,"V(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind = ((sInd*nPtsPerDim+jj)*nPtsPerDim+ii)*nPtsPerDim+ll;
if (faYOut[ind] < threshL)
{
fprintf(fp, "%e ", threshL);
count++;
}
else if (faYOut[ind] > threshU)
{
//**/fprintf(fp, "%e ", threshU);
//**/ set it at isoval
fprintf(fp, "%e ", threshL);
count++;
}
else fprintf(fp, "%e ", faYOut[ind]);
}
fprintf(fp, "\n");
}
fprintf(fp,"];\n");
if (count == nPtsPerDim*nPtsPerDim)
{
if (threshL-0.2*(threshU-threshL) > gamma)
fprintf(fp,"V(:,:,%d) = %e * ones(%d,%d);\n",ii+1,gamma,
nPtsPerDim, nPtsPerDim);
else
fprintf(fp,"V(:,:,%d) = %e * ones(%d,%d);\n",ii+1,
threshL-0.2*(threshU-threshL),
nPtsPerDim,nPtsPerDim);
printf("Frame %d, slice %d nonfeasible -> set to ground.\n",
ll+1, ii+1);
}
}
fprintf(fp,"frame = %d;\n", ll+1);
fprintf(fp,"if nSubplots > 1\n");
fprintf(fp," if frame <= 2\n");
fprintf(fp," nSubCnt = nSubCnt + 1;\n");
fprintf(fp," subplot(nSubNx, nSubNy, nSubCnt)\n");
fprintf(fp," elseif frame == nFrames\n");
fprintf(fp," subplot(nSubNx, nSubNy, nSubplots)\n");
fprintf(fp," else\n");
fprintf(fp," ft1 = (nFrames-1) / (nSubplots-1);\n");
fprintf(fp," ft2 = round(ft1 * (nSubCnt-1)) + 2;\n");
fprintf(fp," if frame == ft2\n");
fprintf(fp," nSubCnt = nSubCnt + 1;\n");
fprintf(fp," subplot(nSubNx, nSubNy, nSubCnt)\n");
fprintf(fp," end\n");
fprintf(fp," end\n");
fprintf(fp,"else\n");
fprintf(fp," clf\n");
fprintf(fp,"end\n");
fprintf(fp,"disp('Frame %d of %d')\n", ll+1, nPtsPerDim);
//**/ Nov 25, 2008: old, new using isosurface is better
//**/ fprintf(fp, "h = contourslice(x,y,z,v,xt,yt,zt,21);\n");
//**/ fprintf(fp, "axis([min(min(min(x))) max(max(max(x))) ");
//**/ fprintf(fp, "min(min(min(y))) max(max(max(y))) ");
//**/ fprintf(fp, "min(min(min(z))) max(max(max(z))) ");
//**/ if (threshL-0.2*(threshU-threshL) > gamma)
//**/ fprintf(fp, " %e %e])\n",gamma,threshU+0.2*(threshU-threshL));
//**/ else
//**/ fprintf(fp, " %e %e])\n", threshL-0.2*(threshU-threshL),
//**/ threshU+0.2*(threshU-threshL));
//**/ fprintf(fp, "view(-40,60)\n");
//**/ fprintf(fp, "set(h, 'Linewidth', 5)\n");
//**/ fprintf(fp, "box on\n");
//**/ fprintf(fp, "grid on\n");
fprintf(fp,"h = patch(isosurface(X,Y,Z,V,isoval),... \n");
fprintf(fp," 'FaceColor', 'blue', ... \n");
fprintf(fp," 'EdgeColor', 'none', ... \n");
fprintf(fp," 'AmbientStrength', 0.2, ... \n");
fprintf(fp," 'SpecularStrength', 0.7, ... \n");
fprintf(fp," 'DiffuseStrength', 0.4);\n");
fprintf(fp,"isonormals(X,Y,Z,V,h);\n");
fprintf(fp,"patch(isocaps(X,Y,Z,V,isoval), ...\n");
fprintf(fp," 'FaceColor', 'interp', ... \n");
fprintf(fp," 'EdgeColor', 'none'); \n");
fprintf(fp,"axis([xlo xhi ylo yhi zlo zhi])\n");
fprintf(fp,"daspect([xhi-xlo, yhi-ylo, zhi-zlo])\n");
fprintf(fp,"colormap('default')\n");
fprintf(fp,"if nSubplots == 1\n");
fprintf(fp," colorbar\n");
fprintf(fp,"end\n");
fprintf(fp,"%%axis tight\n");
fprintf(fp,"view(3) \n");
//**/ fprintf(fp, "camlight right \n");
//**/ fprintf(fp, "camlight left \n");
fprintf(fp,"set(gcf,'Renderer','zbuffer')\n");
fprintf(fp,"box on\n");
fprintf(fp,"grid on\n");
fprintf(fp,"lighting phong\n");
fwritePlotAxes(fp);
if (ll == 0)
{
fprintf(fp,"xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp,"ylabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp,"zlabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot3]);
}
fprintf(fp,"title('%s=%12.4e',",inputNames[iplot4],faXOut[ll*4+3]);
fprintf(fp,"'FontWeight','bold','FontSize',12)\n");
fprintf(fp,"pause(1)\n");
}
fclose(fp);
printf("\nmatlabrs4.m is now available.\n");
if (faXOut != NULL) delete [] faXOut;
if (faYOut != NULL) delete [] faYOut;
if (faPtr != NULL) delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rssd
//**/ generate standard deviation response surface and write the
//**/ grid data to file for display with matlab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssd"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssd: response surface plots for the std. deviations.\n");
printf("INFO: rssd not available for >2 inputs for scilab.\n");
printf("syntax: rssd (no argument needed.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command creates a Matlab response surface plot for the ");
printf("prediction\n");
printf("uncertainties in the selected input space.\n");
printf("You can select up to 4 inputs.\n");
printf("The other inputs are set at their midpoints or user-specified.\n");
printf("You will be asked to select a response surface (RS) type.\n");
printf("The selected RS should give prediction uncertainty (e.g. GP).\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ ask users to specify the three inputs and one output
int iplot1, iplot2, iplot3, iplot4, count, iInd1, sInd, ind, ll;
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
iplot1 = iplot2 = iplot3 = iplot4 = -1;
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
count = 1;
if (nInputs == 2) iplot2 = nInputs - iplot1 - 1;
else if (nInputs > 2)
{
iplot2 = iplot1;
while (iplot1 == iplot2)
{
sprintf(pString, "Y-axis input ? (1-%d, 0 if not used, not %d) ",
nInputs, iplot1+1);
iplot2 = getInt(0, nInputs, pString);
iplot2--;
if (iplot2 == -1) break;
if (iplot1 == iplot2)
printf("ERROR: duplicate input number %d.\n",iplot2+1);
}
}
if (iplot2 != -1) count++;
if (plotMatlab() && iplot2 != -1)
{
if (nInputs == 3) iplot3 = nInputs - iplot1 - iplot2;
else if (nInputs > 3)
{
iplot3 = iplot1;
while (iplot3 == iplot1 || iplot3 == iplot2)
{
sprintf(pString,
"Z axis input ? (1-%d, 0 if not used, not %d nor %d) ",
nInputs, iplot1+1, iplot2+1);
iplot3 = getInt(0, nInputs, pString);
iplot3--;
if (iplot3 == -1) break;
if (iplot3 == iplot1 || iplot3 == iplot2)
printf("ERROR: duplicate input number %d.\n",iplot3+1);
}
}
if (iplot3 != -1) count++;
if (nInputs >= 4 && iplot3 != -1)
{
while (iplot4 < 0 || iplot4 == iplot1 || iplot4 == iplot2 ||
iplot4 == iplot3)
{
sprintf(pString,
"Enter the input for t axis (1 - %d), not %d nor %d,%d: ",
nInputs, iplot1+1, iplot2+1, iplot3+1);
iplot4 = getInt(1, nInputs, pString);
iplot4--;
if (iplot4 == iplot1 || iplot4 == iplot2 || iplot4 == iplot3)
printf("ERROR: duplicate input number %d.\n",iplot4+1);
}
}
if (iplot4 != -1) count++;
}
strcpy(winput, "y");
if (nInputs > count)
{
sprintf(pString,"Set other inputs at their mid points ? (y/n) ");
getString(pString, winput);
}
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3 &&
iInd1 != iplot4)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3 &&
iInd1 != iplot4)
{
vecInpSettings[iInd1] = iLowerB[iInd1] - 1.0;
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
while (vecInpSettings[iInd1] < iLowerB[iInd1] ||
vecInpSettings[iInd1] > iUpperB[iInd1])
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
//**/ set up the function approximator
int nPtsPerDim;
if (iplot2 == -1) nPtsPerDim = 1024;
else if (iplot3 == -1) nPtsPerDim = 128;
else if (iplot4 == -1) nPtsPerDim = 24;
else nPtsPerDim = 10;
printf("This command works with the following response surfaces:\n");
printf("1. Linear regression\n");
printf("2. Quadratic regression\n");
printf("3. cubic regression\n");
printf("4. quartic regression\n");
printf("5. GP1 (MacKay)\n");
printf("6. GP3 (Tong)\n");
printf("7. MarsBagg\n");
printf("8. Tree GP\n");
printf("9. Kriging\n");
sprintf(pString, "Enter your choice: (1, 2, ..., 9) ");
int faType = getInt(1, 9, pString);
if (faType == 1) faType = PSUADE_RS_REGR1;
else if (faType == 2) faType = PSUADE_RS_REGR2;
else if (faType == 3) faType = PSUADE_RS_REGR3;
else if (faType == 4) faType = PSUADE_RS_REGR4;
else if (faType == 5) faType = PSUADE_RS_GP1;
else if (faType == 6) faType = PSUADE_RS_GP3;
else if (faType == 7) faType = PSUADE_RS_MARSB;
else if (faType == 8) faType = PSUADE_RS_TGP;
else if (faType == 9) faType = PSUADE_RS_KR;
int faFlag = 1, iOne=1;
FuncApprox *faPtr = genFA(faType, nInputs, iOne, nSamples);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
//**/ ask users to specify the three inputs and one output
int jplot = 0;
sprintf(pString, "Enter the output number (1 - %d) : ",nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
//**/ generate data points
int faLeng = 0;
double *faXOut=NULL, *faYOut=NULL;
if (iplot2 == -1)
faPtr->gen1DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,
vecInpSettings.getDVector(), &faLeng, &faXOut,&faYOut);
else if (iplot3 == -1)
faPtr->gen2DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,
iplot2,vecInpSettings.getDVector(),&faLeng,&faXOut,&faYOut);
else if (iplot4 == -1)
faPtr->gen3DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,
iplot2,iplot3,vecInpSettings.getDVector(),&faLeng,&faXOut,
&faYOut);
else
faPtr->gen4DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,
iplot2,iplot3,iplot4,vecInpSettings.getDVector(),&faLeng,
&faXOut,&faYOut);
//**/ re-generate to include standard deviation
psVector vecWT, vecXT;
vecWT.setLength(faLeng);
vecXT.setLength(faLeng*nInputs);
for (sInd = 0; sInd < faLeng; sInd++)
for (jj = 0; jj < nInputs; jj++)
vecXT[sInd*nInputs+jj] = vecInpSettings[jj];
for (sInd = 0; sInd < faLeng; sInd++)
{
vecXT[sInd*nInputs+iplot1] = faXOut[sInd*count];
if (iplot2 != -1)
vecXT[sInd*nInputs+iplot2] = faXOut[sInd*count+1];
if (iplot3 != -1)
vecXT[sInd*nInputs+iplot3] = faXOut[sInd*count+2];
if (iplot4 != -1)
vecXT[sInd*nInputs+iplot4] = faXOut[sInd*count+3];
}
faPtr->evaluatePointFuzzy(faLeng, vecXT.getDVector(), faYOut,
vecWT.getDVector());
double gamma = PSUADE_UNDEFINED;
for (sInd = 0; sInd < faLeng; sInd++)
if (vecWT[sInd] < gamma) gamma = vecWT[sInd];
//**/ begin generating data
if (plotScilab())
{
fp = fopen("scilabrssd.sci", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file scilabrssd.sci.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
}
else
{
fp = fopen("matlabrssd.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrssd.m.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
return 1;
}
}
fwritePlotCLF(fp);
if (count == 1)
{
fprintf(fp, "A = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", vecWT[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "X = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faXOut[sInd]);
fprintf(fp, "];\n");
if (plotScilab())
{
fprintf(fp, "plot(X,A);");
fprintf(fp, "a = gca();\n");
fprintf(fp, "a.children.children.thickness = 4;\n");
fprintf(fp, "set(gca(),\"auto_clear\",\"off\")\n");
}
else
{
fprintf(fp, "plot(X,A,'lineWidth',4)\n");
fprintf(fp, "hold on\n");
}
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, outputNames[jplot]);
sprintf(winput, "Std. Dev. Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
}
else if (count == 2)
{
if (plotMatlab()) fprintf(fp, "twoPlots = 1;\n");
fprintf(fp, "A = [\n");
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", vecWT[sInd]);
fprintf(fp, "];\n");
if (plotScilab())
fprintf(fp, "A = matrix(A,%d,%d);\n", nPtsPerDim, nPtsPerDim);
else
fprintf(fp, "A = reshape(A,%d,%d);\n", nPtsPerDim, nPtsPerDim);
fprintf(fp, "X = [\n");
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*2]);
fprintf(fp, "];\n");
fprintf(fp, "Y = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%e\n", faXOut[sInd*2+1]);
fprintf(fp, "];\n");
if (plotScilab())
{
fprintf(fp, "mesh(X,Y,A)\n");
fprintf(fp, "h = get(\"hdl\");\n");
fprintf(fp, "h.color_flag=1;\n");
fprintf(fp, "h.color_mode=-2;\n");
fprintf(fp, "bmin = min(min(A)); bmax = max(max(A));\n");
fprintf(fp, "xset(\"colormap\",jetcolormap(64));\n");
fprintf(fp, "colorbar(bmin,bmax);\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
fwritePlotZLabel(fp, outputNames[jplot]);
sprintf(winput, "Std. Dev. Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp, "scf(2);\n");
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[%e,%e;%e,%e];\n",
iLowerB[iplot1], iLowerB[iplot2],
iUpperB[iplot1], iUpperB[iplot2]);
fprintf(fp, "a.axes_visible=\"on\";\n");
fprintf(fp, "B = A;\n");
fprintf(fp, "nX = length(X);\n");
fprintf(fp, "nY = length(Y);\n");
fprintf(fp, "for ii = 1 : nX\n");
fprintf(fp, "for jj = 1 : nY\n");
fprintf(fp, "B(ii,jj) = A(nX-ii+1,jj);\n");
fprintf(fp, "end;\n");
fprintf(fp, "end;\n");
fprintf(fp, "Matplot1((B-bmin)/(bmax-bmin)*64,[%e,%e,%e,%e])\n",
iLowerB[iplot1],iLowerB[iplot2],
iUpperB[iplot1], iUpperB[iplot2]);
fprintf(fp, "xset(\"colormap\",jetcolormap(64));\n");
fprintf(fp, "colorbar(bmin,bmax);\n");
fprintf(fp, "a.thickness = 2;\n");
fprintf(fp, "a.font_size = 3;\n");
fprintf(fp, "a.font_style = 4;\n");
fprintf(fp, "a.box = \"on\";\n");
fprintf(fp, "a.grid = [1 1];\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
sprintf(winput, "Std. Dev. Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
}
else
{
fprintf(fp, "if twoPlots == 1\n");
fprintf(fp, "subplot(1,2,1), surf(X,Y,A)\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
fwritePlotZLabel(fp, outputNames[jplot]);
sprintf(winput, "Std. Dev. Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp, "colorbar\n");
fprintf(fp, "subplot(1,2,2)\n");
fprintf(fp, "end\n");
fprintf(fp, "contourf(X,Y,A)\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
sprintf(winput, "Std. Dev. Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp, "colorbar\n");
fprintf(fp, "colormap(jet)\n");
}
}
else if (count == 3)
{
fprintf(fp,"xlo = %e; \n", iLowerB[iplot2]);
fprintf(fp,"xhi = %e; \n", iUpperB[iplot2]);
fprintf(fp,"ylo = %e; \n", iLowerB[iplot1]);
fprintf(fp,"yhi = %e; \n", iUpperB[iplot1]);
fprintf(fp,"zlo = %e; \n", iLowerB[iplot3]);
fprintf(fp,"zhi = %e; \n", iUpperB[iplot3]);
fprintf(fp,"X=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Y=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Z=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"V=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp, "Y(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
fprintf(fp, "X(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3+1]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
fprintf(fp, "Z(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3+2]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
double GYmax = - PSUADE_UNDEFINED;
double GYmin = PSUADE_UNDEFINED;
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp, "V(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+ii*nPtsPerDim+jj;
fprintf(fp, "%e ", vecWT[ind]);
if (vecWT[ind] > GYmax) GYmax = vecWT[ind];
if (vecWT[ind] < GYmin) GYmin = vecWT[ind];
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
fprintf(fp, "xt = [%e:%e:%e];\n", iLowerB[iplot2],
(iUpperB[iplot2]-iLowerB[iplot2])*0.01, iUpperB[iplot2]);
fprintf(fp, "yt = [%e:%e:%e];\n", iLowerB[iplot1],
(iUpperB[iplot1]-iLowerB[iplot1])*0.01, iUpperB[iplot1]);
fprintf(fp, "zt = [%e:%e:%e];\n", iLowerB[iplot3],
(iUpperB[iplot3]-iLowerB[iplot3])*0.01, iUpperB[iplot3]);
fwritePlotCLF(fp);
fprintf(fp, "isoval = %e;\n", gamma);
fprintf(fp, "h = patch(isosurface(X,Y,Z,V,isoval),... \n");
fprintf(fp, " 'FaceColor', 'blue', ... \n");
fprintf(fp, " 'EdgeColor', 'none', ... \n");
fprintf(fp, " 'AmbientStrength', 0.2, ... \n");
fprintf(fp, " 'SpecularStrength', 0.7, ... \n");
fprintf(fp, " 'DiffuseStrength', 0.4);\n");
fprintf(fp, "isonormals(X,Y,Z,V,h);\n");
fprintf(fp, "patch(isocaps(X,Y,Z,V,isoval), ...\n");
fprintf(fp, " 'FaceColor', 'interp', ... \n");
fprintf(fp, " 'EdgeColor', 'none'); \n");
fprintf(fp, "axis([xlo xhi ylo yhi zlo zhi])\n");
fprintf(fp, "daspect([xhi-xlo, yhi-ylo, zhi-zlo])\n");
fprintf(fp, "colormap('default'); colorbar\n");
fprintf(fp, "%%axis tight\n");
fprintf(fp, "view(3) \n");
fprintf(fp, "set(gcf,'Renderer','zbuffer')\n");
fprintf(fp, "box on\n");
fprintf(fp, "grid on\n");
fprintf(fp, "lighting phong\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot2]);
fwritePlotYLabel(fp, inputNames[iplot1]);
fwritePlotZLabel(fp, inputNames[iplot3]);
sprintf(winput, "Std. Dev. Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp,"cin = input('generate slices ? (y or n) ','s');\n");
fprintf(fp,"if (cin == 'y')\n");
fprintf(fp,"xin = input('axis to slide through? (x,y,z) ','s');\n");
fprintf(fp,"N = 101;\n");
fprintf(fp,"for i = 1 : N\n");
fprintf(fp," display(['displaying ' int2str(i) ' of 101'])\n");
fprintf(fp," if (xin == 'y')\n");
fprintf(fp," h = slice(X,Y,Z,V,xt(i),[],[]);\n");
fprintf(fp," elseif (xin == 'x')\n");
fprintf(fp," h = slice(X,Y,Z,V,[],yt(i),[]);\n");
fprintf(fp," elseif (xin == 'z')\n");
fprintf(fp," h = slice(X,Y,Z,V,[],[],zt(i));\n");
fprintf(fp," end\n");
fprintf(fp," axis([%11.4e %11.4e %11.4e %11.4e %11.4e %11.4e ",
iLowerB[iplot2], iUpperB[iplot2], iLowerB[iplot1],
iUpperB[iplot1], iLowerB[iplot3], iUpperB[iplot3]);
fprintf(fp, "%11.4e %11.4e])\n",
GYmin-0.1*(GYmax-GYmin),GYmax+0.1*(GYmax-GYmin));
//**/fprintf(fp," if (xin == 'y')\n");
//**/fprintf(fp," h = contourslice(X,Y,Z,V,xt(i),[],[],N);\n");
//**/fprintf(fp," elseif (xin == 'y')\n");
//**/fprintf(fp," h = contourslice(X,Y,Z,V,[],yt(i),[],N);\n");
//**/fprintf(fp," elseif (xin == 'z')\n");
//**/fprintf(fp," h = contourslice(X,Y,Z,V,[],[],zt(i),N);\n");
//**/fprintf(fp," end\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot2]);
fwritePlotYLabel(fp, inputNames[iplot1]);
fwritePlotZLabel(fp, inputNames[iplot3]);
sprintf(winput, "Std. Dev. Slice Plot for %s", outputNames[jplot]);
fwritePlotTitle(fp, winput);
fprintf(fp, " view(3)\n");
fprintf(fp, " colorbar\n");
fprintf(fp, " pause(1)\n");
fprintf(fp, " if (i < 101)\n");
fprintf(fp, " clf\n");
fprintf(fp, " end\n");
fprintf(fp, "end\n");
fprintf(fp, "end\n");
}
else if (count == 4)
{
fprintf(fp,"xlo = %e; \n", iLowerB[iplot2]);
fprintf(fp,"xhi = %e; \n", iUpperB[iplot2]);
fprintf(fp,"ylo = %e; \n", iLowerB[iplot1]);
fprintf(fp,"yhi = %e; \n", iUpperB[iplot1]);
fprintf(fp,"zlo = %e; \n", iLowerB[iplot3]);
fprintf(fp,"zhi = %e; \n", iUpperB[iplot3]);
fprintf(fp,"X=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Y=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"Z=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp,"V=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
for (ii = 0; ii < nPtsPerDim; ii++)
{
//**/ x and y data only needed to output once
fprintf(fp, "Y(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind = (sInd*nPtsPerDim*nPtsPerDim+jj*nPtsPerDim+ii)*
nPtsPerDim;
fprintf(fp, "%e ", faXOut[ind*4]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
fprintf(fp, "X(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind = (sInd*nPtsPerDim*nPtsPerDim+jj*nPtsPerDim+ii)*
nPtsPerDim;
fprintf(fp, "%e ", faXOut[ind*4+1]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
fprintf(fp, "Z(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind = (sInd*nPtsPerDim*nPtsPerDim+jj*nPtsPerDim+ii)*
nPtsPerDim;
fprintf(fp, "%e ", faXOut[ind*4+2]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
fprintf(fp, "xt = [%e:%e:%e];\n", iLowerB[iplot2],
(iUpperB[iplot2]-iLowerB[iplot2])*0.05, iUpperB[iplot2]);
fprintf(fp, "yt = [%e:%e:%e];\n", iLowerB[iplot1],
(iUpperB[iplot1]-iLowerB[iplot1])*0.05, iUpperB[iplot1]);
fprintf(fp, "zt = [%e:%e:%e];\n", iLowerB[iplot3],
(iUpperB[iplot3]-iLowerB[iplot3])*0.05, iUpperB[iplot3]);
for (ll = 0; ll < nPtsPerDim; ll++)
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
//**/ x and y data only needed to output once
fprintf(fp, "V(:,:,%d) = [\n", ii + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
ind=((sInd*nPtsPerDim+jj)*nPtsPerDim+ii)*nPtsPerDim+ll;
fprintf(fp, "%e ", vecWT[ind]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
fprintf(fp, "disp('Frame %d of %d')\n", ll+1, nPtsPerDim);
fwritePlotCLF(fp);
fprintf(fp, "isoval = %e;\n", gamma);
fprintf(fp, "h = patch(isosurface(X,Y,Z,V,isoval),... \n");
fprintf(fp, " 'FaceColor', 'blue', ... \n");
fprintf(fp, " 'EdgeColor', 'none', ... \n");
fprintf(fp, " 'AmbientStrength', 0.2, ... \n");
fprintf(fp, " 'SpecularStrength', 0.7, ... \n");
fprintf(fp, " 'DiffuseStrength', 0.4);\n");
fprintf(fp, "isonormals(X,Y,Z,V,h);\n");
fprintf(fp, "patch(isocaps(X,Y,Z,V,isoval), ...\n");
fprintf(fp, " 'FaceColor', 'interp', ... \n");
fprintf(fp, " 'EdgeColor', 'none'); \n");
fprintf(fp, "axis([xlo xhi ylo yhi zlo zhi])\n");
fprintf(fp, "daspect([xhi-xlo, yhi-ylo, zhi-zlo])\n");
fprintf(fp, "colormap('default'); colorbar\n");
fprintf(fp, "%%axis tight\n");
fprintf(fp, "view(3) \n");
fprintf(fp, "set(gcf,'Renderer','zbuffer')\n");
fprintf(fp, "lighting phong\n");
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot2]);
fwritePlotYLabel(fp, inputNames[iplot1]);
fwritePlotZLabel(fp, inputNames[iplot3]);
fprintf(fp, "title('3D Std Dev Isosurface Plot at %s=%e',",
inputNames[iplot4],faXOut[ll*4+3]);
fprintf(fp, "'FontWeight','bold','FontSize',12)\n");
fprintf(fp, "pause(1)\n");
}
}
fclose(fp);
if (plotScilab())
printf("\nscilabrssd.sci is now available.\n");
else printf("\nmatlabrssd.m is now available.\n");
delete [] faXOut;
delete [] faYOut;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rsi2
//**/ generate intersection surfaces for multiple outputs for
//**/ display with matlab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsi2"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsi2: generate intersection surfaces for >1 outputs.\n");
printf("syntax: rsi2 (no argument needed).\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
if (nInputs < 2)
{
printf("ERROR: rsi2 requires 2 or more inputs.\n");
return 1;
}
if (nOutputs < 2)
{
printf("ERROR: rsi2 requires 2 or more outputs.\n");
return 1;
}
if (plotScilab())
{
printf("INFO: rsi2 is currently not available for scilab.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command first creates 2 or more response surfaces for 2 ");
printf("selected\n");
printf("inputs. Regions in each RS surface falling inside some ");
printf("user-specified\n");
printf("interval are carved out, and the degree of overlap ");
printf("(intersection)\n");
printf("between them will be displayed with different colors ");
printf("(blank for no\n");
printf("overlap).\n");
printf("If there are more than 2 inputs, the other inputs are set at ");
printf("their\n");
printf("midpoints or are user-specified.\n");
printf("You will be asked to select a response surface (RS) type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
//**/ set up the function approximator
int nPtsPerDim = 32;
sprintf(pString, "Grid resolution ? (32 - 256) ");
nPtsPerDim = getInt(32, 256, pString);
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
//**/ ask users to specify the 2 inputs
int iplot1, iplot2, iInd1;
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
iplot1 = iplot2 = -1;
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
iplot2 = iplot1;
while (iplot1 == iplot2)
{
sprintf(pString,"Enter the input for y axis (1 - %d), not %d : ",
nInputs, iplot1+1);
iplot2 = getInt(1, nInputs, pString);
iplot2--;
if (iplot1 == iplot2)
printf("ERROR: duplicate input number %d.\n", iplot2+1);
}
sprintf(pString,"Set other inputs at their mid points ? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2)
{
vecInpSettings[iInd1] = iLowerB[iInd1] - 1.0;
while (vecInpSettings[iInd1] < iLowerB[iInd1] ||
vecInpSettings[iInd1] > iUpperB[iInd1])
{
sprintf(pString,
"Enter nominal value for input %d (%e - %e):",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
vecInpSettings[iInd1] = getDouble(pString);
}
}
else vecInpSettings[iInd1] = 1.0;
}
}
fp = fopen("matlabrsi2.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrsi2.m.\n");
delete faPtr;
return 1;
}
fprintf(fp, "twoPlots = 1;\n");
fprintf(fp, "fs = 10;\n");
fwritePlotCLF(fp);
//**/ ask users to specify the output set
int rsiNOutputs = 2;
sprintf(pString,"How many outputs to use ? (2 - %d) ",nOutputs);
rsiNOutputs = getInt(2, nOutputs, pString);
//**/ get the collection of output set
psIVector vecRsiSet;
vecRsiSet.setLength(rsiNOutputs);
if (rsiNOutputs == nOutputs)
{
for (ii = 0; ii < rsiNOutputs; ii++) vecRsiSet[ii] = ii;
}
else
{
for (ii = 0; ii < rsiNOutputs; ii++)
{
sprintf(pString,"Enter the %d-th output index (1 - %d) : ",
ii+1, nOutputs);
vecRsiSet[ii] = getInt(1, nOutputs, pString);
vecRsiSet[ii]--;
}
}
if (rsiNOutputs > 5)
{
printf("INFO: rsi2 only shows the constrained response surfaces\n");
printf(" for the first 5 outputs and then the aggregate.\n");
}
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
int **rsiMatrix = new int*[nPtsPerDim];
for (ii = 0; ii < nPtsPerDim; ii++)
{
rsiMatrix[ii] = new int[nPtsPerDim];
for (jj = 0; jj < nPtsPerDim; jj++)
rsiMatrix[ii][jj] = rsiNOutputs;
}
//**/ interpolate
int jplot, ind, ind2, sInd, faLeng=0, count;
double Ymin, Ymax, threshU, threshL, *faXOut=NULL, *faYOut=NULL;
for (ii = 0; ii < rsiNOutputs; ii++)
{
jplot = vecRsiSet[ii];
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
faPtr->gen2DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
vecInpSettings.getDVector(), &faLeng, &faXOut,&faYOut);
Ymin = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] < Ymin) Ymin = faYOut[sInd];
Ymax = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] > Ymax) Ymax = faYOut[sInd];
printf("Ymin and Ymax = %e %e\n", Ymin, Ymax);
sprintf(pString,
"Enter the lower threshold for output %d (min = %16.8e) : ",
jplot+1, Ymin);
threshL = getDouble(pString);
sprintf(pString,
"Enter the upper threshold for output %d (max = %16.8e) : ",
jplot+1, Ymax);
threshU = getDouble(pString);
if (ii == 0)
{
fprintf(fp, "x = [\n");
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*2]);
fprintf(fp, "];\n");
fprintf(fp, "y = [\n");
for (sInd = 0; sInd < nPtsPerDim; sInd++)
fprintf(fp, "%e\n", faXOut[sInd*2+1]);
fprintf(fp, "];\n");
}
if (ii < 5)
{
fprintf(fp, "A%d = [\n", ii+1);
for (sInd = 0; sInd < faLeng; sInd++)
fprintf(fp, "%e\n", faYOut[sInd]);
fprintf(fp, "];\n");
fprintf(fp, "A%d = reshape(A%d,%d,%d);\n",ii+1,ii+1,
nPtsPerDim,nPtsPerDim);
fprintf(fp, "yLo = %e;\n", threshL);
fprintf(fp, "yHi = %e;\n", threshU);
fprintf(fp, "nA = size(A%d,1);\n", ii+1);
fprintf(fp, "[ia,ja,aa] = find(A%d<yLo);\n", ii+1);
fprintf(fp, "for ii = 1 : length(ia)\n");
fprintf(fp, " A%d(ia(ii),ja(ii)) = NaN;\n", ii+1);
fprintf(fp, "end;\n");
fprintf(fp, "n1 = length(ia);\n");
fprintf(fp, "[ia,ja,aa] = find(A%d>yHi);\n", ii+1);
fprintf(fp, "for ii = 1 : length(ia)\n");
fprintf(fp, " A%d(ia(ii),ja(ii)) = NaN;\n", ii+1);
fprintf(fp, "end;\n");
fprintf(fp, "n2 = length(ia);\n");
fprintf(fp, "if (n1 + n2 == nA*nA)\n");
fprintf(fp, " A%d(1,1) = 0;\n",ii+1);
fprintf(fp, " A%d(%d,%d) = 1;\n",ii+1,nPtsPerDim,
nPtsPerDim);
fprintf(fp, "end;\n");
if (ii == 0) fprintf(fp, "subplot(2,3,1)\n");
if (ii == 1) fprintf(fp, "subplot(2,3,2)\n");
if (ii == 2) fprintf(fp, "subplot(2,3,3)\n");
if (ii == 3) fprintf(fp, "subplot(2,3,4)\n");
if (ii == 4) fprintf(fp, "subplot(2,3,5)\n");
fprintf(fp, "contourf(x,y,A%d)\n", ii+1);
fprintf(fp, "axis([%e %e %e %e])\n",iLowerB[iplot1],
iUpperB[iplot1],iLowerB[iplot2],iUpperB[iplot2]);
fwritePlotAxes(fp);
fprintf(fp, "xlabel('%s','FontSize',fs,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, "ylabel('%s','Fontsize',fs,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp, "title('%s',",outputNames[jplot]);
fprintf(fp, "'FontWeight','bold','FontSize',fs)\n");
fprintf(fp, "colorbar\n");
}
for (sInd = 0; sInd < faLeng; sInd++)
{
ind = sInd % nPtsPerDim;
ind2 = sInd / nPtsPerDim;
if (faYOut[sInd] < threshL) rsiMatrix[ind][ind2]--;
if (faYOut[sInd] > threshU) rsiMatrix[ind][ind2]--;
}
delete [] faXOut;
delete [] faYOut;
}
//**/ write data to a matlab file
fprintf(fp, "A = [\n");
count = 0;
for (ii = 0; ii < nPtsPerDim; ii++)
for (jj = 0; jj < nPtsPerDim; jj++)
if (rsiMatrix[jj][ii] == 0) count++;
if (count == nPtsPerDim*nPtsPerDim)
{
for (ii = 0; ii < nPtsPerDim; ii++)
for (jj = 0; jj < nPtsPerDim; jj++) fprintf(fp, "0\n");
}
else
{
for (ii = 0; ii < nPtsPerDim; ii++)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
if (rsiMatrix[jj][ii] == 0) fprintf(fp, "NaN\n");
else fprintf(fp, "%d\n", rsiMatrix[jj][ii]);
}
}
}
fprintf(fp, "];\n");
fprintf(fp, "A = reshape(A,%d,%d);\n",nPtsPerDim, nPtsPerDim);
fprintf(fp, "A(%d,%d) = %e;\n", nPtsPerDim, nPtsPerDim,
(double) rsiNOutputs);
//**/ delete (9/2016)
//fprintf(fp, "if twoPlots == 1\n");
//fprintf(fp, "subplot(2,3,5), mesh(y,x,A)\n");
//fprintf(fp, "axis([%e %e %e %e])\n",iLowerB[iplot1],
// iUpperB[iplot1],iLowerB[iplot2],iUpperB[iplot2]);
//fwritePlotAxes(fp);
//fprintf(fp, "xlabel('%s','FontSize',12,'FontWeight','bold')\n",
// inputNames[iplot1]);
//fprintf(fp, "ylabel('%s','Fontsize',12,'FontWeight','bold')\n",
// inputNames[iplot2]);
//fprintf(fp, "title('Intersection Plot','FontWeight',");
//fprintf(fp, "'bold','FontSize',12)\n");
//fprintf(fp, "colorbar\n");
//fprintf(fp, "colormap(cool)\n");
//fprintf(fp, "end\n");
fprintf(fp,"subplot(2,3,6), contourf(x,y,A)\n");
fprintf(fp,"axis([%e %e %e %e])\n",iLowerB[iplot1],
iUpperB[iplot1],iLowerB[iplot2],iUpperB[iplot2]);
fwritePlotAxes(fp);
fprintf(fp,"xlabel('%s','FontSize',fs,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp,"ylabel('%s','Fontsize',fs,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp,"title('Intersection (color=deg of overlap)','FontWeight',");
fprintf(fp,"'bold','FontSize',fs)\n");
fprintf(fp,"colorbar\n");
fprintf(fp,"colormap(cool)\n");
fprintf(fp,"disp('On intersection plot, if a region has a color value");
fprintf(fp," of 2, it means it is feasible for 2 outputs.')\n");
fclose(fp);
printf("matlabrsi2.m is now available for plotting.\n");
delete faPtr;
for (ii = 0; ii < nPtsPerDim; ii++) delete [] rsiMatrix[ii];
delete [] rsiMatrix;
}
//**/ -------------------------------------------------------------
// +++ rsi3
//**/ generate 3D response surface and write the grid data to file
//**/ for display with matlab
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsi3"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsi3: generate intersection surfaces for >1 outputs\n");
printf("syntax: rsi3 (no argument needed).\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
if (nInputs < 3)
{
printf("ERROR: rsi3 requires 3 or more inputs.\n");
return 1;
}
if (nOutputs < 2)
{
printf("ERROR: rsi3 requires 2 or more outputs.\n");
return 1;
}
if (plotScilab())
{
printf("INFO: rsi3 is currently not available for scilab.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command first creates 2 or more response surfaces for 3 ");
printf("selected\n");
printf("inputs. Regions in each RS surface falling inside some ");
printf("user-specified\n");
printf("interval are carved out, and the degree of overlap ");
printf("(in input space)\n");
printf("between them will be displayed with different colors ");
printf("(blank for no\n");
printf("overlap). The 3 selected inputs are in the X, Y, Z axes.\n");
printf("If there are more than 3 inputs, the other inputs are set at ");
printf("their\n");
printf("midpoints or are user-specified.\n");
printf("You will be asked to select a response surface (RS) type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
//**/ set up the function approximator
int nPtsPerDim = 24;
sprintf(pString, "Grid resolution ? (16 - 32) ");
nPtsPerDim = getInt(16, 32, pString);
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
//**/ ask users to specify the three inputs and one output
int iplot1, iplot2, iplot3, iInd1, sInd;
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
iplot1 = iplot2 = iplot3 = -1;
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
iplot2 = iplot1;
while (iplot1 == iplot2)
{
sprintf(pString,"Enter the input for y axis (1 - %d), not %d : ",
nInputs, iplot1+1);
iplot2 = getInt(1, nInputs, pString);
iplot2--;
if (iplot1 == iplot2)
printf("ERROR: duplicate input number %d.\n",iplot2+1);
}
if (nInputs == 3) iplot3 = 3 - iplot1 - iplot2;
while (iplot3 < 0 || iplot3 == iplot1 || iplot3 == iplot2)
{
sprintf(pString,
"Enter the input for z axis (1 - %d), not %d nor %d: ",
nInputs, iplot1+1, iplot2+1);
iplot3 = getInt(1, nInputs, pString);
iplot3--;
if (iplot3 == iplot1 || iplot3 == iplot2)
printf("ERROR: duplicate input number %d.\n",iplot3+1);
}
sprintf(pString,"Set other inputs at their mid points ? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
{
vecInpSettings[iInd1] = iLowerB[iInd1] - 1.0;
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
while (vecInpSettings[iInd1] < iLowerB[iInd1] ||
vecInpSettings[iInd1] > iUpperB[iInd1])
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
fp = fopen("matlabrsi3.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrsi3.m.\n");
delete faPtr;
}
fwritePlotCLF(fp);
//**/ ask users to specify the output set
int rsiNOutputs = 1;
sprintf(pString,"How many outputs to use ? (2 - %d) ",nOutputs);
rsiNOutputs = getInt(2, nOutputs, pString);
psVector vecThreshLs, vecThreshUs;
vecThreshLs.setLength(rsiNOutputs);
vecThreshUs.setLength(rsiNOutputs);
//**/ get the collection of output set
int *rsiSet = new int[rsiNOutputs];
if (rsiNOutputs == nOutputs)
{
for (ii = 0; ii < rsiNOutputs; ii++) rsiSet[ii] = ii;
}
else
{
for (ii = 0; ii < rsiNOutputs; ii++)
{
sprintf(pString,"Enter the %d-th output index (1 - %d) : ",
ii+1, nOutputs);
rsiSet[ii] = getInt(1, nOutputs, pString);
rsiSet[ii]--;
}
}
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
//**/ generate and write response surface data
printf("Please wait while generating the RS data \n");
fprintf(fp, "xlo = %e; \n", iLowerB[iplot2]);
fprintf(fp, "xhi = %e; \n", iUpperB[iplot2]);
fprintf(fp, "ylo = %e; \n", iLowerB[iplot1]);
fprintf(fp, "yhi = %e; \n", iUpperB[iplot1]);
fprintf(fp, "zlo = %e; \n", iLowerB[iplot3]);
fprintf(fp, "zhi = %e; \n", iUpperB[iplot3]);
fprintf(fp, "X=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp, "Y=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp, "Z=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
fprintf(fp, "V=zeros(%d,%d,%d);\n",nPtsPerDim,nPtsPerDim,nPtsPerDim);
//**/ get max and min and write X, Y, Z coordinates
int faLeng, jplot, ind, count;
double GYmax, GYmin, gamma, *faXOut=NULL, *faYOut=NULL;
for (ii = 0; ii < rsiNOutputs; ii++)
{
jplot = rsiSet[ii];
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
faLeng = 0;
faPtr->gen3DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
iplot3,vecInpSettings.getDVector(),&faLeng,&faXOut,&faYOut);
GYmin = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] < GYmin) GYmin = faYOut[sInd];
GYmax = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] > GYmax) GYmax = faYOut[sInd];
printf("\nOutput %d : Ymin and Ymax found = %e %e.\n", jplot+1,
GYmin, GYmax);
//**/vecThreshL = GYmin - 0.2 * PABS(GYmin);
sprintf(pString,"Enter the lower threshold (min = %e) : ", GYmin);
vecThreshLs[ii] = getDouble(pString);
//**/vecThreshU = GYmax + 0.2 * PABS(GYmax);
sprintf(pString,"Enter the upper threshold (max = %e) : ", GYmax);
vecThreshUs[ii] = getDouble(pString);
if (ii == 0) gamma = vecThreshLs[ii];
else gamma = (gamma<vecThreshLs[ii]) ? gamma:vecThreshLs[ii];
if (ii == 0)
{
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp, "Y(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (kk = 0; kk < nPtsPerDim; kk++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+kk*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
fprintf(fp, "X(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (kk = 0; kk < nPtsPerDim; kk++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+kk*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3+1]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
fprintf(fp, "Z(:,:,%d) = [\n", jj + 1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (kk = 0; kk < nPtsPerDim; kk++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+kk*nPtsPerDim+jj;
fprintf(fp, "%e ", faXOut[ind*3+2]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
}
delete [] faXOut;
delete [] faYOut;
}
//**/ invalidate cells not inside feasible region
for (ii = 0; ii < rsiNOutputs; ii++)
{
jplot = rsiSet[ii];
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
faLeng = 0;
faPtr->gen3DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
iplot3,vecInpSettings.getDVector(),&faLeng,&faXOut,&faYOut);
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp, "V%d(:,:,%d) = [\n", ii+1, jj+1);
for (sInd = 0; sInd < nPtsPerDim; sInd++)
{
for (kk = 0; kk < nPtsPerDim; kk++)
{
ind = sInd*nPtsPerDim*nPtsPerDim+kk*nPtsPerDim+jj;
if (faYOut[ind] < vecThreshLs[ii])
{
fprintf(fp, "%e ", gamma);
count++;
}
else if (faYOut[ind] > vecThreshUs[ii])
{
fprintf(fp, "%e ", gamma);
count++;
}
else fprintf(fp, "%e ", faYOut[ind]);
}
fprintf(fp, "\n");
}
fprintf(fp, "];\n");
}
delete [] faXOut;
delete [] faYOut;
if (ii == 0) fprintf(fp, "V = V%d;\n", ii+1);
else fprintf(fp, "V = min(V, V%d);\n", ii+1);
}
//**/ prepare matlab script
double threshL, threshU;
threshL = vecThreshLs[0];
for (ii = 1; ii < rsiNOutputs; ii++)
if (vecThreshLs[ii] < threshL) threshL = vecThreshLs[ii];
threshU = vecThreshUs[0];
for (ii = 1; ii < rsiNOutputs; ii++)
if (vecThreshUs[ii] > threshU) threshU = vecThreshUs[ii];
fprintf(fp, "xt = [%e:%e:%e];\n", iLowerB[iplot2],
(iUpperB[iplot2]-iLowerB[iplot2])*0.01, iUpperB[iplot2]);
fprintf(fp, "yt = [%e:%e:%e];\n", iLowerB[iplot1],
(iUpperB[iplot1]-iLowerB[iplot1])*0.01, iUpperB[iplot1]);
fprintf(fp, "zt = [%e:%e:%e];\n", iLowerB[iplot3],
(iUpperB[iplot3]-iLowerB[iplot3])*0.01, iUpperB[iplot3]);
fprintf(fp, "isoval = %e;\n", gamma);
fprintf(fp, "h = patch(isosurface(X,Y,Z,V,isoval),... \n");
fprintf(fp, " 'FaceColor', 'blue', ... \n");
fprintf(fp, " 'EdgeColor', 'none', ... \n");
fprintf(fp, " 'AmbientStrength', 0.2, ... \n");
fprintf(fp, " 'SpecularStrength', 0.7, ... \n");
fprintf(fp, " 'DiffuseStrength', 0.4);\n");
fprintf(fp, "isonormals(X,Y,Z,V,h);\n");
fprintf(fp, "patch(isocaps(X,Y,Z,V,isoval), ...\n");
fprintf(fp, " 'FaceColor', 'interp', ... \n");
fprintf(fp, " 'EdgeColor', 'none'); \n");
fprintf(fp, "axis([xlo xhi ylo yhi zlo zhi])\n");
fprintf(fp, "daspect([%e,%e,%e])\n",iUpperB[iplot2]-iLowerB[iplot2],
iUpperB[iplot1]-iLowerB[iplot1],
iUpperB[iplot3]-iLowerB[iplot3]);
fprintf(fp, " xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp, " ylabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, " zlabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot3]);
fwritePlotAxes(fp);
fprintf(fp, "%%colormap('default'); colorbar\n");
fprintf(fp, "%%axis tight\n");
fprintf(fp, "view(3) \n");
fprintf(fp, "set(gcf,'Renderer','zbuffer')\n");
fprintf(fp, "lighting phong\n");
fprintf(fp, "cin = input('generate slices ? (y or n) ','s');\n");
fprintf(fp, "if (cin == 'y')\n");
fprintf(fp, "xin = input('axis to slide through ? (x,y,z) ','s');\n");
fprintf(fp, "for i = 1 : 101\n");
fprintf(fp, " if (xin == 'y')\n");
fprintf(fp, " h = contourslice(X,Y,Z,V,xt(i),[],[],101);\n");
fprintf(fp, " elseif (xin == 'x')\n");
fprintf(fp, " h = contourslice(X,Y,Z,V,[],yt(i),[],101);\n");
fprintf(fp, " elseif (xin == 'z')\n");
fprintf(fp, " h = contourslice(X,Y,Z,V,[],[],zt(i),101);\n");
fprintf(fp, " end\n");
fprintf(fp, " axis([%11.4e %11.4e %11.4e %11.4e %11.4e %11.4e ",
iLowerB[iplot2], iUpperB[iplot2], iLowerB[iplot1],
iUpperB[iplot1], iLowerB[iplot3], iUpperB[iplot3]);
fprintf(fp, "%11.4e %11.4e])\n",
threshL-0.2*(threshU-threshL),threshU+0.2*(threshU-threshL));
fwritePlotAxes(fp);
fprintf(fp, " xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot2]);
fprintf(fp, " ylabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, " zlabel('%s','Fontsize',12,'FontWeight','bold')\n",
inputNames[iplot3]);
fprintf(fp, "colormap('default'); colorbar\n");
fprintf(fp, "view(3) \n");
fprintf(fp, "set(gcf,'Renderer','zbuffer')\n");
fprintf(fp, "lighting phong\n");
fprintf(fp, "pause(1)\n");
fprintf(fp," if (i < 101)\n");
fprintf(fp," clf\n");
fprintf(fp," end\n");
fprintf(fp, "end\n");
fprintf(fp, "end\n");
fclose(fp);
printf("matlabrsi3.m is now available for response surface and ");
printf("contour plots\n");
delete [] rsiSet;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rsi3m
//**/ generate 3D response surfaces and find their intersection
//**/ for display with matlab (movie mode)
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsi3m"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsi3m: generate intersection surfaces for >1 outputs\n");
printf("syntax: rsi3m (no argument needed).\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
if (nInputs < 3)
{
printf("ERROR: rsi3m requires 3 or more inputs.\n");
return 1;
}
if (nOutputs < 2)
{
printf("ERROR: rsi3m requires 2 or more outputs.\n");
return 1;
}
if (plotScilab())
{
printf("INFO: rsi3m is currently not available for scilab.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command first creates 2 or more response surfaces for 3 ");
printf("selected\n");
printf("inputs. Regions in each RS surface falling inside some ");
printf("user-specified\n");
printf("interval are carved out, and the degree of overlap ");
printf("(intersection)\n");
printf("between them will be displayed with different colors ");
printf("(blank for no\n");
printf("overlap). The difference between rsi3m and rsi3 is that, ");
printf("instead of\n");
printf("using X,Y,Z axes for the 3 inputs, rsi3m uses X, Y axes for");
printf(" 2 inputs\n");
printf("and time axis for the third input so that it produces a movie ");
printf("of 2D\n");
printf("intersection plots.\n");
printf("If there are more than 3 inputs, the other inputs are set at ");
printf("their\n");
printf("midpoints or are user-specified.\n");
printf("You will be asked to select a response surface (RS) type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
//**/ set up the function approximator
int nPtsPerDim = 24;
sprintf(pString, "Grid resolution ? (16 - 32) ");
nPtsPerDim = getInt(16, 32, pString);
int faFlag = 1;
FuncApprox *faPtr = genFAInteractive(psuadeIO, faFlag);
if (faPtr == NULL) {printf("ERROR detected.\n"); return 1;}
faPtr->setNPtsPerDim(nPtsPerDim);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
//**/ ask users to specify the three inputs and one output
int iplot1, iplot2, iplot3, iInd1, sInd;
psVector vecInpSettings;
vecInpSettings.setLength(nInputs);
iplot1 = iplot2 = iplot3 = -1;
sprintf(pString, "Enter the input for x axis (1 - %d) : ", nInputs);
iplot1 = getInt(1, nInputs, pString);
iplot1--;
iplot2 = iplot1;
while (iplot1 == iplot2)
{
sprintf(pString,"Enter the input for y axis (1 - %d), not %d : ",
nInputs, iplot1+1);
iplot2 = getInt(1, nInputs, pString);
iplot2--;
if (iplot1 == iplot2)
printf("ERROR: duplicate input number %d.\n",iplot2+1);
}
if (nInputs == 3) iplot3 = 3 - iplot1 - iplot2;
while (iplot3 < 0 || iplot3 == iplot1 || iplot3 == iplot2)
{
sprintf(pString,
"Enter the input for t axis (1 - %d), not %d nor %d: ",
nInputs, iplot1+1, iplot2+1);
iplot3 = getInt(1, nInputs, pString);
iplot3--;
if (iplot3 == iplot1 || iplot3 == iplot2)
printf("ERROR: duplicate input number %d.\n",iplot3+1);
}
sprintf(pString,"Set other inputs at their mid points ? (y or n) ");
getString(pString, winput);
if (winput[0] == 'y')
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
vecInpSettings[iInd1] = 0.5*(iLowerB[iInd1]+iUpperB[iInd1]);
else vecInpSettings[iInd1] = 1.0;
}
}
else
{
for (iInd1 = 0; iInd1 < nInputs; iInd1++)
{
if (iInd1 != iplot1 && iInd1 != iplot2 && iInd1 != iplot3)
{
vecInpSettings[iInd1] = iLowerB[iInd1] - 1.0;
sprintf(pString,
"Enter nominal value for input %d (%e - %e): ",
iInd1+1, iLowerB[iInd1], iUpperB[iInd1]);
while (vecInpSettings[iInd1] < iLowerB[iInd1] ||
vecInpSettings[iInd1] > iUpperB[iInd1])
vecInpSettings[iInd1] = getDouble(pString);
}
else vecInpSettings[iInd1] = 1.0;
}
}
fp = fopen("matlabrsi3m.m", "w");
if (fp == NULL)
{
printf("ERROR: cannot open file matlabrsi3m.m.\n");
delete faPtr;
return 1;
}
fprintf(fp, "hold off\n");
fwritePlotCLF(fp);
fprintf(fp, "disp(\'Please wait while loading.\')\n");
fprintf(fp, "pause(1)\n");
//**/ ask users to specify the output set
int rsiNOutputs = 2;
sprintf(pString,"How many outputs to use ? (2 - %d) ",nOutputs);
rsiNOutputs = getInt(2, nOutputs, pString);
//**/ get the collection of output set
int *rsiSet = new int[rsiNOutputs];
if (rsiNOutputs == nOutputs)
{
for (ii = 0; ii < rsiNOutputs; ii++) rsiSet[ii] = ii;
}
else
{
for (ii = 0; ii < rsiNOutputs; ii++)
{
sprintf(pString,"Enter the %d-th output index (1 - %d) : ",
ii+1, nOutputs);
rsiSet[ii] = getInt(1, nOutputs, pString);
rsiSet[ii]--;
}
}
int jplot, faLeng;
double *faXOut=NULL, *faYOut=NULL, GYmax, GYmin, threshL, threshU;
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
//**/ generate and write response surface data
printf("Please wait while generating the RS data \n");
for (jj = 0; jj < nPtsPerDim; jj++)
fprintf(fp, "M%d = %e * ones(%d);\n", jj+1, 1.0*rsiNOutputs,
nPtsPerDim);
for (ii = 0; ii < rsiNOutputs; ii++)
{
jplot = rsiSet[ii];
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
faLeng = 0;
faPtr->gen3DGridData(sampleInputs,vecFaYIn.getDVector(),iplot1,iplot2,
iplot3,vecInpSettings.getDVector(),&faLeng,&faXOut,&faYOut);
GYmin = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] < GYmin) GYmin = faYOut[sInd];
GYmax = faYOut[0];
for (sInd = 1; sInd < faLeng; sInd++)
if (faYOut[sInd] > GYmax) GYmax = faYOut[sInd];
for (jj = 0; jj < nPtsPerDim; jj++)
{
printf(".");
fflush(stdout);
//**/ output the response surface data
fprintf(fp, "A%d_%d = [\n", ii+1, jj+1);
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faYOut[sInd+jj]);
fprintf(fp, "];\n");
fprintf(fp, "A%d_%d = reshape(A%d_%d,%d,%d);\n", ii+1, jj+1,
ii+1, jj+1, nPtsPerDim, nPtsPerDim);
//**/ x and y data only needed to output once
if (ii == 0 && jj == 0)
{
fprintf(fp, "x = [\n");
for (sInd = 0; sInd < faLeng; sInd+=nPtsPerDim*nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*3]);
fprintf(fp, "];\n");
fprintf(fp, "y = [\n");
for (sInd = 0; sInd < nPtsPerDim*nPtsPerDim; sInd+=nPtsPerDim)
fprintf(fp, "%e\n", faXOut[sInd*3+1]);
fprintf(fp, "];\n");
}
}
delete [] faXOut;
delete [] faYOut;
printf("\nOutput %d : Ymin and Ymax found = %e %e.\n", jplot+1,
GYmin, GYmax);
//**/threshL = GYmin - 0.2 * PABS(GYmin);
sprintf(pString,"Enter the lower threshold (min = %e) : ", GYmin);
threshL = getDouble(pString);
//**/threshU = GYmax + 0.2 * PABS(GYmax);
sprintf(pString,"Enter the upper threshold (max = %e) : ", GYmax);
threshU = getDouble(pString);
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp, "B%d_%d = A%d_%d;\n",ii+1,jj+1,ii+1,jj+1);
fprintf(fp, "nA = size(A%d_%d,1);\n", ii+1, jj+1);
fprintf(fp, "n1 = 0;\n");
fprintf(fp, "n2 = 0;\n");
if (threshL > GYmin)
{
fprintf(fp, "yLo = %e;\n", threshL);
fprintf(fp, "[ia,ja,aa] = find(A%d_%d<yLo);\n",ii+1,jj+1);
fprintf(fp, "for ii = 1 : length(ia)\n");
fprintf(fp, " B%d_%d(ia(ii),ja(ii))=NaN;\n",ii+1,jj+1);
fprintf(fp, " M%d(ia(ii),ja(ii))=M%d(ia(ii),ja(ii))-1;\n",
jj+1,jj+1);
fprintf(fp, "end;\n");
fprintf(fp, "n1 = length(ia);\n");
}
if (threshU < GYmax)
{
fprintf(fp, "yHi = %e;\n", threshU);
fprintf(fp, "[ia,ja,aa] = find(A%d_%d>yHi);\n",ii+1,jj+1);
fprintf(fp, "for ii = 1 : length(ia)\n");
fprintf(fp, " B%d_%d(ia(ii),ja(ii))=NaN;\n",ii+1,jj+1);
fprintf(fp, " M%d(ia(ii),ja(ii))=M%d(ia(ii),ja(ii))-1;\n",
jj+1,jj+1);
fprintf(fp, "end;\n");
fprintf(fp, "n1 = length(ia);\n");
}
fprintf(fp, "if (n1+n2 == nA*nA)\n");
fprintf(fp, " B%d_%d(1,1)=0;\n",ii+1,jj+1);
fprintf(fp, " B%d_%d(%d,%d)=1;\n",ii+1,jj+1,
nPtsPerDim,nPtsPerDim);
fprintf(fp, "end;\n");
}
}
for (jj = 0; jj < nPtsPerDim; jj++)
{
fprintf(fp, "[ia,ja,aa] = find(M%d == 0);\n", jj+1);
fprintf(fp, "nM = size(M%d,1);\n", jj+1);
fprintf(fp, "for ii = 1 : length(ia)\n");
fprintf(fp, " M%d(ia(ii),ja(ii)) = NaN;\n", jj+1);
fprintf(fp, "end;\n");
fprintf(fp, "if (length(ia) == nM*nM)\n");
fprintf(fp, " M%d(1,1) = 0;\n", jj+1);
fprintf(fp, " M%d(nM,nM) = %e;\n", jj+1, 1.0*rsiNOutputs);
fprintf(fp, "end;\n");
fprintf(fp, "Mmax = max(max(M%d));\n", jj+1);
fprintf(fp, "if (Mmax ~= %d)\n", rsiNOutputs);
fprintf(fp, " M%d(%d,%d) = %d;\n", jj+1, nPtsPerDim,
nPtsPerDim, rsiNOutputs);
fprintf(fp, "end;\n");
fprintf(fp, "Mmin = min(min(M%d));\n", jj+1);
fprintf(fp, "if (Mmin ~= 0)\n");
fprintf(fp, " M%d(1,1) = 0;\n", jj+1);
fprintf(fp, "end;\n");
}
//**/ create matlab movie
for (jj = 0; jj < nPtsPerDim; jj++)
{
vecInpSettings[iplot3] = (iUpperB[iplot3] - iLowerB[iplot3]) *
jj / (nPtsPerDim - 1.0) + iLowerB[iplot3];
fprintf(fp, "disp(\'Plotting frame %d of %d\')\n",jj+1,nPtsPerDim);
fprintf(fp, "subplot(2,3,1), contourf(x,y,B1_%d)\n", jj+1);
fwritePlotAxes(fp);
fprintf(fp,"title(\'Contour Plot for %s\',",outputNames[rsiSet[0]]);
fprintf(fp, "'FontSize',12,'FontWeight','bold')\n");
fprintf(fp, "xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, "ylabel('%s','FontSize',12,'FontWeight','bold');\n",
inputNames[iplot2]);
fprintf(fp, "subplot(2,3,2), contourf(x,y,B2_%d)\n", jj+1);
fwritePlotAxes(fp);
fprintf(fp,"title(\'Contour Plot for %s\',",outputNames[rsiSet[1]]);
fprintf(fp, "'FontSize',12,'FontWeight','bold')\n");
fprintf(fp, "xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, "ylabel('%s','FontSize',12,'FontWeight','bold');\n",
inputNames[iplot2]);
if (rsiNOutputs > 2)
{
fprintf(fp, "subplot(2,3,3), contourf(x,y,B3_%d)\n", jj+1);
fwritePlotAxes(fp);
fprintf(fp,"title(\'Contour Plot for %s\',",
outputNames[rsiSet[2]]);
fprintf(fp, "'FontSize',12,'FontWeight','bold')\n");
fprintf(fp, "xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, "ylabel('%s','FontSize',12,'FontWeight','bold');\n",
inputNames[iplot2]);
}
if (rsiNOutputs > 3)
{
fprintf(fp, "subplot(2,3,4), contourf(x,y,B4_%d)\n", jj+1);
fwritePlotAxes(fp);
fprintf(fp, "title(\'Contour Plot for ");
fprintf(fp, "%s\','FontSize',12,'FontWeight','bold')\n",
outputNames[rsiSet[3]]);
fprintf(fp, "xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, "ylabel('%s','FontSize',12,'FontWeight','bold');\n",
inputNames[iplot2]);
}
if (rsiNOutputs > 4)
{
fprintf(fp, "subplot(2,3,5), contourf(x,y,B5_%d)\n", jj+1);
fwritePlotAxes(fp);
fprintf(fp, "title(\'Contour Plot for ");
fprintf(fp, "%s\','FontSize',12,'FontWeight','bold')\n",
outputNames[rsiSet[4]]);
fprintf(fp, "xlabel('%s','FontSize',12,'FontWeight','bold')\n",
inputNames[iplot1]);
fprintf(fp, "ylabel('%s','FontSize',12,'FontWeight','bold');\n",
inputNames[iplot2]);
}
//**/if (rsiNOutputs <= 3)
//**/ fprintf(fp, "subplot(2,3,[4 5]), surfl(x,y,M%d)\n", jj+1);
//**/else
//**/ fprintf(fp, "subplot(2,3,5), surfl(x,y,M%d)\n", jj+1);
//**/fwritePlotAxes(fp);
//**/fprintf(fp,"xlabel('%s','FontSize',12,'FontWeight','bold')\n",
//**/ inputNames[iplot1]);
//**/fprintf(fp,"ylabel('%s','FontSize',12,'FontWeight','bold');\n",
//**/ inputNames[iplot2]);
//**/fprintf(fp, "title('Intersection','FontSize',12,");
//**/fprintf(fp, "'FontWeight','bold')\n");
//**/fprintf(fp, "colorbar\n");
fprintf(fp, "subplot(2,3,6), contourf(x,y,M%d)\n",jj+1);
fwritePlotAxes(fp);
fwritePlotXLabel(fp, inputNames[iplot1]);
fwritePlotYLabel(fp, inputNames[iplot2]);
fprintf(fp, "title('Intersection: Input %s = %11.4e',",
inputNames[iplot3], vecInpSettings[iplot3]);
fprintf(fp, "'FontSize',12,'FontWeight','bold')\n");
fprintf(fp, "colorbar\n");
fprintf(fp, "colormap(jet)\n");
fprintf(fp,"pause(1)\n");
}
//**/ Sept 2010: not good enough, create rsi3m
//**/fprintf(fp,"disp(\'Press enter to view 3D shape plot\')\n");
//**/fprintf(fp,"pause\n");
//**/fprintf(fp,"hold off\n");
//**/fprintf(fp,"clf\n");
//**/fprintf(fp, "yLo = %e;\n", threshL);
//**/fprintf(fp, "yHi = %e;\n", threshU);
//**/for (jj = 0; jj < nPtsPerDim; jj++)
//**/{
//**/ vecInpSettings[iplot3] = (iUpperB[iplot3] - iLowerB[iplot3]) *
//**/ jj/(nPtsPerDim - 1.0) + iLowerB[iplot3];
//**/ fprintf(fp, "B%d = ones(%d) * NaN;\n", jj+1, nPtsPerDim);
//**/ fprintf(fp, "[ia,ja,aa] = find(M%d==%d);\n", jj+1,rsiNOutputs);
//**/ fprintf(fp, "for ii = 1 : length(ia)\n");
//**/ fprintf(fp, " B%d(ia(ii),ja(ii)) = %e;\n", jj+1,
//**/ vecInpSettings[iplot3]);
//**/ fprintf(fp, "end;\n");
//**/ fprintf(fp, "if (length(ia) == 0)\n");
//**/ fprintf(fp, " B%d(1,1) = 0;\n", jj+1);
//**/ fprintf(fp, " B%d(%d,%d) = 1;\n",jj+1,nPtsPerDim,nPtsPerDim);
//**/ fprintf(fp, "end;\n");
//**/ //**/fprintf(fp, "surf(x,y,B%d,M%d)\n",jj+1,jj+1);
//**/ fprintf(fp, "surf(x,y,B%d)\n",jj+1);
//**/ if (jj == 0) fprintf(fp, "hold on;\n");
//**/}
//**/fprintf(fp, "rotate3d on\n");
fclose(fp);
printf("matlabrsi3m.m is now available for response surface and ");
printf("contour plots\n");
delete [] rsiSet;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rssd_ua
//**/ uncertainty analysis of standard deviations from RS fit
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rssd_ua"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rssd_ua: generate pdf for std. deviations from RS fit\n");
printf("syntax: rssd_ua (no argument needed).\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data to analyze (load sample first).\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command first creates a response surface for a ");
printf("selected output.\n");
printf("It then creates a large sample from the input distributions and\n");
printf("propagates it through the response surface, collecting ");
printf("at each sample\n");
printf("point its prediction uncertainty (thus, this command requires ");
printf("the use\n");
printf("of a stochastic response surface such as regression, GP ");
printf("or Kriging),\n");
printf("and finally creating a histogram of the prediction ");
printf("uncertainties.\n");
printf("You will be asked to select a response surface (RS) type.\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ choose function approximator
printf("This command works with the following response surfaces:\n");
printf("1. Linear regression\n");
printf("2. Quadratic regression\n");
printf("3. cubic regression\n");
printf("4. quartic regression\n");
#ifdef HAVE_TPROS
printf("5. GP1 (MacKay implementation)\n");
printf("6. GP3 (Tong implementation)\n");
printf("7. MarsBagg\n");
printf("8. Tree GP\n");
printf("9. Kriging\n");
sprintf(pString, "Enter your choice: (1, 2, ..., 9) ");
int faType = getInt(1, 9, pString);
#else
printf("5. GP3 (Tong implementation)\n");
printf("6. MarsBagg\n");
printf("7. Tree GP\n");
printf("8. Kriging\n");
sprintf(pString, "Enter your choice: (1, 2, ..., 8) ");
int faType = getInt(1, 8, pString);
#endif
if (faType == 1) faType = PSUADE_RS_REGR1;
else if (faType == 2) faType = PSUADE_RS_REGR2;
else if (faType == 3) faType = PSUADE_RS_REGR3;
else if (faType == 4) faType = PSUADE_RS_REGR4;
#ifdef HAVE_TPROS
else if (faType == 5) faType = PSUADE_RS_GP1;
else if (faType == 6) faType = PSUADE_RS_GP3;
else if (faType == 7) faType = PSUADE_RS_MARSB;
else if (faType == 8) faType = PSUADE_RS_TGP;
else if (faType == 9) faType = PSUADE_RS_KR;
#else
else if (faType == 5) faType = PSUADE_RS_GP3;
else if (faType == 6) faType = PSUADE_RS_MARSB;
else if (faType == 7) faType = PSUADE_RS_TGP;
else if (faType == 8) faType = PSUADE_RS_KR;
#endif
//**/ ask users to specify one output
int jplot = 0;
sprintf(pString, "Enter the output number (1 - %d) : ",nOutputs);
jplot = getInt(1, nOutputs, pString);
jplot--;
//**/ set up function approximator
printf("rssd_ua: setting up function approximator\n");
int iOne=1, sInd;
FuncApprox *faPtr = genFA(faType, nInputs, iOne, nSamples);
if (faPtr == NULL) {printf("ERROR detected in RS.\n"); return 1;}
psVector vecFaYIn;
vecFaYIn.setLength(nSamples);
for (sInd = 0; sInd < nSamples; sInd++)
vecFaYIn[sInd] = sampleOutputs[sInd*nOutputs+jplot];
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(outputLevel);
faPtr->initialize(sampleInputs,vecFaYIn.getDVector());
//**/ generate a quasi-Monte Carlo sample
printf("rssd_ua: creating a large sample for constructing PDF\n");
Sampling *sampPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LPTAU);
sampPtr->setPrintLevel(0);
sampPtr->setInputBounds(nInputs, iLowerB, iUpperB);
sampPtr->setOutputParams(1);
int count = 100000;
sampPtr->setSamplingParams(count, -1, 1);
sampPtr->initialize(0);
psVector vecXT, vecYT, vecWT;
psIVector vecST;
vecXT.setLength(count*nInputs);
vecYT.setLength(count);
vecWT.setLength(count);
vecST.setLength(count);
sampPtr->getSamples(count,nInputs,1,vecXT.getDVector(),
vecYT.getDVector(), vecST.getIVector());
faPtr->evaluatePointFuzzy(count,vecXT.getDVector(),vecYT.getDVector(),
vecWT.getDVector());
//**/ put the scale results in vecYT
psVector vecSW;
vecSW.setLength(count);
for (ii = 0; ii < count; ii++)
{
if (vecYT[ii] == 0.0) vecSW[ii] = vecWT[ii];
else vecSW[ii] = vecWT[ii]/vecYT[ii];
}
//**/ plot the result
char fname[100];
if (plotScilab()) strcpy(fname, "scilabrssdua.sci");
else strcpy(fname, "matlabrssdua.m");
fp = fopen(fname, "w");
if (fp != NULL)
{
strcpy(pString," Col 1: std dev, Col 2: scaled std dev, Col 3: YOut");
fwriteComment(fp, pString);
fprintf(fp, "Y = [\n");
for (ss = 0; ss < nSamples; ss++)
fprintf(fp, " %24.16e %24.16e %24.16e\n",vecWT[ss],vecSW[ss],
vecYT[ss]);
fprintf(fp, "];\n");
if (plotScilab())
{
fwritePlotCLF(fp);
fprintf(fp, "subplot(1,2,1)\n");
fprintf(fp, "ymin = min(Y(:,1));\n");
fprintf(fp, "ymax = max(Y(:,1));\n");
fprintf(fp, "ywid = 0.1 * (ymax - ymin);\n");
fprintf(fp, "if (ywid < 1.0e-12)\n");
fprintf(fp, " disp('range too small.')\n");
fprintf(fp, " halt\n");
fprintf(fp, "end;\n");
fprintf(fp, "histplot(10, Y(:,1)/ywid, style=2);\n");
fprintf(fp, "a = gce();\n");
fprintf(fp, "a.children.fill_mode = \"on\";\n");
fprintf(fp, "a.children.thickness = 2;\n");
fprintf(fp, "a.children.foreground = 0;\n");
fprintf(fp, "a.children.background = 2;\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prediction Std. Dev. Distribution");
fwritePlotXLabel(fp, "Output Std. Dev.");
fwritePlotYLabel(fp, "Probabilities");
fprintf(fp, "subplot(1,2,2)\n");
fprintf(fp, "ymin = min(Y(:,2));\n");
fprintf(fp, "ymax = max(Y(:,2));\n");
fprintf(fp, "ywid = 0.1 * (ymax - ymin);\n");
fprintf(fp, "if (ywid < 1.0e-12)\n");
fprintf(fp, " disp('range too small.')\n");
fprintf(fp, " halt\n");
fprintf(fp, "end;\n");
fprintf(fp, "histplot(10, Y(:,2)/ywid, style=2);\n");
fprintf(fp, "a = gce();\n");
fprintf(fp, "a.children.fill_mode = \"on\";\n");
fprintf(fp, "a.children.thickness = 2;\n");
fprintf(fp, "a.children.foreground = 0;\n");
fprintf(fp, "a.children.background = 2;\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prediction Scaled Std. Dev. Distribution");
fwritePlotXLabel(fp, "Output Scaled Std. Dev.");
fwritePlotYLabel(fp, "Probabilities");
}
else
{
fwritePlotCLF(fp);
fprintf(fp, "twoPlots = 0;\n");
fprintf(fp, "if (twoPlots == 1)\n");
fprintf(fp, "subplot(1,2,1)\n");
fprintf(fp, "end;\n");
if (nSamples > 500) fprintf(fp, "[nk,xk]=hist(Y(:,1),20);\n");
else fprintf(fp, "[nk,xk]=hist(Y(:,1),10);\n");
fprintf(fp, "bar(xk,nk/%d,1.0)\n",nSamples);
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prediction Std. Dev. Distribution");
fwritePlotXLabel(fp, "Output Std. Dev.");
fwritePlotYLabel(fp, "Probabilities");
fprintf(fp, "subplot(1,2,2)\n");
fprintf(fp, "end;\n");
if (nSamples > 500) fprintf(fp, "[nk,xk]=hist(Y(:,2),20);\n");
else fprintf(fp, "[nk,xk]=hist(Y(:,2),10);\n");
fprintf(fp, "bar(xk,nk/%d,1.0)\n",nSamples);
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Prediction Scaled Std. Dev. Distribution");
fwritePlotXLabel(fp, "Output Scaled Std. Dev.");
fwritePlotYLabel(fp, "Probabilities");
fprintf(fp, "if (twoPlots == 1)\n");
fprintf(fp, "figure(2)\n");
fprintf(fp, "Yk = sort(Y(:,1));\n");
fprintf(fp, "Xk = 1 : %d;\n", nSamples);
fprintf(fp, "Xk = Xk / %d;\n", nSamples);
fprintf(fp, "subplot(1,2,2)\n");
fprintf(fp, "plot(Yk, Xk, 'lineWidth',3)\n");
fwritePlotAxes(fp);
fwritePlotTitle(fp, "Cumulative Std Dev Distribution");
fwritePlotXLabel(fp, "Cumulative Std. Dev.");
fwritePlotYLabel(fp, "Probabilities");
fprintf(fp, "end;\n");
}
printOutTS(PL_INFO,"Output distribution plot is now in %s.\n",fname);
fclose(fp);
}
else
{
printOutTS(PL_ERROR,"ERROR: cannot open file %s.\n", fname);
}
//**/ clean up
delete sampPtr;
delete faPtr;
}
//**/ -------------------------------------------------------------
// +++ rsmeb
//**/ bootstrapped main effect analysis using replicated LH
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsmeb"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsmeb: main effect analysis on response surface\n");
printf("syntax: rsmeb (no argument needed)\n");
printf("This command perform main effect analysis on the response\n");
printf("surface built from the loaded sample.\n");
printf("NOTE: This analysis supports other than uniform ");
printf("distributions for the\n");
printf(" inputs. Simply prescribe the distributions ");
printf("in the data file and\n");
printf(" turn on use_input_pdfs in ANALYSIS.\n");
printf("NOTE: This analysis is equivalent to rssobol1b but using ");
printf("a different\n");
printf(" algorithm.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
//**/ header message
printAsterisks(PL_INFO, 0);
printf("This analysis performs main effect analysis on the ");
printf("response surface\n");
printf("constructed from the loaded sample (with bootstrapping).\n");
printf("This is an alternative to rssobol1b (for cross-checking).\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
if (faType == PSUADE_RS_MARSB) faType = PSUADE_RS_MARS;
int nLHS=200000;
if (psConfig_.RSExpertModeIsOn())
{
sprintf(pString,
"Sample size for generating distribution? (10000 - 500000) ");
nLHS = getInt(10000, 500000, pString);
}
sprintf(pString, "How many bootstrapped samples to use (10 - 300) : ");
int numBS = getInt(10, 300, pString);
//**/ create replicated LH sample => nLHS, LHSInputs, LHSOutputs
int nReps=100, iOne=1, iZero=0;
Sampling *samPtr;
printEquals(PL_INFO, 0);
printf("Phase 1 of 2: create a replicated LH sample\n");
psVector vecLHSInps, vecLHSOuts;
psIVector vecLHSStas;
vecLHSInps.setLength(nLHS*nInputs);
vecLHSOuts.setLength(nLHS);
vecLHSStas.setLength(nLHS);
samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_LHS);
samPtr->setPrintLevel(0);
samPtr->setInputBounds(nInputs, iLowerB, iUpperB);
samPtr->setInputParams(nInputs, NULL, NULL, NULL);
samPtr->setOutputParams(iOne);
samPtr->setSamplingParams(nLHS, nReps, iZero);
psConfig_.SamExpertModeSaveAndReset();
samPtr->initialize(0);
psConfig_.SamExpertModeRestore();
samPtr->getSamples(nLHS, nInputs, iOne, vecLHSInps.getDVector(),
vecLHSOuts.getDVector(),vecLHSStas.getIVector());
delete samPtr;
//**/ convert the sample to different PDF, if needed
PDFManager *pdfman;
psVector vecTT, vecLower, vecUpper;
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
int usePDFs = pPtr.intData_;
if (usePDFs == 1)
{
pdfman = new PDFManager();
psuadeIO->updateAnalysisSection(-1,-1,-1,0,-1, -1);
psuadeIO->updateMethodSection(PSUADE_SAMP_MC, -1, -1, -1, -1);
pdfman->initialize(psuadeIO);
vecTT.setLength(nLHS*nInputs);
vecUpper.load(nInputs, iUpperB);
vecLower.load(nInputs, iLowerB);
pdfman->invCDF(nLHS, vecLHSInps, vecTT, vecLower, vecUpper);
for (ii = 0; ii < nLHS*nInputs; ii++) vecLHSInps[ii] = vecTT[ii];
delete pdfman;
}
//**/ create response surface ==> faPtr
FuncApprox *faPtr;
printEquals(PL_INFO, 0);
printf("Phase 2 of 2: create response surfaces and run main effects\n");
psVector vecYT;
if (nOutputs > 1)
{
vecYT.setLength(nSamples);
for (ss = 0; ss < nSamples; ss++)
vecYT[ss] = sampleOutputs[ss*nOutputs+outputID];
}
else vecYT.load(nSamples,sampleOutputs);
int ind, nSamples2;
psIVector vecMebInds;
psVector vecTmpInps, vecTmpOuts, vecMeStore;
vecTmpInps.setLength(nSamples*nInputs);
vecTmpOuts.setLength(nSamples);
vecMebInds.setLength(nSamples);
vecMeStore.setLength((numBS+2)*nInputs);
MainEffectAnalyzer *meAnalyzer = new MainEffectAnalyzer();
pData *pd = NULL;
aData adata;
adata.nInputs_ = nInputs;
adata.nOutputs_ = 1;
adata.nSamples_ = nLHS;
adata.outputID_ = 0;
adata.sampleInputs_ = vecLHSInps.getDVector();
adata.sampleOutputs_ = vecLHSOuts.getDVector();
adata.nSubSamples_ = nLHS / nReps;
adata.iLowerB_ = iLowerB;
adata.iUpperB_ = iUpperB;
adata.printLevel_ = -1;
adata.ioPtr_ = psuadeIO;
psConfig_.AnaExpertModeSaveAndReset();
psConfig_.RSExpertModeSaveAndReset();
for (kk = 0; kk < numBS; kk++)
{
printf("rsmeb: ITERATION %d (of %d)\n", kk+1, numBS);
//**/ random draw
for (ss = 0; ss < nSamples; ss++) vecMebInds[ss] = 0;
ss = nSamples2 = 0;
while (ss < nSamples)
{
ind = PSUADE_rand() % nSamples;
if (vecMebInds[ind] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecTmpInps[nSamples2*nInputs+ii] = sampleInputs[ind*nInputs+ii];
vecTmpOuts[nSamples2] = vecYT[ind];
vecMebInds[ind] = 1;
nSamples2++;
}
ss++;
}
faPtr = genFA(faType, nInputs, -1, nSamples2);
faPtr->setNPtsPerDim(32);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(0);
faPtr->initialize(vecTmpInps.getDVector(),vecTmpOuts.getDVector());
faPtr->evaluatePoint(nLHS,vecLHSInps.getDVector(),
vecLHSOuts.getDVector());
//**/ perform main effect analysis
meAnalyzer->analyze(adata);
pd = psuadeIO->getAuxData();
for (ii = 0; ii < nInputs; ii++)
{
if (pd->dbleData_ > 0)
vecMeStore[kk*nInputs+ii] = pd->dbleArray_[ii]/pd->dbleData_;
else vecMeStore[kk*nInputs+ii] = pd->dbleArray_[ii];
}
pd->clean();
delete faPtr;
}
//**/ compute main effects
double mean, stdev;
printAsterisks(PL_INFO, 0);
printf("rsmeb main effect analysis (normalized by total variance)\n");
printEquals(PL_INFO, 0);
for (ii = 0; ii < nInputs; ii++)
{
mean = 0.0;
for (kk = 0; kk < numBS; kk++) mean += vecMeStore[kk*nInputs+ii];
mean /= numBS;
vecMeStore[numBS*nInputs+ii] = mean;
stdev = 0.0;
for (kk = 0; kk < numBS; kk++)
stdev += pow(vecMeStore[kk*nInputs+ii]-mean, 2.0);
stdev = sqrt(stdev/(numBS-1));
vecMeStore[(numBS+1)*nInputs+ii] = stdev;
printf("Input %6d = %12.4e (stdev = %12.4e)\n",ii+1,mean,stdev);
}
printAsterisks(PL_INFO, 0);
//**/ generate matlab/scilab file
fp = NULL;
if (plotScilab()) fp = fopen("scilabrsmeb.sci","w");
else fp = fopen("matlabrsmeb.m","w");
if (fp == NULL) printf("ERROR: cannot open plot file.\n");
else
{
strcpy(pString," This file contains main effect ");
fwriteComment(fp, pString);
strcpy(pString," with error bars coming from bootstrapping.");
fwriteComment(fp, pString);
strcpy(pString," to select the most important ones to display,");
fwriteComment(fp, pString);
strcpy(pString," set sortFlag = 1 and set nn to be the number");
fwriteComment(fp, pString);
strcpy(pString," of inputs to display.\n");
fwriteComment(fp, pString);
fprintf(fp, "sortFlag = 0;\n");
fprintf(fp, "nn = %d;\n", nInputs);
fprintf(fp, "Means = [\n");
for (ii = 0; ii < nInputs; ii++)
fprintf(fp,"%24.16e\n",vecMeStore[numBS*nInputs+ii]);
fprintf(fp, "];\n");
fprintf(fp, "Stds = [\n");
for (ii = 0; ii < nInputs; ii++)
fprintf(fp,"%24.16e\n",vecMeStore[(numBS+1)*nInputs+ii]);
fprintf(fp, "];\n");
if (inputNames == NULL)
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1);
if (plotScilab()) fprintf(fp,"'X%d'];\n",nInputs);
else fprintf(fp,"'X%d'};\n",nInputs);
}
else
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++)
{
if (inputNames[ii] != NULL)
fprintf(fp,"'%s',",inputNames[ii]);
else fprintf(fp,"'X%d',",ii+1);
}
if (plotScilab())
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'];\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'];\n",nInputs);
}
else
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'};\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'};\n",nInputs);
}
}
fwriteHold(fp, 0);
fprintf(fp, "if (sortFlag == 1)\n");
if (plotScilab())
fprintf(fp, " [Means, I2] = gsort(Means);\n");
else fprintf(fp, " [Means, I2] = sort(Means,'descend');\n");
fprintf(fp, " Stds = Stds(I2);\n");
fprintf(fp, " I2 = I2(1:nn);\n");
fprintf(fp, " Means = Means(1:nn);\n");
fprintf(fp, " Stds = Stds(1:nn);\n");
fprintf(fp, " Str = Str(I2);\n");
fprintf(fp, "end\n");
fprintf(fp, "ymin = min(Means-Stds);\n");
fprintf(fp, "ymax = max(Means+Stds);\n");
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
if (plotScilab()) fprintf(fp, "drawlater\n");
fprintf(fp, "bar(Means,0.8);\n");
fprintf(fp, "for ii = 1:nn\n");
fprintf(fp, " if (ii == 1)\n");
fwriteHold(fp, 1);
fprintf(fp, " end;\n");
fprintf(fp, " XX = [ii ii];\n");
fprintf(fp, " d1 = Means(ii)-Stds(ii);\n");
fprintf(fp, " d2 = Means(ii)+Stds(ii);\n");
fprintf(fp, " if (d1 < 0)\n");
fprintf(fp, " d1 = 0.0;\n");
fprintf(fp, " end;\n");
fprintf(fp, " YY = [d1 d2];\n");
fprintf(fp, " plot(XX,YY,'-ko','LineWidth',3.0,'MarkerEdgeColor',");
fprintf(fp, "'k','MarkerFaceColor','g','MarkerSize',13)\n");
fprintf(fp, "end;\n");
fwritePlotAxes(fp);
if (plotScilab())
{
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, ymin; nn+1, ymax];\n");
fprintf(fp, "newtick = a.x_ticks;\n");
fprintf(fp, "newtick(2) = [1:nn]';\n");
fprintf(fp, "newtick(3) = Str';\n");
fprintf(fp, "a.x_ticks = newtick;\n");
fprintf(fp, "a.x_label.font_size = 3;\n");
fprintf(fp, "a.x_label.font_style = 4;\n");
}
else
{
fprintf(fp, "axis([0 nn+1 ymin ymax])\n");
fprintf(fp, "set(gca,'XTickLabel',[]);\n");
fprintf(fp, "th=text(1:nn, repmat(ymin-0.05*(ymax-ymin),nn,1),Str,");
fprintf(fp, "'HorizontalAlignment','left','rotation',90);\n");
fprintf(fp, "set(th, 'fontsize', 12)\n");
fprintf(fp, "set(th, 'fontweight', 'bold')\n");
}
fwritePlotTitle(fp,"Main Effects (with bootstrap)");
fwritePlotYLabel(fp, "Main Effects (Normalized)");
if (plotScilab())
{
fprintf(fp, "drawnow\n");
printf("Scilab plot for main effect is in scilabrsmebb.sci.\n");
}
else printf("Matlab plot for main effect is in matlabrsmeb.m.\n");
fclose(fp);
}
delete meAnalyzer;
faPtr = NULL;
psConfig_.AnaExpertModeRestore();
psConfig_.RSExpertModeRestore();
}
//**/ -------------------------------------------------------------
// +++ rsieb
//**/ bootstrapped pairwise effect analysis using replicated OA
//**/ -------------------------------------------------------------
else if (!strcmp(command, "rsieb"))
{
sscanf(lineIn,"%s %s",command,winput);
if (!strcmp(winput, "-h"))
{
printf("rsieb: two-parameter effect analysis on response surface\n");
printf("syntax: rsieb (no argument needed)\n");
printf("This command perform two parameter effect analysis on the\n");
printf("response surface built from the loaded sample.\n");
printf("NOTE: This analysis supports different distributions\n");
printf(" for the inputs. Simply prescribe the distributions in\n");
printf(" the data file and turn on use_input_pdfs in ANALYSIS.\n");
printf("NOTE: This analysis is equivalent to rssobol2b but using\n");
printf(" a different algorithm.\n");
return 0;
}
if (psuadeIO == NULL || sampleOutputs == NULL)
{
printf("ERROR: no data (load sample first).\n");
return 1;
}
if (nInputs <= 2)
{
printf("INFO: nInputs <=2 -> no point of performing this analysis.\n");
return 1;
}
printAsterisks(PL_INFO, 0);
printf("This command computes second-order sensitivity ");
printf("indices using the\n");
printf("response surface built from the loaded ");
printf("sample (with bootstrapping).\n");
printf("This is an alternative to rssobol2b (for cross-checking).\n");
printDashes(PL_INFO, 0);
printf("Proceed ? (y or n to abort) ");
scanf("%s", lineIn2);
fgets(winput,5000,stdin);
if (lineIn2[0] != 'y') return 0;
//**/ query user for which output and which response surface type
sprintf(pString, "Enter output number (1 - %d) : ", nOutputs);
outputID = getInt(1, nOutputs, pString);
outputID--;
faType = -1;
sprintf(pString, "Enter your response surface choice ? ");
while (faType < 0 || faType > PSUADE_NUM_RS)
{
writeFAInfo(outputLevel_);
faType = getFAType(pString);
}
if (faType < 0)
{
printf("ERROR: response surface type not currently available.\n");
return 1.0;
}
if (faType == PSUADE_RS_MARSB) faType = PSUADE_RS_MARS;
//**/ query user for sampling information
int nOA, nOA1;
sprintf(pString, "How many bootstrapped samples to use (1 - 100) : ");
int numBS = getInt(1, 100, pString);
//**/ create replicated OA sample => nOA, OAInputs, OAOutputs
int iOne=1, iZero=0, nReps;
Sampling *samPtr;
printEquals(PL_INFO, 0);
printf("Phase 1 of 2: create a replicated OA sample\n");
nOA1 = 293;
nOA = nOA1 * nOA1;
nReps = 100;
nOA = nOA * nReps;
psVector vecOAInps, vecOAOuts;
psIVector vecOAStas;
vecOAInps.setLength(nInputs*nOA);
vecOAOuts.setLength(nOA);
vecOAStas.setLength(nOA);
samPtr = (Sampling *) SamplingCreateFromID(PSUADE_SAMP_OA);
samPtr->setPrintLevel(outputLevel);
samPtr->setInputBounds(nInputs, iLowerB, iUpperB);
samPtr->setInputParams(nInputs, NULL, NULL, NULL);
samPtr->setOutputParams(iOne);
samPtr->setSamplingParams(nOA, nReps, iZero);
samPtr->initialize(0);
samPtr->getSamples(nOA, nInputs, iOne, vecOAInps.getDVector(),
vecOAOuts.getDVector(), vecOAStas.getIVector());
delete samPtr;
//**/ convert the sample to different PDF, if needed
PDFManager *pdfman;
psVector vecIn, vecOut, vecLower, vecUpper;
psuadeIO->getParameter("ana_use_input_pdfs", pPtr);
int usePDFs = pPtr.intData_;
if (usePDFs == 1)
{
pdfman = new PDFManager();
psuadeIO->updateAnalysisSection(-1,-1,-1,0,-1, -1);
psuadeIO->updateMethodSection(PSUADE_SAMP_MC, -1, -1, -1, -1);
pdfman->initialize(psuadeIO);
vecIn = vecOAInps;
vecOut.setLength(nOA*nInputs);
vecUpper.load(nInputs, iUpperB);
vecLower.load(nInputs, iLowerB);
pdfman->invCDF(nOA, vecIn, vecOut, vecLower, vecUpper);
for (ii = 0; ii < nOA*nInputs; ii++) vecOAInps[ii] = vecOut[ii];
delete pdfman;
}
//**/ acquire and prepare for response surface generation
FuncApprox *faPtr;
printEquals(PL_INFO, 0);
printf("Phase 2 of 2: create response surfaces and run input-pair effect\n");
psVector vecYT;
if (nOutputs > 1)
{
vecYT.setLength(nSamples);
for (ss = 0; ss < nSamples; ss++)
vecYT[ss] = sampleOutputs[ss*nOutputs+outputID];
}
else vecYT.load(nSamples,sampleOutputs);
//**/ generate ensemble statistics
int ind, nSamples2, ii1, ii2, jj1, jj2, kk2, bin1, bin2;
double width1, width2, iemean, ievar, totVar=0;
psIVector vecIebInds, vecIeCount;
psVector vecTmpInps, vecTmpOuts, vecIeMeans, vecIeVars, vecIeStore;
vecIebInds.setLength(nSamples);
vecIeCount.setLength(nOA1*nOA1);
vecTmpInps.setLength(nSamples*nInputs);
vecTmpOuts.setLength(nSamples);
vecIeMeans.setLength(nOA1*nOA1);
vecIeVars.setLength(nOA1*nOA1);
vecIeStore.setLength((numBS+2)*nInputs*nInputs);
for (kk = 0; kk < numBS; kk++)
{
printf("rsieb: ITERATION %d (of %d)\n", kk+1, numBS);
//**/ random draw
if (numBS > 1)
{
for (ss = 0; ss < nSamples; ss++) vecIebInds[ss] = 0;
ss = nSamples2 = 0;
while (ss < nSamples)
{
ind = PSUADE_rand() % nSamples;
if (vecIebInds[ind] == 0)
{
for (ii = 0; ii < nInputs; ii++)
vecTmpInps[nSamples2*nInputs+ii] = sampleInputs[ind*nInputs+ii];
vecTmpOuts[nSamples2] = vecYT[ind];
vecIebInds[ind] = 1;
nSamples2++;
}
ss++;
}
}
else
{
nSamples2 = nSamples;
for (ss = 0; ss < nSamples; ss++)
{
for (ii = 0; ii < nInputs; ii++)
vecTmpInps[ss*nInputs+ii] = sampleInputs[ss*nInputs+ii];
vecTmpOuts[ss] = vecYT[ss];
}
}
//**/ create response surface on bootstrap
faPtr = genFA(faType, nInputs, -1, nSamples2);
faPtr->setNPtsPerDim(32);
faPtr->setBounds(iLowerB, iUpperB);
faPtr->setOutputLevel(0);
faPtr->initialize(vecTmpInps.getDVector(),vecTmpOuts.getDVector());
faPtr->evaluatePoint(nOA,vecOAInps.getDVector(),
vecOAOuts.getDVector());
double rsieMean = 0;
for (ii1 = 0; ii1 < nOA; ii1++) rsieMean += vecOAOuts[ii1];
rsieMean /= (double) nOA;
ddata = 0;
for (ii1 = 0; ii1 < nOA; ii1++)
ddata += pow(vecOAOuts[ii1] - rsieMean, 2.0);
ddata /= (nOA -1);
totVar += ddata;
//**/ perform interaction effect analysis
for (ii1 = 0; ii1 < nInputs; ii1++)
{
vecIeStore[kk*nInputs*nInputs+ii1*nInputs+ii1] = 0.0;
width1 = (iUpperB[ii1] - iLowerB[ii1]) / (nOA1 - 1);
for (ii2 = ii1+1; ii2 < nInputs; ii2++)
{
width2 = (iUpperB[ii2] - iLowerB[ii2]) / (nOA1 - 1);
for (kk2 = 0; kk2 < nOA1*nOA1; kk2++)
{
vecIeCount[kk2] = 0;
vecIeMeans[kk2] = 0.0;
vecIeVars[kk2] = 0.0;
}
for (kk2 = 0; kk2 < nOA; kk2++)
{
bin1 = (int) ((vecOAInps[kk2*nInputs+ii1]-
iLowerB[ii1]+1.0e-12)/width1);
bin2 = (int) ((vecOAInps[kk2*nInputs+ii2]-
iLowerB[ii2]+1.0e-12)/width2);
vecIeMeans[bin1*nOA1+bin2] += vecOAOuts[kk2];
vecIeCount[bin1*nOA1+bin2]++;
}
for (kk2 = 0; kk2 < nOA1*nOA1; kk2++)
if (vecIeCount[kk2] > 0) vecIeMeans[kk2] /= vecIeCount[kk2];
for (kk2 = 0; kk2 < nOA; kk2++)
{
bin1 = (int) ((vecOAInps[kk2*nInputs+ii1]-
iLowerB[ii1]+1.0e-12)/width1);
bin2 = (int) ((vecOAInps[kk2*nInputs+ii2]-
iLowerB[ii2]+1.0e-12)/width2);
vecIeVars[bin1*nOA1+bin2] +=
pow(vecOAOuts[kk2]-vecIeMeans[bin1*nOA1+bin2],2.0);
}
for (kk2 = 0; kk2 < nOA1*nOA1; kk2++)
if (vecIeCount[kk2] > 0) vecIeVars[kk2] /= vecIeCount[kk2];
iemean = 0.0;
for (kk2 = 0; kk2 < nOA1*nOA1; kk2++) iemean += vecIeMeans[kk2];
iemean /= (double) (nOA1 * nOA1);
ievar = 0.0;
for (kk2 = 0; kk2 < nOA1*nOA1; kk2++)
ievar += pow(vecIeMeans[kk2]-iemean,2.0);
ievar /= (double) (nOA1 * nOA1);
iemean = 0.0;
for (kk2 = 0; kk2 < nOA1*nOA1; kk2++) iemean += vecIeVars[kk2];
iemean /= (double) (nOA1 * nOA1);
ievar -= iemean / nReps;
if (ievar < 0) ievar = 0;
vecIeStore[kk*nInputs*nInputs+ii1*nInputs+ii2] = ievar;
vecIeStore[kk*nInputs*nInputs+ii2*nInputs+ii1] = ievar;
}
}
delete faPtr;
}
//**/ compute aggregate statistics
double mean, stdev;
totVar /= (double) numBS;
printAsterisks(PL_INFO, 0);
printf("rsieb analysis (normalized by total variance = %e)\n",totVar);
printEquals(PL_INFO, 0);
for (ii = 0; ii < nInputs; ii++)
{
for (jj = ii+1; jj < nInputs; jj++)
{
mean = 0.0;
for (kk = 0; kk < numBS; kk++)
mean += vecIeStore[kk*nInputs*nInputs+ii*nInputs+jj];
mean /= numBS;
vecIeStore[numBS*nInputs*nInputs+ii*nInputs+jj] = mean;
vecIeStore[numBS*nInputs*nInputs+jj*nInputs+ii] = 0.0;
stdev = 0.0;
if (numBS > 1)
{
for (kk = 0; kk < numBS; kk++)
stdev += pow(vecIeStore[kk*nInputs*nInputs+ii*nInputs+jj]-mean,2.0);
stdev = sqrt(stdev/(numBS-1));
}
vecIeStore[(numBS+1)*nInputs*nInputs+ii*nInputs+jj] = stdev;
vecIeStore[(numBS+1)*nInputs*nInputs+jj*nInputs+ii] = 0.0;
//printf("Input %6d %d = %10.2e (stdev = %10.2e)\n",ii+1,
// jj+1,mean,stdev);
printf("Input %6d %d = %10.3e (stdev = %10.3e)\n",ii+1,
jj+1,mean/totVar,stdev/totVar);
}
}
printAsterisks(PL_INFO, 0);
//**/ generate graphics
if (plotScilab())
{
fp = fopen("scilabrsieb.sci", "w");
if (fp == NULL) printf("ERROR : cannot open file scilabrsieb.sci\n");
else
{
fprintf(fp,"// This file contains 2nd order sensitivity indices\n");
fprintf(fp,"// set sortFlag = 1 and set nn to be the number\n");
fprintf(fp,"// of inputs to display.\n");
}
}
else
{
fp = fopen("matlabrsieb.m", "w");
if (fp == NULL) printf("ERROR : cannot open file matlabrsieb.sci\n");
else
{
fprintf(fp, "%% This file contains 2nd order sensitivity indices\n");
fprintf(fp, "%% set sortFlag = 1 and set nn to be the number\n");
fprintf(fp, "%% of inputs to display.\n");
}
}
if (fp != NULL)
{
fprintf(fp, "sortFlag = 0;\n");
fprintf(fp, "nn = %d;\n", nInputs);
fprintf(fp, "Means = [\n");
for (ii = 0; ii < nInputs*nInputs; ii++)
fprintf(fp,"%24.16e\n", vecIeStore[numBS*nInputs*nInputs+ii]);
fprintf(fp, "];\n");
fprintf(fp, "Stds = [\n");
for (ii = 0; ii < nInputs*nInputs; ii++)
fprintf(fp,"%24.16e\n", vecIeStore[(numBS+1)*nInputs*nInputs+ii]);
fprintf(fp, "];\n");
if (inputNames == NULL)
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1);
if (plotScilab()) fprintf(fp,"'X%d'];\n",nInputs);
else fprintf(fp,"'X%d'};\n",nInputs);
}
else
{
if (plotScilab()) fprintf(fp, " Str = [");
else fprintf(fp, " Str = {");
for (ii = 0; ii < nInputs-1; ii++)
{
if (inputNames[ii] != NULL)
fprintf(fp,"'%s',",inputNames[ii]);
else fprintf(fp,"'X%d',",ii+1);
}
if (plotScilab())
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'];\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'];\n",nInputs);
}
else
{
if (inputNames[nInputs-1] != NULL)
fprintf(fp,"'%s'};\n",inputNames[nInputs-1]);
else fprintf(fp,"'X%d'};\n",nInputs);
}
}
fwriteHold(fp, 0);
fprintf(fp, "ymin = min(Means-Stds);\n");
fprintf(fp, "ymax = max(Means+Stds);\n");
fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n");
if (plotScilab())
{
fprintf(fp, "nn = %d;\n",nInputs);
fprintf(fp, "Means = matrix(Means, nn, nn);\n");
fprintf(fp, "Means = Means';\n");
fprintf(fp, "Stds = matrix(Stds, nn, nn);\n");
fprintf(fp, "Stds = Stds';\n");
fprintf(fp, "drawlater\n");
fprintf(fp, "hist3d(Means);\n");
fprintf(fp, "set(gca(),\"auto_clear\",\"off\")\n");
fprintf(fp, "a=gca();\n");
fprintf(fp, "a.data_bounds=[0, 0, 0; nn, nn+1, ymax];\n");
fprintf(fp, "newtick = a.x_ticks;\n");
fprintf(fp, "newtick(2) = [1:nn]';\n");
fprintf(fp, "newtick(3) = Str';\n");
fprintf(fp, "a.x_ticks = newtick;\n");
fprintf(fp, "a.x_label.font_size = 3;\n");
fprintf(fp, "a.x_label.font_style = 4;\n");
fprintf(fp, "a.y_ticks = newtick;\n");
fprintf(fp, "a.y_label.font_size = 3;\n");
fprintf(fp, "a.y_label.font_style = 4;\n");
fprintf(fp, "a.rotation_angles = [5 -70];\n");
fprintf(fp, "drawnow\n");
}
else
{
fprintf(fp, "nn = %d;\n",nInputs);
fprintf(fp, "Means = reshape(Means, nn, nn);\n");
fprintf(fp, "Means = Means';\n");
fprintf(fp, "Stds = reshape(Stds, nn, nn);\n");
fprintf(fp, "Stds = Stds';\n");
fprintf(fp, "hh = bar3(Means,0.8);\n");
fprintf(fp, "alpha = 0.2;\n");
fprintf(fp, "set(hh,'FaceColor','b','facea',alpha);\n");
fprintf(fp, "Lstds = Means - Stds;\n");
fprintf(fp, "Ustds = Means + Stds;\n");
fprintf(fp, "[X,Y] = meshgrid(1:nn,1:nn);\n");
fwriteHold(fp, 1);
fprintf(fp, "for k = 1:nn\n");
fprintf(fp, " for l = k:nn\n");
fprintf(fp, " mkl = Means(k,l);\n");
fprintf(fp, " ukl = Ustds(k,l);\n");
fprintf(fp, " lkl = Lstds(k,l);\n");
fprintf(fp, " if (mkl > .02 & (ukl-lkl)/mkl > .02)\n");
fprintf(fp, " xkl = [X(k,l), X(k,l)];\n");
fprintf(fp, " ykl = [Y(k,l), Y(k,l)];\n");
fprintf(fp, " zkl = [lkl, ukl];\n");
fprintf(fp, " plot3(xkl,ykl,zkl,'-mo',...\n");
fprintf(fp, " 'LineWidth',5,'MarkerEdgeColor','k',...\n");
fprintf(fp, " 'MarkerFaceColor','k','MarkerSize',10);\n");
fprintf(fp, " end\n");
fprintf(fp, " end\n");
fprintf(fp, "end\n");
fwriteHold(fp, 0);
fprintf(fp, "axis([0.5 nn+0.5 0.5 nn+0.5 0 ymax])\n");
fprintf(fp, "set(gca,'XTickLabel',Str);\n");
fprintf(fp, "set(gca,'YTickLabel',Str);\n");
fprintf(fp, "set(gca, 'fontsize', 12)\n");
fprintf(fp, "set(gca, 'fontweight', 'bold')\n");
fprintf(fp, "set(gca, 'linewidth', 2)\n");
}
fwritePlotAxes(fp);
fwritePlotTitle(fp,"1st+2nd Order Sensitivity Indices (with bootstrap)");
fwritePlotZLabel(fp, "2nd Order Sensitivity Indices (Normalized)");
fwritePlotXLabel(fp, "Inputs");
fwritePlotYLabel(fp, "Inputs");
fclose(fp);
if (plotScilab())
printf("rsieb plot file = scilabrsieb.sci\n");
else printf("rsieb plot file = matlabrsieb.m\n");
}
faPtr = NULL;
}
return 0;
}
|
1812c3d2a977a174cf85cbafb9c38f0ff16d6f10
|
0c22d527c18df1f4edb90523f01e4a56cdf58606
|
/NaoTH2011-light/NaoTHSoccer/Source/Core/Motion/Engine/MotionEngine.cpp
|
155cfc4f06fba4249df7be0cf9e4c645a63fd350
|
[] |
no_license
|
IntelligentRoboticsLab/DNT2013
|
3d9fdb1677858fe73006132cc47dda54b47ef165
|
ddc47ce982fe9f9cfaf924902208df1d5e53a802
|
refs/heads/master
| 2020-04-09T06:04:30.577673
| 2013-12-11T13:39:12
| 2013-12-11T13:39:12
| 9,521,743
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,961
|
cpp
|
MotionEngine.cpp
|
#include "MotionEngine.h"
// motion factories
#include "InitialMotion/InitialMotionFactory.h"
#include "InverseKinematicsMotion/InverseKinematicsMotionFactory.h"
#include "ParallelKinematicMotionEngine/ParallelKinematicMotionFactory.h"
#include "KeyFrameMotion/KeyFrameMotionEngine.h"
MotionEngine::MotionEngine()
{
theEmptyMotion = registerModule<EmptyMotion>("EmptyMotion");
theHeadMotionEngine = registerModule<HeadMotionEngine>("HeadMotionEngine", true);
theMotionFactories.push_back(registerModule<InitialMotionFactory>("InitialMotionFactory", true)->getModuleT());
theMotionFactories.push_back(registerModule<InverseKinematicsMotionFactory>("InverseKinematicsMotionFactory", true)->getModuleT());
theMotionFactories.push_back(registerModule<KeyFrameMotionFactory>("KeyFrameMotionFactory", true)->getModuleT());
theMotionFactories.push_back(registerModule<ParallelKinematicMotionFactory>("ParallelKinematicMotionFactory", true)->getModuleT());
//
currentlyExecutedMotion = createEmptyMotion();
// init internal state
//selectMotion();// create init motion
state = initial;
}
MotionEngine::~MotionEngine()
{
}
void MotionEngine::execute()
{
// ensure initialization
switch (state)
{
case initial: // wait for the init motion to start
{
getHeadMotionRequest().id = HeadMotionRequest::numOfHeadMotion;
getMotionRequest().time = getMotionStatus().time;
getMotionRequest().id = motion::init;
if ( getMotionStatus().currentMotion == motion::init
&& getMotionLock().id == motion::init
&& !getMotionLock().isStopped())
{
state = running;
}
break;
}
case running:
{
break;
}
case exiting:
{
getHeadMotionRequest().id = HeadMotionRequest::numOfHeadMotion;
getMotionRequest().time = getMotionStatus().time;
getMotionRequest().id = motion::init;
break;
}
}//end switch
// IMPORTANT: execute head motion firstly
// stabilization of the walk depends on the head position
// cf. InverseKinematicsMotionEngine::controlCenterOfMass(...)
theHeadMotionEngine->execute();
// motion engine execute
selectMotion();
ASSERT(NULL!=currentlyExecutedMotion);
currentlyExecutedMotion->execute();
getMotionStatus().currentMotionState = getMotionLock().state;
}//end execute
void MotionEngine::selectMotion()
{
ASSERT(currentlyExecutedMotion != NULL);
// test if the current MotionStatus allready arrived in cognition
if ( getMotionStatus().time != getMotionRequest().time )
return;
if (getMotionStatus().currentMotion == getMotionRequest().id
&& getMotionLock().isStopped())
{
changeMotion(createEmptyMotion());
}
if (getMotionStatus().currentMotion != getMotionRequest().id
&&
(getMotionLock().isStopped() || getMotionRequest().forced))
{
// unlock if forced
if(getMotionRequest().forced) {
getMotionLock().forceUnlock();
}
Module* newMotion = NULL;
for ( MotionFactorieRegistry::iterator iter=theMotionFactories.begin();
NULL==newMotion && iter!=theMotionFactories.end(); ++iter)
{
newMotion = (*iter)->createMotion(getMotionRequest());
}
if (NULL != newMotion)
{
// assure the right motion acquired the lock
ASSERT(getMotionLock().id == getMotionRequest().id);
changeMotion(newMotion);
} else
{
changeMotion(createEmptyMotion());
std::cerr << "Warning: Request " << motion::getName(getMotionRequest().id)
<< " cannot be executed!" << std::endl;
}
}
}//end selectMotion
void MotionEngine::changeMotion(Module* m)
{
currentlyExecutedMotion = m;
getMotionStatus().lastMotion = getMotionStatus().currentMotion;
getMotionStatus().currentMotion = getMotionLock().id;
getMotionStatus().time = getFrameInfo().getTime();
}//end changeMotion
|
7a48661122db244f010e95b9639af9b677ff929b
|
95a0bb23a05a96b9ef01f88dcc35c2bdaa7f2f14
|
/1.9.1.12285/SDK/WBP_ModalMenu_functions.cpp
|
087e0811c4f63ca48e612481d68d353d9afb2320
|
[] |
no_license
|
MuhanjalaRE/Midair-Community-Edition-SDKs
|
38ccb53898cf22669d99724e7246eb543ae2d25d
|
8f459da568912b3d737d6494db003537af45bf85
|
refs/heads/main
| 2023-04-06T03:49:42.732247
| 2021-04-14T11:35:28
| 2021-04-14T11:35:28
| 334,685,504
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,781
|
cpp
|
WBP_ModalMenu_functions.cpp
|
// Name: mace, Version: 1.9.1.12285
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function WBP_ModalMenu.WBP_ModalMenu_C.HandleDirectNamedHotkey
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FString Hotkey (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, HasGetValueTypeHash)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
bool UWBP_ModalMenu_C::HandleDirectNamedHotkey(const struct FString& Hotkey)
{
static UFunction* fn = nullptr;
if(!fn){
fn = UObject::FindObject<UFunction>("Function WBP_ModalMenu.WBP_ModalMenu_C.HandleDirectNamedHotkey");
}
UWBP_ModalMenu_C_HandleDirectNamedHotkey_Params params;
params.Hotkey = Hotkey;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function WBP_ModalMenu.WBP_ModalMenu_C.HandleNamedHotkeyWithInt
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FString Hotkey (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, HasGetValueTypeHash)
// int Int (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
bool UWBP_ModalMenu_C::HandleNamedHotkeyWithInt(const struct FString& Hotkey, int Int)
{
static UFunction* fn = nullptr;
if(!fn){
fn = UObject::FindObject<UFunction>("Function WBP_ModalMenu.WBP_ModalMenu_C.HandleNamedHotkeyWithInt");
}
UWBP_ModalMenu_C_HandleNamedHotkeyWithInt_Params params;
params.Hotkey = Hotkey;
params.Int = Int;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function WBP_ModalMenu.WBP_ModalMenu_C.Remove
// (Public, BlueprintCallable, BlueprintEvent)
void UWBP_ModalMenu_C::Remove()
{
static UFunction* fn = nullptr;
if(!fn){
fn = UObject::FindObject<UFunction>("Function WBP_ModalMenu.WBP_ModalMenu_C.Remove");
}
UWBP_ModalMenu_C_Remove_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
80640903fdcbc0f45be32cad666a3a253805b51a
|
67cf5d1d7ea62ca9e7b35c42c042efcf1c77ff36
|
/mosixFastProjections/Stitcher.cpp
|
545d7d571453cad40ceaa1ccd85c5532a3d813bf
|
[] |
no_license
|
bpass/cegis
|
d3c84d2d29a084105b4c207391ddc6ace0cdf398
|
6c849e41974b8ff844f78e260de26d644c956afb
|
refs/heads/master
| 2020-04-03T18:57:58.102939
| 2013-04-24T22:07:54
| 2013-04-24T22:07:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,018
|
cpp
|
Stitcher.cpp
|
#ifndef STITCHER_CPP
#define STITCHER_CPP
#include "Stitcher.h"
#include <iostream>
//*************************************************************
Stitcher::Stitcher( USGSImageLib::ImageOFile * inout, unsigned long lines )
{
//copy the output file
out = inout;
m_currentRow = 0;
done = false;
// assign the total number of lines to the job
m_totalLines = lines;
//std::cout << "STITCHER: m_totalLines is " << m_totalLines << std::endl;
// MUST BE LAST: start the thread
thread_start_func threadthing(this);
boost::thread threadhead(threadthing);
}
//*************************************************************
Stitcher::~Stitcher()
{
boost::mutex::scoped_lock donemutexlock(donemutex);
if ( !done )
waitcond.wait(donemutexlock);
donemutexlock.unlock();
}
//***********************************************************
void Stitcher::add(StitcherNode * temp) throw()
{
// notify the run() execution, there's more in the queue now
//std::cout << "ADD: signal end wait" << std::endl;
//put the work in the queue
boost::mutex::scoped_lock workmutexlock(workmutex);
//std::cout << "ADD: acquired lock, adding " << std::endl;
workqueue.push(temp);
workmutexlock.unlock();
//std::cout << "ADD: unlock, adding " << std::endl;
workcond.notify_one();
}
//**********************************************************
void Stitcher::wait() throw()
{
//try to aquire the done mutex
boost::mutex::scoped_lock donemutexlock(donemutex);
while(!done)
waitcond.wait(donemutexlock);
donemutexlock.unlock();
}
//**************************************************************
void Stitcher::run() throw()
{
StitcherNode * temp(0);
long row(0);
void * data(0);
bool ldone(false);
//check the output image
if (!out)
{
//std::cout << "STITCHER: out is NULL !" << std::endl;
waitcond.notify_one();
boost::mutex::scoped_lock donemutexlock(donemutex);
done = true;
donemutexlock.unlock();
return; //exit
}
//std::cout << "STITCHER: m_totalLines is " << m_totalLines << std::endl;
while(!ldone)
{
//check the queue
boost::mutex::scoped_lock workmutexlock(workmutex);
if ( m_currentRow >= m_totalLines )
{
//std::cout << "STITCHER: reached last line. " << std::endl;
//std::cout << "STITCHER: m_currentRow is " << m_currentRow <<std::endl;
//std::cout << "STITCHER: m_totalLines is " << m_totalLines <<std::endl;
workmutexlock.unlock();
ldone = true;
} else if (workqueue.size() == 0 )
{
// wait for work to be put in the queue
//std::cout << "STITCHER: waiting on empty" << std::endl;
workcond.wait(workmutexlock);
workmutexlock.unlock();
//std::cout << "STITCHER: signaled to continue" << std::endl;
}
else
{
temp = workqueue.top();
if ( static_cast<unsigned int>(temp->getrow()) == m_currentRow )
{
m_currentRow++;
workqueue.pop();
workmutexlock.unlock();
row = temp->getrow();
data = temp->getdata();
//std::cout << "STITCHER: waiting for lock on 'out'. " << std::endl;
boost::mutex::scoped_lock scanlineLock(scanlineMutex);
//std::cout << "STITCHER: writing row " << m_currentRow << std::endl;
try {
out->putRawScanline(row, data);
} catch ( USGSImageLib::ImageException & e )
{
std::string s;
e.getString(s);
//std::cout << "STITCHER: exception caught: " << s << std::endl;
}
scanlineLock.unlock();
delete temp;
} else
{
workmutexlock.unlock();
}
}
}
//termination
waitcond.notify_one();
boost::mutex::scoped_lock donemutexlock(donemutex);
done = true;
donemutexlock.unlock();
}
#endif
|
58b33f20588d1673e62f85e60d67b533e6ff4756
|
9379625eeadd777a4b4961982cf0cb228ef192d1
|
/src/financial.h
|
e9ea48d2b73025fd04e2f745689f675d72235ed3
|
[] |
no_license
|
ettoremaiorana/resampling-and-simulation-methods-for-trading
|
06652c7c615654b8971aa40a08a962f44d19d2f9
|
f68b6b60a7f9a7a5cbc5a9c62e6aee2098aedbdc
|
refs/heads/master
| 2020-07-26T13:38:52.282788
| 2019-10-16T07:51:20
| 2019-10-16T07:51:20
| 208,662,607
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 425
|
h
|
financial.h
|
//
// Created by ivan on 13/09/2019.
//
#include <vector>
double annual_return(const std::vector<double>& daily_returns);
double annual_volatility(const std::vector<double>& daily_returns);
double sharpe_ratio(const std::vector<double>& daily_returns, double risk_free);
double max_drawdown(const std::vector<double>& daily_returns);
double value_at_risk(const std::vector<double>& daily_returns, double cutoff_percentage);
|
3bf8145d775e29ce19705b8441b7dc9300b0f6ce
|
8dc536fde88501d1c208414ee4fd854e25557050
|
/url_code.h
|
2cbc12a948330ff5b01125ba11259434113bec8c
|
[] |
no_license
|
qhadyn/VideoQualityDetection
|
f1eadf9d716524723fdd686e5443a89415ab25da
|
cdbc86cfae5ff4a478f57d12e79418b450663f1f
|
refs/heads/master
| 2023-08-03T06:13:58.305690
| 2021-09-25T08:59:02
| 2021-09-25T08:59:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,527
|
h
|
url_code.h
|
/******************************************************************************
*
* Copyright (C), 2001-2005, Huawei Tech. Co., Ltd.
*
*******************************************************************************
* File Name : url_code.h
* Version : Initial Draft
* Author : sst
* Created : 2021/9/6
* Last Modified :
* Description : url_code.cpp header file
* Function List :
*
*
* History:
*
* 1. Date : 2021/9/6
* Author : sst
* Modification : Created file
*
******************************************************************************/
#ifndef __URL_CODE_H__
#define __URL_CODE_H__
/*==============================================*
* include header files *
*----------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
/*==============================================*
* constants or macros define *
*----------------------------------------------*/
/*==============================================*
* project-wide global variables *
*----------------------------------------------*/
/*==============================================*
* routines' or functions' implementations *
*----------------------------------------------*/
extern string UrlDecode(const string& str, string& dst);
extern string UrlEncode(const string& str, string& dst);
#endif /* __URL_CODE_H__ */
|
ec997e5c1a553b9167d523f92b5ce6068e444023
|
24b6dc34a419586a14d384c216186f6175011db6
|
/game_platform_win32.cpp
|
60744b854af0661c206a49492a71a7b2765b5b76
|
[] |
no_license
|
xstraski/quantic_veryold
|
c6e440b108b9cd963001b4e24c2f606d87f67af4
|
ff91bcabda48fd0d23707dc45f2fb4f3adeaf952
|
refs/heads/master
| 2020-06-10T19:58:55.288261
| 2019-07-25T13:00:39
| 2019-07-25T13:00:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 48,509
|
cpp
|
game_platform_win32.cpp
|
#include "game.h"
#include "game_platform_win32.h"
// Win32-specific CRT extensions.
#include <crtdbg.h>
// NOTE(ivan): Win32 visual styles enable.
#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
// NOTE(ivan): Win32 extra includes.
#include <objbase.h>
#include <commctrl.h>
#include <versionhelpers.h>
#include <mmsystem.h>
#include <shlwapi.h>
// NOTE(ivan): Win32 XInput includes.
#include <xinput.h>
// NOTE(ivan): Win32 XInput prototypes.
#define X_INPUT_GET_STATE(Name) DWORD WINAPI Name(DWORD UserIndex, XINPUT_STATE *State)
typedef X_INPUT_GET_STATE(x_input_get_state);
#define X_INPUT_SET_STATE(Name) DWORD WINAPI Name(DWORD UserIndex, XINPUT_VIBRATION *Vibration)
typedef X_INPUT_SET_STATE(x_input_set_state);
// NOTE(ivan): Win32 XInput module structure.
struct win32_xinput_module {
b32 IsValid; // NOTE(ivan): False if something went wrong and the XInput module is not loaded.
HMODULE XInputLibrary;
x_input_get_state *GetState;
x_input_set_state *SetState;
};
// NOTE(ivan): Win32-specific game module structure.
struct win32_game_module {
b32 IsValid; // NOTE(ivan): False if something went wrong and the game module is not loaded.
HMODULE GameLibrary;
game_trigger *GameTrigger;
};
// NOTE(ivan): Win32-specific game renderer module structure.
struct win32_renderer_module {
b32 IsValid; // NOTE(ivan): False if something went wrong and the game module is not loaded.
HMODULE RendererLibrary;
renderer_api *API;
};
// NOTE(ivan): Win32 files maximum count.
#define MAX_WIN32_FILES_COUNT 256
// NOTE(ivan): Win32 file.
struct win32_file {
b32 IsOpened; // NOTE(ivan): Whether the handle is already opened or not.
HANDLE OSHandle;
};
// NOTE(ivan): Win32 globals.
static struct {
HINSTANCE Instance;
s32 ArgC;
char **ArgV;
u64 PerformanceFrequency;
UINT QueryCancelAutoplay; // NOTE(ivan): Special event for disabling disc autoplay feaature.
b32 IsDebugCursor;
b32 IsDebuggerActive; // NOTE(ivan): Indicates whether the program is running under the debugger.
b32 IsWindowActive; // NOTE(ivan): Indicates whether the main window is active or not (focused/not focused).
// NOTE(ivan): Standard text stream.
HANDLE Stdout;
// NOTE(ivan): Game input, needs to be global to be accessed by Win32WindowProc()'s raw input routines.
game_input *GameInput;
// NOTE(ivan): Reserved file handles.
win32_file Files[MAX_WIN32_FILES_COUNT];
ticket_mutex FilesMutex;
} Win32State;
// NOTE(ivan): Win32-specific system structure for setting thread name by Win32SetThreadName.
struct win32_thread_name {
DWORD Type; // NOTE(ivan): Must be 0x1000.
LPCSTR Name;
DWORD ThreadId;
DWORD Flags;
};
static void
Win32SetThreadName(DWORD ThreadId, LPCSTR Name) {
Assert(Name);
win32_thread_name ThreadName = {};
ThreadName.Type = 0x1000;
ThreadName.Name = Name;
ThreadName.ThreadId = ThreadId;
#pragma warning(push)
#pragma warning(disable: 6320 6322)
__try {
RaiseException(0x406d1388, 0, sizeof(ThreadName) / sizeof(ULONG_PTR), (ULONG_PTR *)&ThreadName);
} __except(EXCEPTION_EXECUTE_HANDLER) {}
#pragma warning(pop)
}
inline u64
Win32GetClock(void) {
LARGE_INTEGER Result;
Verify(QueryPerformanceCounter(&Result));
return Result.QuadPart;
}
inline f32
Win32GetSecondsElapsed(u64 Start, u64 End) {
return (f32)((f64)(End - Start) / (f64)Win32State.PerformanceFrequency);
}
static PLATFORM_CHECK_PARAM(Win32CheckParam) {
Assert(Param);
for (s32 Index = 0; Index < Win32State.ArgC; Index++) {
if (strcmp(Win32State.ArgV[Index], Param) == 0)
return Index;
}
return NOTFOUND;
}
static PLATFORM_CHECK_PARAM_VALUE(Win32CheckParamValue) {
Assert(Param);
s32 Index = Win32CheckParam(Param);
if (Index == NOTFOUND)
return 0;
if ((Index + 1) > Win32State.ArgC)
return 0;
return Win32State.ArgV[Index + 1];
}
static PLATFORM_OUTF(Win32Outf) {
Assert(Format);
char Buffer[2048] = {};
CollectArgsN(Buffer, ArraySize(Buffer) - 1, Format);
char FinalString[2048] = {};
u32 FinalStringLength = snprintf(FinalString, ArraySize(FinalString) - 1, "%s\r\n", Buffer);
// NOTE(ivan): Output to debugger's output window if any.
if (Win32State.IsDebuggerActive) {
OutputDebugStringA("## ");
OutputDebugStringA(FinalString);
OutputDebugStringA("\r\n");
}
// NOTE(ivan): Output to system console if any.
if (Win32State.Stdout) {
DWORD Unused;
WriteFile(Win32State.Stdout, FinalString, FinalStringLength, &Unused, 0);
}
}
static PLATFORM_CRASHF(Win32Crashf) {
Assert(Format);
static b32 AlreadyCrashed = false;
if (!AlreadyCrashed) {
AlreadyCrashed = true;
char Buffer[2048] = {};
CollectArgsN(Buffer, ArraySize(Buffer) - 1, Format);
Win32Outf("*** CRASH *** %s", Buffer);
MessageBoxA(0, Buffer, GAMENAME, MB_OK | MB_ICONERROR | MB_TOPMOST);
}
ExitProcess(0);
}
static s32
Win32GetFreeFileIndex(void) {
s32 Result = NOTFOUND;
EnterTicketMutex(&Win32State.FilesMutex);
s32 Index;
for (Index = 0; Index < (s32)ArraySize(Win32State.Files); Index++) {
if (!Win32State.Files[Index].IsOpened) {
Win32State.Files[Index].IsOpened = true;
Result = Index;
break;
}
}
LeaveTicketMutex(&Win32State.FilesMutex);
if (Index == NOTFOUND)
Win32Crashf("Out of Win32-file-handles!");
return Index;
}
inline win32_file *
Win32GetFile(s32 FileIndex) {
Assert(FileIndex < (s32)ArraySize(Win32State.Files));
EnterTicketMutex(&Win32State.FilesMutex);
win32_file *Result = &Win32State.Files[FileIndex];
LeaveTicketMutex(&Win32State.FilesMutex);
return Result;
}
inline void
Win32FreeFileIndex(s32 FileIndex) {
EnterTicketMutex(&Win32State.FilesMutex);
win32_file *File = &Win32State.Files[FileIndex];
File->IsOpened = false;
LeaveTicketMutex(&Win32State.FilesMutex);
}
static PLATFORM_FOPEN(Win32FOpen) {
Assert(FileName);
Assert(AccessType);
file_handle Result = NOTFOUND;
// NOTE(ivan): Get free file handle.
s32 FileIndex = Win32GetFreeFileIndex();
win32_file *File = Win32GetFile(FileIndex);
// NOTE(ivan): Prepare open flags.
DWORD FileAccess = 0;
DWORD FileShareMode = 0;
DWORD FileCreation = 0;
DWORD FileAttribs = 0;
if (AccessType | FileAccessType_OpenForReading) {
FileAccess |= GENERIC_READ;
FileShareMode |= FILE_SHARE_READ;
FileCreation |= OPEN_EXISTING;
} else if (AccessType | FileAccessType_OpenForWriting) {
FileAccess |= GENERIC_WRITE;
FileShareMode |= FILE_SHARE_READ;
FileCreation |= CREATE_ALWAYS;
FileAttribs |= FILE_ATTRIBUTE_NORMAL;
}
// NOTE(ivan): Open/create file.
File->OSHandle = CreateFileA(FileName, FileAccess, FileShareMode, 0, FileCreation, FileAttribs, 0);
if (File->OSHandle != INVALID_HANDLE_VALUE)
Result = (file_handle)FileIndex;
return Result;
}
static PLATFORM_FCLOSE(Win32FClose) {
Assert(FileHandle != NOTFOUND);
CloseHandle(Win32GetFile(FileHandle)->OSHandle);
Win32FreeFileIndex(FileHandle);
}
static PLATFORM_FREAD(Win32FRead) {
Assert(FileHandle != NOTFOUND);
Assert(Buffer);
Assert(Size);
u32 Result = 0;
win32_file *File = Win32GetFile(FileHandle);
DWORD BytesRead = 0;
if (ReadFile(File->OSHandle, Buffer, Size, &BytesRead, 0))
Result = BytesRead;
return Result;
}
static PLATFORM_FWRITE(Win32FWrite) {
Assert(FileHandle != NOTFOUND);
Assert(Buffer);
Assert(Size);
u32 Result = 0;
win32_file *File = Win32GetFile(FileHandle);
DWORD BytesWritten = 0;
if (WriteFile(File->OSHandle, Buffer, Size, &BytesWritten, 0))
Result = BytesWritten;
return Result;
}
static PLATFORM_FSEEK(Win32FSeek) {
Assert(FileHandle);
Assert(Size);
Assert(SeekOrigin);
Assert(NewPos);
b32 Result = false;
win32_file *File = Win32GetFile(FileHandle);
LARGE_INTEGER DistanceToMove;
LARGE_INTEGER NewFilePointer;
DWORD MoveMethod;
DistanceToMove.QuadPart = Size;
switch (SeekOrigin) {
default:
case FileSeekOrigin_Begin: MoveMethod = FILE_BEGIN; break;
case FileSeekOrigin_Current: MoveMethod = FILE_CURRENT; break;
case FileSeekOrigin_End: MoveMethod = FILE_END; break;
};
if (SetFilePointerEx(File->OSHandle, DistanceToMove, &NewFilePointer, MoveMethod)) {
Result = true;
#if X32CPU
*NewPos = NewFilePointer.LowPart;
#elif X64CPU
*NewPos = NewFilePointer.QuadPart;
#endif
}
return Result;
}
static PLATFORM_FFLUSH(Win32FFlush) {
Assert(FileHandle);
FlushFileBuffers(Win32GetFile(FileHandle)->OSHandle);
}
static cpu_info
Win32GatherCPUInfo(void) {
cpu_info CPUInfo = {};
int CPUId[4] = {}, ExIds = 0;
const u32 EAX = 0;
const u32 EBX = 1;
const u32 ECX = 2;
const u32 EDX = 3;
// NOTE(ivan): Obtain vendor name.
__cpuid(CPUId, 0);
*((int *)(CPUInfo.VendorName + 0)) = CPUId[EBX];
*((int *)(CPUInfo.VendorName + 4)) = CPUId[EDX];
*((int *)(CPUInfo.VendorName + 8)) = CPUId[ECX];
if (strcmp(CPUInfo.VendorName, "GenuineIntel") == 0)
CPUInfo.IsIntel = true;
else if (strcmp(CPUInfo.VendorName, "AuthenticAMD") == 0)
CPUInfo.IsAMD = true;
// NOTE(ivan): Obtain brand name.
__cpuid(CPUId, 0x80000000);
ExIds = CPUId[EAX];
if (ExIds >= 0x80000004) {
for (int Func = 0x80000002, Pos = 0; Func <= 0x80000004; Func++, Pos += 16) {
__cpuid(CPUId, Func);
memcpy(CPUInfo.BrandName + Pos, CPUId, sizeof(CPUId));
}
} else {
strcpy(CPUInfo.BrandName, "Unknown");
}
// NOTE(ivan): Check features.
__cpuid(CPUId, 1);
CPUInfo.SupportsMMX = (IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE) == TRUE);
CPUInfo.SupportsSSE = (IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE) == TRUE);
CPUInfo.SupportsSSE2 = (IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE) == TRUE);
CPUInfo.SupportsSSE3 = (CPUId[ECX] & (1 << 0)) ? true : false;
CPUInfo.SupportsSSSE3 = (CPUId[ECX] & (1 << 9)) ? true : false;
CPUInfo.SupportsSSE4_1 = (CPUId[ECX] & (1 << 19)) ? true : false;
CPUInfo.SupportsSSE4_2 = (CPUId[ECX] & (1 << 20)) ? true : false;
CPUInfo.SupportsHT = (CPUId[EDX] & (1 << 28)) ? true : false;
// NOTE(ivan): Check extended features.
if (ExIds >= 0x80000001) {
__cpuid(CPUId, 0x80000001);
CPUInfo.SupportsMMXExt = CPUInfo.IsAMD && ((CPUId[EDX] & (1 << 22)) ? true : false);
CPUInfo.Supports3DNow = CPUInfo.IsAMD && ((CPUId[EDX] & (1 << 31)) ? true : false);
CPUInfo.Supports3DNowExt = CPUInfo.IsAMD && ((CPUId[EDX] & (1 << 30)) ? true : false);
CPUInfo.SupportsSSE4A = CPUInfo.IsAMD && ((CPUId[ECX] & (1 << 6)) ? true : false);
}
// NOTE(ivan): Calculate cores/threads/caches count.
DWORD LogicalLength = 0;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION LogicalInfo = 0;
if (!GetLogicalProcessorInformation(0, &LogicalLength) && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
LogicalInfo = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)VirtualAlloc(0, LogicalLength, MEM_COMMIT, PAGE_READWRITE);
if (LogicalInfo)
GetLogicalProcessorInformation(LogicalInfo, &LogicalLength);
}
if (LogicalInfo) {
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION LogicalPtr = LogicalInfo;
u32 ByteOffset = 0;
while ((ByteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)) <= LogicalLength) {
switch (LogicalPtr->Relationship) {
case RelationProcessorCore: {
CPUInfo.NumCores++;
CPUInfo.NumCoreThreads += CountSetBits(LogicalPtr->ProcessorMask);
} break;
case RelationCache: {
if (LogicalPtr->Cache.Level == 1)
CPUInfo.NumL1++;
else if (LogicalPtr->Cache.Level == 2)
CPUInfo.NumL2++;
else if (LogicalPtr->Cache.Level == 3)
CPUInfo.NumL3++;
} break;
case RelationNumaNode: {
CPUInfo.NumNUMA++;
} break;
}
ByteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
LogicalPtr++;
}
if (LogicalInfo)
VirtualFree(LogicalInfo, 0, MEM_RELEASE);
}
// NOTE(ivan): Calculate clock speed.
HANDLE CurrentProcess = GetCurrentProcess();
HANDLE CurrentThread = GetCurrentThread();
DWORD CurrentPriorityClass = GetPriorityClass(CurrentProcess);
int CurrentThreadPriority = GetThreadPriority(CurrentThread);
DWORD_PTR ProcessMask, SystemMask;
GetProcessAffinityMask(CurrentProcess, &ProcessMask, &SystemMask);
SetPriorityClass(CurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(CurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
SetProcessAffinityMask(CurrentProcess, 1);
// NOTE(ivan): CPU serialization: call the processor to ensure that all other prior called functions are completed now.
__cpuid(CPUId, 0);
u64 StartCycle, EndCycle;
u64 StartClock, EndClock;
StartCycle = Win32GetClock();
StartClock = __rdtsc();
Sleep(300); // NOTE(ivan): Sleep time should be as short as possible.
EndCycle = Win32GetClock();
EndClock = __rdtsc();
SetProcessAffinityMask(CurrentProcess, ProcessMask);
SetThreadPriority(CurrentThread, CurrentThreadPriority);
SetPriorityClass(CurrentProcess, CurrentPriorityClass);
f32 SecondsElapsed = Win32GetSecondsElapsed(StartCycle, EndCycle);
u64 ClocksElapsed = EndClock - StartClock;
CPUInfo.ClockSpeed = (f32)(((f64)ClocksElapsed / SecondsElapsed) / (f32)(1000 * 1000 * 1000));
// NOTE(ivan): Complete.
return CPUInfo;
}
static X_INPUT_GET_STATE(Win32XInputGetStateStub) {
UnusedParam(UserIndex);
UnusedParam(State);
return ERROR_DEVICE_NOT_CONNECTED;
}
static X_INPUT_SET_STATE(Win32XInputSetStateStub) {
UnusedParam(UserIndex);
UnusedParam(Vibration);
return ERROR_DEVICE_NOT_CONNECTED;
}
inline win32_xinput_module
Win32LoadXInputModule(void) {
win32_xinput_module Result = {};
Win32Outf("Loading XInput module...");
Win32Outf("...trying xinput1_4.dll");
Result.XInputLibrary = LoadLibraryA("xinput1_4.dll");
if (!Result.XInputLibrary) {
Win32Outf("...trying xinput9_1_0.dll");
Result.XInputLibrary = LoadLibraryA("xinput9_1_0.dll");
}
if (!Result.XInputLibrary) {
Win32Outf("...trying xinput1_3.dll");
Result.XInputLibrary = LoadLibraryA("xinput1_3.dll");
}
if (Result.XInputLibrary) {
Result.GetState = (x_input_get_state *)GetProcAddress(Result.XInputLibrary, "XInputGetState");
Result.SetState = (x_input_set_state *)GetProcAddress(Result.XInputLibrary, "XInputSetState");
// NOTE(ivan): We target to the oldest available XInput library version 1.3
// so the program can run on at least Windows 7 without any additional DX-redistributables installation.
// The functions XInputGetState() and XInputSetState() are guaranteed to be there.
if (Result.GetState && Result.SetState) {
Result.IsValid = true; // NOTE(ivan): Success.
Win32Outf("...success.");
}
} else {
Win32Outf("...fail, file not found!");
}
if (!Result.IsValid) {
Win32Outf("...fail, entries not found, using stubs!");
// NOTE(ivan): In case of load fail, use these dummies that always return ERROR_DEVICE_NOT_CONNECTED,
// so the program will behave like there are no Xbox controllers plugged in the machine at all.
Result.GetState = Win32XInputGetStateStub;
Result.SetState = Win32XInputSetStateStub;
}
return Result;
}
inline void
Win32SetInputButtonState(input_button_state *Button, b32 IsDown) {
Assert(Button);
Button->WasDown = Button->IsDown;
Button->IsDown = IsDown;
Button->IsNew = true;
}
inline void
Win32ProcessXInputDigitalButton(input_button_state *Button, DWORD XInputButtonState, DWORD ButtonBit) {
Assert(Button);
b32 IsDown = ((XInputButtonState & ButtonBit) == ButtonBit);
Win32SetInputButtonState(Button, IsDown);
}
inline f32
Win32ProcessXInputStickValue(SHORT Value, SHORT DeadZoneThreshold) {
f32 Result = 0.0f;
if (Value < -DeadZoneThreshold)
Result = (f32)((Value + DeadZoneThreshold) / (32768.0f - DeadZoneThreshold));
else if (Value > DeadZoneThreshold)
Result = (f32)((Value - DeadZoneThreshold) / (32767.0f - DeadZoneThreshold));
return Result;
}
static b32
Win32MapVKToKeyCode(u32 VKCode, u32 ScanCode, b32 IsE0, b32 IsE1, key_code *OutCode) {
Assert(OutCode);
key_code KeyCode = {}; // NOTE(ivan): Result of Windows VK -> our keycode conversion.
b32 KeyFound = false;
if (VKCode == 255) {
// NOTE(ivan): Discard "fake keys" which are part of en escaped sequence.
return false;
} else if (VKCode == VK_SHIFT) {
// NOTE(ivan): Correct left-hand / right-hand SHIFT.
VKCode = MapVirtualKey(ScanCode, MAPVK_VSC_TO_VK_EX);
} else if (VKCode == VK_NUMLOCK) {
// NOTE(ivan): Correct PAUSE/BREAK and NUMLOCK silliness, and set the extended bit.
ScanCode = (MapVirtualKey(VKCode, MAPVK_VK_TO_VSC) | 0x100);
}
// NOTE(ivan): E0 and E1 are escape sequences used for certain special keys, such as PRINTSCREEN or PAUSE/BREAK.
// See: http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html
if (IsE1) {
// NOTE(ivan): For escaped sequences, turn the virtual key into the correct scan code using MapVirtualKey.
// However, MapVirtualKey is unable to map VK_PAUSE (this is a known bug), hence we map that by hand.
if (VKCode == VK_PAUSE)
ScanCode = 0x45;
else
ScanCode = MapVirtualKey(VKCode, MAPVK_VK_TO_VSC);
}
switch (VKCode) {
// NOTE(ivan): Right-hand CONTROL and ALT have their E0 bit set.
case VK_CONTROL: {
if (IsE0)
KeyCode = KeyCode_RightControl;
else
KeyCode = KeyCode_LeftControl;
KeyFound = true;
} break;
case VK_MENU: {
if (IsE0)
KeyCode = KeyCode_RightAlt;
else
KeyCode = KeyCode_LeftAlt;
KeyFound = true;
} break;
// NOTE(ivan): NUM ENTER has its E0 bit set
case VK_RETURN: {
if (IsE0)
KeyCode = KeyCode_NumEnter;
else
KeyCode = KeyCode_Enter;
KeyFound = true;
} break;
// NOTE(ivan): The standard INSERT, DELETE, HOME, END, PRIOR and NEXT keys will always have their E0 bit set,
// but the corresponding NUM keys will not.
case VK_INSERT: {
if (!IsE0)
KeyCode = KeyCode_NumInsert;
else
KeyCode = KeyCode_Insert;
KeyFound = true;
} break;
case VK_DELETE: {
if (!IsE0)
KeyCode = KeyCode_NumDelete;
else
KeyCode = KeyCode_Delete;
KeyFound = true;
} break;
case VK_HOME: {
if (!IsE0)
KeyCode = KeyCode_NumHome;
else
KeyCode = KeyCode_Home;
KeyFound = true;
} break;
case VK_END: {
if (!IsE0)
KeyCode = KeyCode_NumEnd;
else
KeyCode = KeyCode_End;
KeyFound = true;
} break;
case VK_PRIOR: {
if (!IsE0)
KeyCode = KeyCode_NumPageUp;
else
KeyCode = KeyCode_PageUp;
KeyFound = true;
} break;
case VK_NEXT: {
if (!IsE0)
KeyCode = KeyCode_NumPageDown;
else
KeyCode = KeyCode_PageDown;
KeyFound = true;
} break;
// NOTE(ivan): The standard arrow keys will awlays have their E0 bit set,
// but the corresponding NUM keys will not.
case VK_UP: {
if (!IsE0)
KeyCode = KeyCode_NumUp;
else
KeyCode = KeyCode_Up;
KeyFound = true;
} break;
case VK_DOWN: {
if (!IsE0)
KeyCode = KeyCode_NumDown;
else
KeyCode = KeyCode_Down;
KeyFound = true;
} break;
case VK_LEFT: {
if (!IsE0)
KeyCode = KeyCode_NumLeft;
else
KeyCode = KeyCode_Left;
KeyFound = true;
} break;
case VK_RIGHT: {
if (!IsE0)
KeyCode = KeyCode_NumRight;
else
KeyCode = KeyCode_Right;
KeyFound = true;
} break;
// NOTE(ivan): NUM 5 doesn't have its E0 bit set.
case VK_CLEAR: {
if (!IsE0) {
KeyCode = KeyCode_NumClear;
KeyFound = true;
} else {
return false;
}
} break;
}
#define KeyMap(MapVK, MapKeyCode) \
if (VKCode == MapVK) { \
KeyCode = MapKeyCode; \
KeyFound = true; \
}
KeyMap(VK_TAB, KeyCode_Tab);
KeyMap(VK_ESCAPE, KeyCode_Escape);
KeyMap(VK_SPACE, KeyCode_Space);
KeyMap(VK_BACK, KeyCode_BackSpace);
KeyMap(VK_LSHIFT, KeyCode_LeftShift);
KeyMap(VK_RSHIFT, KeyCode_RightShift);
KeyMap(VK_LMENU, KeyCode_LeftAlt);
KeyMap(VK_RMENU, KeyCode_RightAlt);
KeyMap(VK_LCONTROL, KeyCode_LeftControl);
KeyMap(VK_RCONTROL, KeyCode_RightControl);
KeyMap(VK_LWIN, KeyCode_LeftSuper);
KeyMap(VK_RWIN, KeyCode_RightSuper);
KeyMap(VK_F1, KeyCode_F1);
KeyMap(VK_F2, KeyCode_F2);
KeyMap(VK_F3, KeyCode_F3);
KeyMap(VK_F4, KeyCode_F4);
KeyMap(VK_F5, KeyCode_F5);
KeyMap(VK_F6, KeyCode_F6);
KeyMap(VK_F7, KeyCode_F7);
KeyMap(VK_F8, KeyCode_F8);
KeyMap(VK_F9, KeyCode_F9);
KeyMap(VK_F10, KeyCode_F10);
KeyMap(VK_F11, KeyCode_F11);
KeyMap(VK_F12, KeyCode_F12);
KeyMap(VK_NUMLOCK, KeyCode_NumLock);
KeyMap(VK_CAPITAL, KeyCode_CapsLock);
KeyMap(VK_SCROLL, KeyCode_ScrollLock);
KeyMap(VK_PRINT, KeyCode_PrintScreen);
KeyMap(VK_PAUSE, KeyCode_Pause);
KeyMap(0x41, KeyCode_A);
KeyMap(0x42, KeyCode_B);
KeyMap(0x43, KeyCode_C);
KeyMap(0x44, KeyCode_D);
KeyMap(0x45, KeyCode_E);
KeyMap(0x46, KeyCode_F);
KeyMap(0x47, KeyCode_G);
KeyMap(0x48, KeyCode_H);
KeyMap(0x49, KeyCode_I);
KeyMap(0x4A, KeyCode_J);
KeyMap(0x4B, KeyCode_K);
KeyMap(0x4C, KeyCode_L);
KeyMap(0x4D, KeyCode_M);
KeyMap(0x4E, KeyCode_N);
KeyMap(0x4F, KeyCode_O);
KeyMap(0x50, KeyCode_P);
KeyMap(0x51, KeyCode_Q);
KeyMap(0x52, KeyCode_R);
KeyMap(0x53, KeyCode_S);
KeyMap(0x54, KeyCode_T);
KeyMap(0x55, KeyCode_U);
KeyMap(0x56, KeyCode_V);
KeyMap(0x57, KeyCode_W);
KeyMap(0x58, KeyCode_X);
KeyMap(0x59, KeyCode_Y);
KeyMap(0x5A, KeyCode_Z);
KeyMap(0x30, KeyCode_0);
KeyMap(0x31, KeyCode_1);
KeyMap(0x32, KeyCode_2);
KeyMap(0x33, KeyCode_3);
KeyMap(0x34, KeyCode_4);
KeyMap(0x35, KeyCode_5);
KeyMap(0x36, KeyCode_6);
KeyMap(0x37, KeyCode_7);
KeyMap(0x38, KeyCode_8);
KeyMap(0x39, KeyCode_9);
KeyMap(VK_OEM_4, KeyCode_OpenBracket);
KeyMap(VK_OEM_6, KeyCode_CloseBracket);
KeyMap(VK_OEM_1, KeyCode_Semicolon);
KeyMap(VK_OEM_7, KeyCode_Quote);
KeyMap(VK_OEM_COMMA, KeyCode_Comma);
KeyMap(VK_OEM_PERIOD, KeyCode_Period);
KeyMap(VK_OEM_2, KeyCode_Slash);
KeyMap(VK_OEM_5, KeyCode_BackSlash);
KeyMap(VK_OEM_3, KeyCode_Tilde);
KeyMap(VK_OEM_PLUS, KeyCode_Plus);
KeyMap(VK_OEM_MINUS, KeyCode_Minus);
KeyMap(VK_NUMPAD8, KeyCode_Num8);
KeyMap(VK_NUMPAD2, KeyCode_Num2);
KeyMap(VK_NUMPAD4, KeyCode_Num4);
KeyMap(VK_NUMPAD6, KeyCode_Num6);
KeyMap(VK_NUMPAD7, KeyCode_Num7);
KeyMap(VK_NUMPAD1, KeyCode_Num1);
KeyMap(VK_NUMPAD9, KeyCode_Num9);
KeyMap(VK_NUMPAD3, KeyCode_Num3);
KeyMap(VK_NUMPAD0, KeyCode_Num0);
KeyMap(VK_SEPARATOR, KeyCode_NumSeparator);
KeyMap(VK_MULTIPLY, KeyCode_NumMultiply);
KeyMap(VK_DIVIDE, KeyCode_NumDivide);
KeyMap(VK_ADD, KeyCode_NumPlus);
KeyMap(VK_SUBTRACT, KeyCode_NumMinus);
#undef KeyMap
if (!KeyFound)
return false;
*OutCode = KeyCode;
return true;
}
inline win32_game_module
Win32LoadGameModule(const char *SharedName) {
Assert(SharedName);
win32_game_module Result = {};
char GameLibraryName[1024] = {};
snprintf(GameLibraryName, ArraySize(GameLibraryName) - 1, "%s.dll", SharedName);
Win32Outf("Loading game module %s...", GameLibraryName);
Result.GameLibrary = LoadLibraryA(GameLibraryName);
if (Result.GameLibrary) {
Result.GameTrigger = (game_trigger *)GetProcAddress(Result.GameLibrary, "GameTrigger");
if (Result.GameTrigger)
Result.IsValid = true;
}
return Result;
}
inline win32_renderer_module
Win32LoadRendererModule(const char *SharedName, const char *APIName) {
Assert(APIName);
win32_renderer_module Result = {};
char RendererLibraryName[1024] = {};
snprintf(RendererLibraryName, ArraySize(RendererLibraryName) - 1, "%s_renderer_%s.dll", SharedName, APIName);
Win32Outf("Loading renderer module %s...", RendererLibraryName);
Result.RendererLibrary = LoadLibraryA(RendererLibraryName);
if (Result.RendererLibrary) {
renderer_get_api *RendererGetAPI = (renderer_get_api *)GetProcAddress(Result.RendererLibrary, "RendererGetAPI");
if (RendererGetAPI) {
Result.IsValid = true;
Result.API = RendererGetAPI();
}
}
return Result;
}
static uptr
Win32CalculateDesirableUsableMemorySize(void) {
uptr Result;
// NOTE(ivan): Detect how much memory is available.
MEMORYSTATUSEX MemStat;
MemStat.dwLength = sizeof(MemStat);
if (GlobalMemoryStatusEx(&MemStat)) {
// NOTE(ivan): Capture 80% of free RAM space and leave the rest for internal platform-layer and OS needs.
// TODO(ivan): Play aroud with this percent to achieve maximum RAM space allocation
// without stressing the OS and the environment too much.
Result = (uptr)((f64)MemStat.ullAvailPhys * 0.8);
} else {
// NOTE(ivan): Available free RAM detection went wrong
// for some strange reason - try to guess it approximately.
if (IsTargetCPU32Bit()) {
BOOL Is64BitWindows = FALSE;
if (!IsWow64Process(GetCurrentProcess(), &Is64BitWindows))
Is64BitWindows = FALSE;
// NOTE(ivan): 64-bit Windows allows 32-bit programs to eat 3 gigabytes of RAM
// instead of 2 gigabytes as in 32-bit Windows.
if (Is64BitWindows) // NOTE(ivan): Requesting 3Gb of memory for 32-bit program
Result = Gigabytes(3); // requires it being built with /largeaddressaware MS linker option.
else
Result = Gigabytes(2);
} else if (IsTargetCPU64Bit()) {
Result = Gigabytes(4);
}
}
return Result;
}
static LRESULT CALLBACK
Win32WindowProc(HWND Window, UINT Msg, WPARAM W, LPARAM L) {
switch (Msg) {
case WM_DESTROY: {
PostQuitMessage(0);
} break;
case WM_ACTIVATE: {
if (W == WA_ACTIVE || W == WA_CLICKACTIVE)
Win32State.IsWindowActive = true;
else
Win32State.IsWindowActive = false;
} break;
case WM_INPUT: {
u8 Buffer[sizeof(RAWINPUT)] = {};
u32 BufferSize = sizeof(RAWINPUT);
GetRawInputData((HRAWINPUT)L, RID_INPUT, Buffer, (PUINT)&BufferSize, sizeof(RAWINPUTHEADER));
RAWINPUT *RawInput = (RAWINPUT *)Buffer;
if (RawInput->header.dwType == RIM_TYPEKEYBOARD) {
RAWKEYBOARD *RawKeyboard = &RawInput->data.keyboard;
key_code KeyCode;
if (Win32MapVKToKeyCode(RawKeyboard->VKey, RawKeyboard->MakeCode,
(RawKeyboard->Flags & RI_KEY_E0) != 0,
(RawKeyboard->Flags & RI_KEY_E1) != 0,
&KeyCode))
Win32SetInputButtonState(&Win32State.GameInput->KbButtons[KeyCode],
(RawKeyboard->Flags & RI_KEY_BREAK) == 0);
} else if (RawInput->header.dwType == RIM_TYPEMOUSE) {
RAWMOUSE *RawMouse = &RawInput->data.mouse;
if (RawMouse->usFlags == MOUSE_MOVE_ABSOLUTE) {
Win32State.GameInput->MousePos.X = RawMouse->lLastX;
Win32State.GameInput->MousePos.Y = RawMouse->lLastY;
}
switch (RawMouse->usButtonFlags) {
case RI_MOUSE_BUTTON_1_DOWN: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_Left], true);
} break;
case RI_MOUSE_BUTTON_1_UP: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_Left], false);
} break;
case RI_MOUSE_BUTTON_2_DOWN: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_Middle], true);
} break;
case RI_MOUSE_BUTTON_2_UP: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_Middle], false);
} break;
case RI_MOUSE_BUTTON_3_DOWN: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_Right], true);
} break;
case RI_MOUSE_BUTTON_3_UP: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_Right], false);
} break;
case RI_MOUSE_BUTTON_4_DOWN: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_X1], true);
} break;
case RI_MOUSE_BUTTON_4_UP: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_X1], false);
} break;
case RI_MOUSE_BUTTON_5_DOWN: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_X2], true);
} break;
case RI_MOUSE_BUTTON_5_UP: {
Win32SetInputButtonState(&Win32State.GameInput->MouseButtons[MouseButton_X2], false);
} break;
case RI_MOUSE_WHEEL: {
s32 WheelRotations = (s32)RawMouse->usButtonData / WHEEL_DELTA;
Win32State.GameInput->MouseWheel += WheelRotations;
} break;
}
}
} break;
case WM_SETCURSOR: {
if (Win32State.IsDebugCursor)
SetCursor(LoadCursorA(0, MAKEINTRESOURCEA(32515))); // NOTE(ivan): IDC_CROSS.
else
SetCursor(0);
} break;
default: {
if (Msg == Win32State.QueryCancelAutoplay)
return TRUE; // NOTE(ivan): Cancel disc autoplay feature.
return DefWindowProcA(Window, Msg, W, L);
} break;
}
return FALSE;
}
int CALLBACK
WinMain(HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCommand) {
UnusedParam(PrevInstance);
UnusedParam(CommandLine);
platform_api Win32API = {};
game_memory GameMemory = {};
game_clocks GameClocks = {};
game_input GameInput = {};
Win32State.Instance = Instance;
Win32SetThreadName(GetCurrentThreadId(), GAMENAME " primary thread");
SetCursor(LoadCursorA(0, MAKEINTRESOURCEA(32514))); // NOTE(ivan): IDC_WAIT.
// NOTE(ivan): C runtime memory optimization for faster execution.
_CrtSetDbgFlag(0); // NOTE(ivan): Disable heap check every 1024 allocation.
_CrtSetDebugFillThreshold(0); // NOTE(ivan): Disable buffers filling.
Win32State.ArgC = __argc;
Win32State.ArgV = __argv;
Win32State.GameInput = &GameInput;
// NOTE(ivan): Debug cursor (cross) is initially visible on the main window in internal build.
#if INTERNAL
Win32State.IsDebugCursor = true;
#endif
Win32API.CheckParam = Win32CheckParam;
Win32API.CheckParamValue = Win32CheckParamValue;
Win32API.Outf = Win32Outf;
Win32API.Crashf = Win32Crashf;
Win32API.FOpen = Win32FOpen;
Win32API.FClose = Win32FClose;
Win32API.FRead = Win32FRead;
Win32API.FWrite = Win32FWrite;
Win32API.FSeek = Win32FSeek;
Win32API.FFlush = Win32FFlush;
// NOTE(ivan): Various Win32-specific strings declaration.
const char GameWindowClassName[] = (GAMENAME "Window");
const char GameExistsMutexName[] = (GAMENAME "Exists");
const char GameRestartMutexName[] = (GAMENAME "Restarts");
// NOTE(ivan): Check whether the host OS is not obsolete.
if (IsWindows7OrGreater()) {
// NOTE(ivan): Check debugger presence.
Win32State.IsDebuggerActive = (IsDebuggerPresent() == TRUE);
// NOTE(ivan): Initialize and setup COM.
Verify(CoInitializeEx(0, COINIT_MULTITHREADED) == S_OK);
Verify(CoInitializeSecurity(0, -1, 0, 0, RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE, 0, EOAC_NONE, 0) == S_OK);
// NOTE(ivan): Initialize Common Controls for modern visuals.
INITCOMMONCONTROLSEX InitCC;
InitCC.dwSize = sizeof(InitCC);
InitCC.dwICC = ICC_STANDARD_CLASSES;
Verify(InitCommonControlsEx(&InitCC));
// NOTE(ivan): Disable disc autoplay feature.
Win32State.QueryCancelAutoplay = RegisterWindowMessageA("QueryCancelAutoplay");
// NOTE(ivan): Obtain system high-resolution timer frequency.
LARGE_INTEGER PerformanceFrequency;
Verify(QueryPerformanceFrequency(&PerformanceFrequency));
Win32State.PerformanceFrequency = PerformanceFrequency.QuadPart;
// NOTE(ivan): Strange, but it is thre only way to set the system's scheduler granularity
// so our Sleep() calls will be way more accurate.
b32 IsSleepGranular = (timeBeginPeriod(1) != TIMERR_NOCANDO);
// NOTE(ivan): Obtain CPU information.
Win32API.CPUInfo = Win32GatherCPUInfo();
// NOTE(ivan): Obtain executable's file name, base name and path.
char ExecPath[1024] = {}, ExecName[1024] = {}, ExecNameNoExt[1024] = {};
char ModuleName[2048] = {};
Verify(GetModuleFileNameA(Win32State.Instance, ModuleName, ArraySize(ModuleName) - 1));
char *PastLastSlash = ModuleName, *Ptr = ModuleName;
while (*Ptr) {
if (*Ptr == '\\' || *Ptr == '/')
PastLastSlash = Ptr + 1;
Ptr++;
}
strcpy(ExecName, PastLastSlash);
strncpy(ExecPath, ModuleName, PastLastSlash - ModuleName);
strcpy(ExecNameNoExt, ExecName);
for (Ptr = ExecNameNoExt; *Ptr; Ptr++) {
if (*Ptr == '.') {
*Ptr = 0;
break;
}
}
Win32API.ExecutableName = ExecName;
Win32API.ExecutableNameNoExt = ExecNameNoExt;
Win32API.ExecutablePath = ExecPath;
// NOTE(ivan): Obtain game "shared name".
char SharedName[1024] = {};
strncpy(SharedName, ExecNameNoExt + 3, ArraySize(SharedName) - 1); // NOTE(ivan): Remove "run" from the name.
Win32API.SharedName = SharedName;
// NOTE(ivan): If restarting, wait until the previous instance of the program dies.
HANDLE RestartMutex = CreateMutexA(0, FALSE, GameRestartMutexName);
if (GetLastError() == ERROR_ALREADY_EXISTS) {
WaitForSingleObject(RestartMutex, INFINITE);
ReleaseMutex(RestartMutex);
}
CloseHandle(RestartMutex);
// NOTE(ivan): Check whether the program is already running.
HANDLE ExistsMutex = CreateMutexA(0, FALSE, GameExistsMutexName);
if (GetLastError() != ERROR_ALREADY_EXISTS) {
// NOTE(ivan): Create system console.
// As a GUI program, we do not normally get a console when we start.
// If we were run from the shell, we can attach to its console.
// If we already have a stdout handle, then we have been redirected
// and should just use that handle.
Win32State.Stdout = GetStdHandle(STD_OUTPUT_HANDLE);
if (Win32State.Stdout) {
// NOTE(ivan): It seems that running from a shell always creates a stdout handle
// for us, even if it does not go anywhere (running from explorer.exe does not).
// If we can get file information for this handle, it's a file or pipe, so use it.
// Otherwise, pretend it wasn't there and find a console to use instead.
BY_HANDLE_FILE_INFORMATION StdoutInfo;
if (!GetFileInformationByHandle(Win32State.Stdout, &StdoutInfo))
Win32State.Stdout = 0;
}
if (!Win32State.Stdout) {
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
Win32State.Stdout = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD Unused;
WriteFile(Win32State.Stdout, "\r\n", 2, &Unused, 0);
}
}
// NOTE(ivan): Set current working directory if necessary.
const char *ParamCwd = Win32CheckParamValue("-cwd");
if (ParamCwd)
SetCurrentDirectoryA(ParamCwd);
// NOTE(ivan): Create game primary storage.
GameMemory.FreeStorage.Size = Win32CalculateDesirableUsableMemorySize();
GameMemory.FreeStorage.Base = (u8 *)VirtualAlloc(0, GameMemory.FreeStorage.Size, MEM_COMMIT, PAGE_READWRITE);
if (GameMemory.FreeStorage.Base) {
GameMemory.StorageTotalSize = GameMemory.FreeStorage.Size;
// NOTE(ivan): Create main window.
WNDCLASSA WindowClass = {};
WindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
WindowClass.lpszClassName = GameWindowClassName;
WindowClass.lpfnWndProc = Win32WindowProc;
WindowClass.hInstance = Win32State.Instance;
if (RegisterClassA(&WindowClass)) {
HWND Window = CreateWindowExA(WS_EX_APPWINDOW,
WindowClass.lpszClassName,
GAMENAME,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
0, 0, Win32State.Instance, 0);
if (Window) {
HDC WindowDC = GetDC(Window); // NOTE(ivan): CS_OWNDC indicates that a window
// has single non-shared device context.
// NOTE(ivan): Obtain monitor refresh rate.
// TODO(ivan): Should it be updated each new frame to handle monitor settings change while
// the program is running?
s32 DisplayFrequency = GetDeviceCaps(WindowDC, VREFRESH);
if (DisplayFrequency < 2)
DisplayFrequency = 60; // TODO(ivan): Find a more appropriate way to obtain display frequency.
// NOTE(ivan): Target seconds to last per one frame.
f32 GameTargetFramerate = (1.0f / DisplayFrequency);
// NOTE(ivan): Initialize raw keyboard and mouse input.
RAWINPUTDEVICE RawDevices[2] = {};
RawDevices[0].usUsagePage = 0x01;
RawDevices[0].usUsage = 0x06;
RawDevices[0].dwFlags = 0;
RawDevices[0].hwndTarget = Window;
RawDevices[1].usUsagePage = 0x01;
RawDevices[1].usUsage = 0x02;
RawDevices[1].dwFlags = 0;
RawDevices[1].hwndTarget = Window;
RegisterRawInputDevices(RawDevices, 2, sizeof(RAWINPUTDEVICE));
// NOTE(ivan): Connect to XInput for processing Xbox controller(s) input.
win32_xinput_module XInputModule = Win32LoadXInputModule();
// NOTE(ivan): Connect to game module.
win32_game_module GameModule = Win32LoadGameModule(Win32API.SharedName);
if (GameModule.IsValid) {
// NOTE(ivan): Load appropriate renderer module.
win32_renderer_module RendererModule = Win32LoadRendererModule(Win32API.SharedName,
"dx11");
if (RendererModule.IsValid) {
renderer_init_platform_specific RendererPlatformSpecific = {};
RendererPlatformSpecific.TargetWindow = Window;
RendererModule.API->Init(&RendererPlatformSpecific);
// NOTE(ivan): Prepare the game.
GameModule.GameTrigger(GameTriggerType_Prepare,
&Win32API,
RendererModule.API,
&GameMemory,
&GameClocks,
&GameInput);
// NOTE(ivan): When all initialization is done, present the window.
ShowWindow(Window, ShowCommand);
SetCursor(LoadCursorA(0, MAKEINTRESOURCEA(32512))); // NOTE(ivan): IDC_ARROW.
// NOTE(ivan): Prepare game clocks and timings.
u64 LastCPUClockCounter = __rdtsc();
u64 LastCycleCounter = Win32GetClock();
// NOTE(ivan): Primary loop.
b32 IsGameRunning = true;
while (IsGameRunning) {
// NOTE(ivan): Process OS messages.
static MSG Msg;
while (PeekMessageA(&Msg, 0, 0, 0, PM_REMOVE)) {
if (Msg.message == WM_QUIT)
IsGameRunning = false;
TranslateMessage(&Msg);
DispatchMessageA(&Msg);
}
// NOTE(ivan): Do these routines only in case the main window is in focus.
if (Win32State.IsWindowActive) {
// NOTE(ivan): Process Xbox controllers state.
static DWORD MaxXboxControllers = Min((u32)XUSER_MAX_COUNT,
ArraySize(GameInput.XboxControllers));
for (u32 Index = 0; Index < MaxXboxControllers; Index++) {
xbox_controller_state *XboxController = &GameInput.XboxControllers[Index];
XINPUT_STATE XboxControllerState;
if (XInputModule.GetState(Index, &XboxControllerState) == ERROR_SUCCESS) {
XboxController->IsConnected = true;
// TODO(ivan): See if XboxControllerState.dwPacketNumber
// increments too rapidly.
static DWORD PrevXboxPacketNumber = 0;
if (PrevXboxPacketNumber < XboxControllerState.dwPacketNumber) {
PrevXboxPacketNumber = XboxControllerState.dwPacketNumber;
// NOTE(ivan): Process buttons.
XINPUT_GAMEPAD *XboxGamepad = &XboxControllerState.Gamepad;
Win32ProcessXInputDigitalButton(&XboxController->Start,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_START);
Win32ProcessXInputDigitalButton(&XboxController->Back,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_BACK);
Win32ProcessXInputDigitalButton(&XboxController->A,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_A);
Win32ProcessXInputDigitalButton(&XboxController->B,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_B);
Win32ProcessXInputDigitalButton(&XboxController->X,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_X);
Win32ProcessXInputDigitalButton(&XboxController->Y,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_Y);
Win32ProcessXInputDigitalButton(&XboxController->DPad.Up,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_DPAD_UP);
Win32ProcessXInputDigitalButton(&XboxController->DPad.Down,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_DPAD_DOWN);
Win32ProcessXInputDigitalButton(&XboxController->DPad.Left,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_DPAD_LEFT);
Win32ProcessXInputDigitalButton(&XboxController->DPad.Right,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_DPAD_RIGHT);
Win32ProcessXInputDigitalButton(&XboxController->LeftStick.Button,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_LEFT_THUMB);
Win32ProcessXInputDigitalButton(&XboxController->RightStick.Button,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_RIGHT_THUMB);
// NOTE(ivan): Process bumpers.
Win32ProcessXInputDigitalButton(&XboxController->LeftBumper,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_LEFT_SHOULDER);
Win32ProcessXInputDigitalButton(&XboxController->RightBumper,
XboxGamepad->wButtons,
XINPUT_GAMEPAD_RIGHT_SHOULDER);
// NOTE(ivan): Process triggers.
Win32SetInputButtonState(&XboxController->LeftTrigger.Button,
XboxGamepad->bLeftTrigger == 255);
Win32SetInputButtonState(&XboxController->RightTrigger.Button,
XboxGamepad->bRightTrigger == 255);
XboxController->LeftTrigger.PullValue = XboxGamepad->bLeftTrigger;
XboxController->RightTrigger.PullValue = XboxGamepad->bRightTrigger;
// NOTE(ivan): Process sticks positions.
XboxController->LeftStick.Pos.X =
Win32ProcessXInputStickValue(XboxGamepad->sThumbLX,
XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE);
XboxController->LeftStick.Pos.Y =
Win32ProcessXInputStickValue(XboxGamepad->sThumbLY,
XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE);
XboxController->RightStick.Pos.X =
Win32ProcessXInputStickValue(XboxGamepad->sThumbRX,
XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE);
XboxController->RightStick.Pos.Y =
Win32ProcessXInputStickValue(XboxGamepad->sThumbRY,
XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE);
}
// NOTE(ivan): Vibrate if requested (on previous frame).
if (XboxController->DoVibration.LeftMotorSpeed ||
XboxController->DoVibration.RightMotorSpeed) {
XINPUT_VIBRATION XboxControllerVibration;
XboxControllerVibration.wLeftMotorSpeed
= XboxController->DoVibration.LeftMotorSpeed;
XboxControllerVibration.wRightMotorSpeed
= XboxController->DoVibration.RightMotorSpeed;
XInputModule.SetState(Index, &XboxControllerVibration);
XboxController->DoVibration.LeftMotorSpeed = 0;
XboxController->DoVibration.RightMotorSpeed = 0;
}
} else {
XboxController->IsConnected = false;
}
}
// NOTE(ivan): Process Win32-specific input events.
if (GameInput.KbButtons[KeyCode_F4].IsDown &&
(GameInput.KbButtons[KeyCode_LeftAlt].IsDown ||
GameInput.KbButtons[KeyCode_RightAlt].IsDown))
IsGameRunning = false;
if (IsNewlyPressed(&GameInput.KbButtons[KeyCode_F2]))
Win32State.IsDebugCursor = !Win32State.IsDebugCursor;
// NOTE(ivan): Is running on battery?
SYSTEM_POWER_STATUS PowerStatus;
GetSystemPowerStatus(&PowerStatus);
Win32API.IsOnBattery = (PowerStatus.BatteryFlag != 128);
// NOTE(ivan): Update game frame.
GameModule.GameTrigger(GameTriggerType_Frame, 0, 0, 0, 0, 0);
// NOTE(ivan): Before the next frame, make all input events obsolete.
for (u32 Index = 0; Index < ArraySize(GameInput.KbButtons); Index++)
GameInput.KbButtons[Index].IsNew = false;
for (u32 Index = 0; Index < ArraySize(GameInput.MouseButtons); Index++)
GameInput.MouseButtons[Index].IsNew = false;
for (u32 Index = 0; Index < MaxXboxControllers; Index++) {
xbox_controller_state *XboxController = &GameInput.XboxControllers[Index];
XboxController->Start.IsNew = false;
XboxController->Back.IsNew = false;
XboxController->A.IsNew = false;
XboxController->B.IsNew = false;
XboxController->X.IsNew = false;
XboxController->Y.IsNew = false;
XboxController->DPad.Up.IsNew = false;
XboxController->DPad.Down.IsNew = false;
XboxController->DPad.Left.IsNew = false;
XboxController->DPad.Right.IsNew = false;
XboxController->LeftBumper.IsNew = false;
XboxController->RightBumper.IsNew = false;
XboxController->LeftStick.Button.IsNew = false;
XboxController->RightStick.Button.IsNew = false;
}
// NOTE(ivan): Escape primary loop if quit has been requested.
IsGameRunning = !Win32API.QuitRequested;
// NOTE(ivan): Finalize timings and synchronize framerate.
u64 EndCycleCounter = Win32GetClock();
f32 CycleSecondsElapsed =
Win32GetSecondsElapsed(LastCycleCounter, EndCycleCounter);
if (CycleSecondsElapsed < GameTargetFramerate) {
while (CycleSecondsElapsed < GameTargetFramerate) {
if (IsSleepGranular) {
DWORD SleepMS
= (DWORD)((GameTargetFramerate - CycleSecondsElapsed) * 1000);
if (SleepMS) // NOTE(ivan): Wa don't want to call Sleep(0).
Sleep(SleepMS);
}
CycleSecondsElapsed
= Win32GetSecondsElapsed(LastCycleCounter, Win32GetClock());
}
}
GameClocks.SecondsPerFrame = CycleSecondsElapsed;
u64 EndCPUClockCounter = __rdtsc();
GameClocks.CPUClocksPerFrame = EndCPUClockCounter - LastCPUClockCounter;
EndCycleCounter = Win32GetClock();
GameClocks.FramesPerSecond =
(f32)((f64)Win32State.PerformanceFrequency
/ (EndCycleCounter - LastCycleCounter));
LastCPUClockCounter = __rdtsc();
LastCycleCounter = EndCycleCounter;
}
}
// NOTE(ivan): Release renderer.
RendererModule.API->Shutdown();
FreeLibrary(RendererModule.RendererLibrary);
} else {
// NOTE(ivan): Renderer module cannot be loaded.
Win32Crashf(GAMENAME " cannot load renderer DLL!");
}
// NOTE(ivan): Release game and its module.
GameModule.GameTrigger(GameTriggerType_Release, 0, 0, 0, 0, 0);
FreeLibrary(GameModule.GameLibrary);
} else {
// NOTE(ivan): Game module cannot be loaded.
Win32Crashf(GAMENAME " cannot load game DLL!");
}
FreeLibrary(XInputModule.XInputLibrary);
RawDevices[0].dwFlags = RIDEV_REMOVE;
RawDevices[1].dwFlags = RIDEV_REMOVE;
RegisterRawInputDevices(RawDevices, 2, sizeof(RAWINPUTDEVICE));
ReleaseDC(Window, WindowDC);
} else {
// NOTE(ivan): Game window cannot be created.
Win32Crashf(GAMENAME " window cannot be created!");
}
DestroyWindow(Window);
} else {
// NOTE(ivan): Game window class cannot be registered.
Win32Crashf(GAMENAME " window class cannot be registered!");
}
VirtualFree(GameMemory.FreeStorage.Base, 0, MEM_RELEASE);
} else {
// NOTE(ivan): Game primary storage cannot be allocated.
Win32Crashf(GAMENAME " primary storage cannnot be allocated!");
}
// NOTE(ivan): No longer needs to be set.
ReleaseMutex(ExistsMutex);
CloseHandle(ExistsMutex);
} else {
// NOTE(ivan): Game is already running.
Win32Crashf(GAMENAME " instance is already running!");
}
if (IsSleepGranular)
timeEndPeriod(0);
CoUninitialize();
} else {
// NOTE(ivan): Obsolete OS.
Win32Crashf(GAMENAME " requires Windows 7 or newer OS!");
}
// NOTE(ivan): Start itself before quitting so the program restarts if requested.
if (Win32API.QuitToRestart) {
HANDLE RestartMutex = CreateMutexA(0, FALSE, GameRestartMutexName);
if (GetLastError() == ERROR_ALREADY_EXISTS) {
WaitForSingleObject(RestartMutex, INFINITE);
ReleaseMutex(RestartMutex);
CloseHandle(RestartMutex);
} else {
char ModuleName[2048] = {};
GetModuleFileNameA(Win32State.Instance, ModuleName, ArraySize(ModuleName) - 1);
PathQuoteSpacesA(ModuleName);
STARTUPINFO StartupInfo = {};
PROCESS_INFORMATION ProcessInfo = {};
if (CreateProcessA(0, ModuleName, 0, 0, FALSE, 0, 0, 0, &StartupInfo, &ProcessInfo)) {
// NOTE(ivan): Success.
} else {
CloseHandle(RestartMutex);
}
}
}
// NOTE(ivan): Goodbye world.
return Win32API.QuitReturnCode;
}
|
1d54b838a67fec5bfc97569c1bb57ec57629c4b7
|
aa4d78d6a25650b274591fa60fecc43cb78ff1bd
|
/alarm/alarm.ino
|
cfa56ca66d4710f816e2a81be4b11b765ca1f841
|
[] |
no_license
|
wnew/arduino_pi_alarm
|
b789d71fe081adca00d417d7a074f6f696fdfdac
|
ccaf239ec7ff63d11264817c0ffab9d2423852f7
|
refs/heads/master
| 2020-07-01T15:07:23.662984
| 2016-12-30T10:19:40
| 2016-12-30T10:19:40
| 74,336,316
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,960
|
ino
|
alarm.ino
|
// this project uses the arduino to poll the alarm sensors and to send a serial
// message to the rpi if there is any change in the state of the sensors. This
// means that the rpi is required to handle the alarm state.
// list of sensor pins, set this to the number of sensors in your system.
// this must match the number of sensors in your rpi python code
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
const uint8_t pins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56};
int pin_states[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1};
#else
const uint8_t pins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
int pin_states[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
#endif
bool state_changed = false;
// setup method
void setup() {
Serial.begin(115200);
Serial.println("Arduino Alarm System 4.0");
// setup pins as outputs with pullup resistors
for (int i = 0; i < sizeof(pins); i++) {
pinMode(pins[i], INPUT_PULLUP);
}
// read and set the initial state of the pins
for (int i = 0; i < sizeof(pins); i++) {
pin_states[i] = digitalRead(pins[i]);
}
}
// main loop
void loop() {
delay(25);
// read the pins and compare to the current state, if different save the changed state
for (int i = 0; i < sizeof(pins); i++) {
if (digitalRead(pins[i]) != pin_states[i]) {
state_changed = true;
pin_states[i] = !pin_states[i];
}
}
// if the state of any pin has changed, send the states over serial to the pi
if (state_changed == true) {
state_changed = false;
String serial_str = "s";
for (int i = 0; i < sizeof(pins); i++) {
serial_str = serial_str + pin_states[i];
}
serial_str = serial_str + "e";
Serial.println(serial_str);
}
one_second();
}
unsigned long previousMillis = 0; // last time update
long interval = 1000; // interval at which to do something (milliseconds)
// send the state of the sensors every second
// this adds to the robustness of the sensors
// also serves to send the states to the rpi before anything changes
void one_second() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
String serial_str = "s";
for (int i = 0; i < sizeof(pins); i++) {
serial_str = serial_str + pin_states[i];
}
serial_str = serial_str + "e";
Serial.println(serial_str);
}
}
|
80578705df1ca4e3498f86952516b6ae13f35dc3
|
71e295b8b1fbba937e92502856a22c3c69d49e4f
|
/src/engine/Scene/Scene.h
|
95c18ce0baa3720fb5a2ff1f4c292aeb473c5269
|
[] |
no_license
|
Douidik/GameEngine
|
a41f9737589e4ca543b44f1dc02f3fe8ef518823
|
e43da29402c6cb5d63490a6cc69cfbc972ba017b
|
refs/heads/master
| 2022-06-19T01:10:20.235816
| 2020-05-10T21:25:08
| 2020-05-10T21:25:08
| 262,878,057
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 584
|
h
|
Scene.h
|
#pragma once
#include "Primitives/GameObject.h"
class Scene {
public:
Scene(const std::string &name);
void addGameObject(GameObject *pGameObject);
void removeGameObject(GameObject *pGameObject);
void removeGameObject(const std::string &name);
GameObject *getGameObject(const std::string &name);
void update();
public:
inline void setName(const std::string &name) { mName = name; }
inline std::string getName() const { return mName; }
private:
std::vector<GameObject *> mGameObjects;
std::string mName;
};
|
eb260240ffc33847805230a22015512b61b6cc38
|
03341c7ff8115384a5edea4b6e66895b33ab73c1
|
/Codes/Basics/friend.cpp
|
396cc3930650efb6cfb98c4c95f98375f2fba942
|
[] |
no_license
|
abhi3700/My_Learning-Cpp
|
fa5e5f919c02e3dad7279c9b56c0d2cd6ddad0b6
|
73cc3a085a66f30a3fe480dff8d0c3a3e9689945
|
refs/heads/master
| 2022-07-11T15:43:56.066960
| 2022-06-14T07:21:59
| 2022-06-14T07:21:59
| 252,186,491
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,475
|
cpp
|
friend.cpp
|
/*
Use of `friend` keyword
- The global operator function is made friend of this class so
that it can access private members
*/
#include <iostream>
class complex
{
private:
int real, imag;
public:
complex( int r=0, int i=0) : real(r), imag(i) {}
void print() {
std::cout << real << " + " << imag << "i" << "\n";
}
friend complex operator +(const complex& c1, const complex& c2) {
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
// complex operator +(
// // const complex& c1
// complex const &c1
// )
// {
// complex res;
// res.real = real + c1.real;
// res.imag = imag + c1.imag;
// return res;
// }
};
int main() {
complex c1(10, 5), c2(2, 4);
auto c3 = c1 + c2;
c3.print();
return 0;
}
// *
/*#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
void print() { cout << real << " + i" << imag << endl; }
// The global operator function is made friend of this class so
// that it can access private members
friend Complex operator + (Complex const &, Complex const &);
};
Complex operator + (Complex const &c1, Complex const &c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
return 0;
}
*/
|
332725c9a76d5278bbd452eaf308fdc028e79cc9
|
e18ef95490745713792e75b84d48b943069ac152
|
/src/pkgi.cpp
|
45426fa22319b0f1fc4ac1d642436c512c92ab61
|
[
"Zlib",
"BSD-2-Clause"
] |
permissive
|
blastrock/pkgj
|
f6ee562743e9b0c338803cce829b8ea6f07059fd
|
fa3f130d6f5df224ddeef2b090e850af81a626a7
|
refs/heads/master
| 2023-08-14T18:59:35.994836
| 2023-07-31T08:46:56
| 2023-07-31T08:46:56
| 124,300,424
| 1,054
| 141
|
BSD-2-Clause
| 2023-07-07T19:29:21
| 2018-03-07T22:08:48
|
C++
|
UTF-8
|
C++
| false
| false
| 42,702
|
cpp
|
pkgi.cpp
|
#include "pkgi.hpp"
extern "C"
{
#include "style.h"
}
#include "bgdl.hpp"
#include "comppackdb.hpp"
#include "config.hpp"
#include "db.hpp"
#include "dialog.hpp"
#include "download.hpp"
#include "downloader.hpp"
#include "gameview.hpp"
#include "imgui.hpp"
#include "install.hpp"
#include "menu.hpp"
#include "update.hpp"
#include "utils.hpp"
#include "vitahttp.hpp"
#include "zrif.hpp"
#include "psm.hpp"
#include <vita2d.h>
#include <fmt/format.h>
#include <memory>
#include <set>
#include <psp2common/npdrm.h>
#include <cstddef>
#include <cstring>
#define PKGI_UPDATE_URL \
"https://api.github.com/repos/blastrock/pkgj/releases/latest"
namespace
{
typedef enum
{
StateError,
StateRefreshing,
StateMain,
} State;
State state = StateMain;
Mode mode = ModeGames;
uint32_t first_item;
uint32_t selected_item;
int search_active;
Config config;
Config config_temp;
int font_height;
int avail_height;
int bottom_y;
char search_text[256];
char error_state[256];
// used for multiple things actually
Mutex refresh_mutex("refresh_mutex");
std::string current_action;
std::unique_ptr<TitleDatabase> db;
std::unique_ptr<CompPackDatabase> comppack_db_games;
std::unique_ptr<CompPackDatabase> comppack_db_updates;
std::set<std::string> installed_games;
std::set<std::string> installed_themes;
std::unique_ptr<GameView> gameview;
bool need_refresh = true;
bool runtime_install_queued = false;
std::string content_to_refresh;
void pkgi_reload();
const char* pkgi_get_ok_str(void)
{
return pkgi_ok_button() == PKGI_BUTTON_X ? PKGI_UTF8_X : PKGI_UTF8_O;
}
const char* pkgi_get_cancel_str(void)
{
return pkgi_cancel_button() == PKGI_BUTTON_O ? PKGI_UTF8_O : PKGI_UTF8_X;
}
Type mode_to_type(Mode mode)
{
switch (mode)
{
case ModeGames:
return Game;
case ModeDlcs:
return Dlc;
case ModePsmGames:
return PsmGame;
case ModePsxGames:
return PsxGame;
case ModePspGames:
return PspGame;
case ModePspDlcs:
return PspDlc;
case ModeDemos:
case ModeThemes:
throw formatEx<std::runtime_error>(
"unsupported mode {}", static_cast<int>(mode));
}
throw formatEx<std::runtime_error>(
"unknown mode {}", static_cast<int>(mode));
}
BgdlType mode_to_bgdl_type(Mode mode)
{
switch (mode)
{
case ModePspGames:
case ModePsxGames:
case ModePspDlcs:
return BgdlTypePsp;
case ModePsmGames:
return BgdlTypePsm;
case ModeGames:
case ModeDemos:
return BgdlTypeGame;
case ModeDlcs:
return BgdlTypeDlc;
case ModeThemes:
return BgdlTypeTheme;
default:
throw formatEx<std::runtime_error>(
"unsupported bgdl mode {}", static_cast<int>(mode));
}
}
void configure_db(TitleDatabase* db, const char* search, const Config* config)
{
try
{
db->reload(
mode,
mode == ModeGames || mode == ModeDlcs
? config->filter
: config->filter & ~DbFilterInstalled,
config->sort,
config->order,
search ? search : "",
installed_games);
}
catch (const std::exception& e)
{
snprintf(
error_state,
sizeof(error_state),
"can't reload list: %s",
e.what());
pkgi_dialog_error(error_state);
}
}
std::string const& pkgi_get_url_from_mode(Mode mode)
{
switch (mode)
{
case ModeGames:
return config.games_url;
case ModeDlcs:
return config.dlcs_url;
case ModeDemos:
return config.demos_url;
case ModeThemes:
return config.themes_url;
case ModePsmGames:
return config.psm_games_url;
case ModePspGames:
return config.psp_games_url;
case ModePspDlcs:
return config.psp_dlcs_url;
case ModePsxGames:
return config.psx_games_url;
}
throw std::runtime_error(
fmt::format("unknown mode: {}", static_cast<int>(mode)));
}
void pkgi_refresh_thread(void)
{
LOG("starting update");
try
{
auto mode_count = ModeCount + (config.comppack_url.empty() ? 0 : 2);
ScopeProcessLock lock;
for (int i = 0; i < ModeCount; ++i)
{
const auto mode = static_cast<Mode>(i);
auto const url = pkgi_get_url_from_mode(mode);
if (url.empty())
continue;
{
std::lock_guard<Mutex> lock(refresh_mutex);
current_action = fmt::format(
"Refreshing {} [{}/{}]",
pkgi_mode_to_string(mode),
i + 1,
mode_count);
}
auto const http = std::make_unique<VitaHttp>();
db->update(mode, http.get(), url);
}
if (!config.comppack_url.empty())
{
{
std::lock_guard<Mutex> lock(refresh_mutex);
current_action = fmt::format(
"Refreshing games compatibility packs [{}/{}]",
mode_count - 1,
mode_count);
}
{
auto const http = std::make_unique<VitaHttp>();
comppack_db_games->update(
http.get(), config.comppack_url + "entries.txt");
}
{
std::lock_guard<Mutex> lock(refresh_mutex);
current_action = fmt::format(
"Refreshing updates compatibility packs [{}/{}]",
mode_count,
mode_count);
}
{
auto const http = std::make_unique<VitaHttp>();
comppack_db_updates->update(
http.get(), config.comppack_url + "entries_patch.txt");
}
}
first_item = 0;
selected_item = 0;
configure_db(db.get(), search_active ? search_text : NULL, &config);
}
catch (const std::exception& e)
{
snprintf(
error_state,
sizeof(error_state),
"can't get list: %s",
e.what());
pkgi_dialog_error(error_state);
}
state = StateMain;
}
const char* pkgi_get_mode_partition()
{
return mode == ModePspGames || mode == ModePspDlcs || mode == ModePsxGames
? config.install_psp_psx_location.c_str()
: "ux0:";
}
void pkgi_refresh_installed_packages()
{
auto games = pkgi_get_installed_games();
installed_games.clear();
installed_games.insert(
std::make_move_iterator(games.begin()),
std::make_move_iterator(games.end()));
auto themes = pkgi_get_installed_themes();
installed_themes.clear();
installed_themes.insert(
std::make_move_iterator(themes.begin()),
std::make_move_iterator(themes.end()));
}
bool pkgi_is_installed(const char* titleid)
{
return installed_games.find(titleid) != installed_games.end();
}
bool pkgi_theme_is_installed(std::string contentid)
{
if (contentid.size() < 19)
return false;
contentid.erase(16, 3);
contentid.erase(0, 7);
return installed_themes.find(contentid) != installed_themes.end();
}
void do_download(Downloader& downloader, DbItem* item) {
pkgi_start_download(downloader, *item);
item->presence = PresenceUnknown;
}
void pkgi_install_package(Downloader& downloader, DbItem* item)
{
if (item->presence == PresenceInstalled)
{
LOGF("[{}] {} - already installed", item->content, item->name);
pkgi_dialog_question(
fmt::format(
"{} is already installed."
"Would you like to redownload it?",
item->name)
.c_str(),
{{"Redownload.", [&downloader, item] { do_download(downloader, item); }},
{"Dont Redownload.", [] {} }});
return;
}
do_download(downloader, item);
}
void pkgi_friendly_size(char* text, uint32_t textlen, int64_t size)
{
if (size <= 0)
{
text[0] = 0;
}
else if (size < 1000LL)
{
pkgi_snprintf(text, textlen, "%u " PKGI_UTF8_B, (uint32_t)size);
}
else if (size < 1000LL * 1000)
{
pkgi_snprintf(text, textlen, "%.2f " PKGI_UTF8_KB, size / 1024.f);
}
else if (size < 1000LL * 1000 * 1000)
{
pkgi_snprintf(
text, textlen, "%.2f " PKGI_UTF8_MB, size / 1024.f / 1024.f);
}
else
{
pkgi_snprintf(
text,
textlen,
"%.2f " PKGI_UTF8_GB,
size / 1024.f / 1024.f / 1024.f);
}
}
void pkgi_set_mode(Mode set_mode)
{
mode = set_mode;
pkgi_reload();
first_item = 0;
selected_item = 0;
}
void pkgi_refresh_list()
{
state = StateRefreshing;
pkgi_start_thread("refresh_thread", &pkgi_refresh_thread);
}
void pkgi_do_main(Downloader& downloader, pkgi_input* input)
{
int col_titleid = 0;
int col_region = col_titleid + pkgi_text_width("PCSE00000") +
PKGI_MAIN_COLUMN_PADDING;
int col_installed =
col_region + pkgi_text_width("USA") + PKGI_MAIN_COLUMN_PADDING;
int col_name = col_installed + pkgi_text_width(PKGI_UTF8_INSTALLED) +
PKGI_MAIN_COLUMN_PADDING;
uint32_t db_count = db->count();
if (input)
{
if (input->active & PKGI_BUTTON_UP)
{
if (selected_item == first_item && first_item > 0)
{
first_item--;
selected_item = first_item;
}
else if (selected_item > 0)
{
selected_item--;
}
else if (selected_item == 0)
{
selected_item = db_count - 1;
uint32_t max_items =
avail_height / (font_height + PKGI_MAIN_ROW_PADDING) -
1;
first_item =
db_count > max_items ? db_count - max_items - 1 : 0;
}
}
if (input->active & PKGI_BUTTON_DOWN)
{
uint32_t max_items =
avail_height / (font_height + PKGI_MAIN_ROW_PADDING) - 1;
if (selected_item == db_count - 1)
{
selected_item = first_item = 0;
}
else if (selected_item == first_item + max_items)
{
first_item++;
selected_item++;
}
else
{
selected_item++;
}
}
if (input->active & PKGI_BUTTON_LEFT)
{
uint32_t max_items =
avail_height / (font_height + PKGI_MAIN_ROW_PADDING) - 1;
if (first_item < max_items)
{
first_item = 0;
}
else
{
first_item -= max_items;
}
if (selected_item < max_items)
{
selected_item = 0;
}
else
{
selected_item -= max_items;
}
}
if (input->active & PKGI_BUTTON_RIGHT)
{
uint32_t max_items =
avail_height / (font_height + PKGI_MAIN_ROW_PADDING) - 1;
if (first_item + max_items < db_count - 1)
{
first_item += max_items;
selected_item += max_items;
if (selected_item >= db_count)
{
selected_item = db_count - 1;
}
}
}
}
int y = font_height + PKGI_MAIN_HLINE_EXTRA;
int line_height = font_height + PKGI_MAIN_ROW_PADDING;
for (uint32_t i = first_item; i < db_count; i++)
{
DbItem* item = db->get(i);
uint32_t color = PKGI_COLOR_TEXT;
const auto titleid = item->titleid.c_str();
if (item->presence == PresenceUnknown)
{
switch (mode)
{
case ModeGames:
case ModeDemos:
if (pkgi_is_installed(titleid))
item->presence = PresenceInstalled;
else if (downloader.is_in_queue(Game, item->content))
item->presence = PresenceInstalling;
break;
case ModePsmGames:
if (pkgi_psm_is_installed(titleid))
item->presence = PresenceInstalled;
else if (downloader.is_in_queue(PsmGame, item->content))
item->presence = PresenceInstalling;
break;
case ModePspDlcs:
if (pkgi_psp_is_installed(
pkgi_get_mode_partition(), item->content.c_str()))
item->presence = PresenceGamePresent;
else if (downloader.is_in_queue(PspGame, item->content))
item->presence = PresenceInstalling;
break;
case ModePspGames:
if (pkgi_psp_is_installed(
pkgi_get_mode_partition(), item->content.c_str()))
item->presence = PresenceInstalled;
else if (downloader.is_in_queue(PspGame, item->content))
item->presence = PresenceInstalling;
break;
case ModePsxGames:
if (pkgi_psx_is_installed(
pkgi_get_mode_partition(), item->content.c_str()))
item->presence = PresenceInstalled;
else if (downloader.is_in_queue(PsxGame, item->content))
item->presence = PresenceInstalling;
break;
case ModeDlcs:
if (downloader.is_in_queue(Dlc, item->content))
item->presence = PresenceInstalling;
else if (pkgi_dlc_is_installed(item->content.c_str()))
item->presence = PresenceInstalled;
else if (pkgi_is_installed(titleid))
item->presence = PresenceGamePresent;
break;
case ModeThemes:
if (pkgi_theme_is_installed(item->content))
item->presence = PresenceInstalled;
else if (pkgi_is_installed(titleid))
item->presence = PresenceGamePresent;
break;
}
if (item->presence == PresenceUnknown)
{
if (pkgi_is_incomplete(
pkgi_get_mode_partition(), item->content.c_str()))
item->presence = PresenceIncomplete;
else
item->presence = PresenceMissing;
}
}
char size_str[64];
pkgi_friendly_size(size_str, sizeof(size_str), item->size);
int sizew = pkgi_text_width(size_str);
pkgi_clip_set(0, y, VITA_WIDTH, line_height);
if (i == selected_item)
{
pkgi_draw_rect(
0,
y,
VITA_WIDTH,
font_height + PKGI_MAIN_ROW_PADDING - 1,
PKGI_COLOR_SELECTED_BACKGROUND);
}
pkgi_draw_text(col_titleid, y, color, titleid);
const char* region;
switch (pkgi_get_region(item->titleid))
{
case RegionASA:
region = "ASA";
break;
case RegionEUR:
region = "EUR";
break;
case RegionJPN:
region = "JPN";
break;
case RegionINT:
region = "INT";
break;
case RegionUSA:
region = "USA";
break;
default:
region = "???";
break;
}
pkgi_draw_text(col_region, y, color, region);
if (item->presence == PresenceIncomplete)
{
pkgi_draw_text(col_installed, y, color, PKGI_UTF8_PARTIAL);
}
else if (item->presence == PresenceInstalled)
{
pkgi_draw_text(col_installed, y, color, PKGI_UTF8_INSTALLED);
}
else if (item->presence == PresenceGamePresent)
{
pkgi_draw_text(
col_installed,
y,
PKGI_COLOR_GAME_PRESENT,
PKGI_UTF8_INSTALLED);
}
else if (item->presence == PresenceInstalling)
{
pkgi_draw_text(col_installed, y, color, PKGI_UTF8_INSTALLING);
}
pkgi_draw_text(
VITA_WIDTH - PKGI_MAIN_SCROLL_WIDTH - PKGI_MAIN_SCROLL_PADDING -
sizew,
y,
color,
size_str);
pkgi_clip_remove();
pkgi_clip_set(
col_name,
y,
VITA_WIDTH - PKGI_MAIN_SCROLL_WIDTH - PKGI_MAIN_SCROLL_PADDING -
PKGI_MAIN_COLUMN_PADDING - sizew - col_name,
line_height);
pkgi_draw_text(col_name, y, color, item->name.c_str());
pkgi_clip_remove();
y += font_height + PKGI_MAIN_ROW_PADDING;
if (y > VITA_HEIGHT - (2 * font_height + PKGI_MAIN_HLINE_EXTRA))
{
break;
}
else if (
y + font_height >
VITA_HEIGHT - (2 * font_height + PKGI_MAIN_HLINE_EXTRA))
{
line_height =
(VITA_HEIGHT - (2 * font_height + PKGI_MAIN_HLINE_EXTRA)) -
(y + 1);
if (line_height < PKGI_MAIN_ROW_PADDING)
{
break;
}
}
}
if (db_count == 0)
{
const char* text = "No items! Try to refresh.";
int w = pkgi_text_width(text);
pkgi_draw_text(
(VITA_WIDTH - w) / 2, VITA_HEIGHT / 2, PKGI_COLOR_TEXT, text);
}
// scroll-bar
if (db_count != 0)
{
uint32_t max_items =
(avail_height + font_height + PKGI_MAIN_ROW_PADDING - 1) /
(font_height + PKGI_MAIN_ROW_PADDING) -
1;
if (max_items < db_count)
{
uint32_t min_height = PKGI_MAIN_SCROLL_MIN_HEIGHT;
uint32_t height = max_items * avail_height / db_count;
uint32_t start =
first_item *
(avail_height - (height < min_height ? min_height : 0)) /
db_count;
height = max32(height, min_height);
pkgi_draw_rect(
VITA_WIDTH - PKGI_MAIN_SCROLL_WIDTH - 1,
font_height + PKGI_MAIN_HLINE_EXTRA + start,
PKGI_MAIN_SCROLL_WIDTH,
height,
PKGI_COLOR_SCROLL_BAR);
}
}
if (input && (input->pressed & pkgi_ok_button()))
{
input->pressed &= ~pkgi_ok_button();
if (selected_item >= db->count())
return;
DbItem* item = db->get(selected_item);
if (mode == ModeGames)
gameview = std::make_unique<GameView>(
&config,
&downloader,
item,
comppack_db_games->get(item->titleid),
comppack_db_updates->get(item->titleid));
else if (mode == ModeThemes || mode == ModeDemos)
{
pkgi_start_download(downloader, *item);
}
else
{
if (downloader.is_in_queue(mode_to_type(mode), item->content))
{
downloader.remove_from_queue(mode_to_type(mode), item->content);
item->presence = PresenceUnknown;
}
else
pkgi_install_package(downloader, item);
}
}
else if (input && (input->pressed & PKGI_BUTTON_T))
{
input->pressed &= ~PKGI_BUTTON_T;
config_temp = config;
int allow_refresh = !config.games_url.empty() << 0 |
!config.dlcs_url.empty() << 1 |
!config.demos_url.empty() << 6 |
!config.themes_url.empty() << 5 |
!config.psx_games_url.empty() << 2 |
!config.psp_games_url.empty() << 3 |
!config.psp_dlcs_url.empty() << 7 |
!config.psm_games_url.empty() << 4;
pkgi_menu_start(search_active, &config, allow_refresh);
}
}
void pkgi_do_refresh(void)
{
std::string text;
uint32_t updated;
uint32_t total;
db->get_update_status(&updated, &total);
if (total == 0)
text = fmt::format("{}...", current_action);
else
text = fmt::format("{}... {}%", current_action, updated * 100 / total);
int w = pkgi_text_width(text.c_str());
pkgi_draw_text(
(VITA_WIDTH - w) / 2,
VITA_HEIGHT / 2,
PKGI_COLOR_TEXT,
text.c_str());
}
void pkgi_do_head(void)
{
const char* version = PKGI_VERSION;
char title[256];
pkgi_snprintf(title, sizeof(title), "PKGj v%s", version);
pkgi_draw_text(0, 0, PKGI_COLOR_TEXT_HEAD, title);
pkgi_draw_rect(
0,
font_height,
VITA_WIDTH,
PKGI_MAIN_HLINE_HEIGHT,
PKGI_COLOR_HLINE);
int rightw;
if (pkgi_battery_present())
{
char battery[256];
pkgi_snprintf(
battery,
sizeof(battery),
"Battery: %u%%",
pkgi_bettery_get_level());
uint32_t color;
if (pkgi_battery_is_low())
{
color = PKGI_COLOR_BATTERY_LOW;
}
else if (pkgi_battery_is_charging())
{
color = PKGI_COLOR_BATTERY_CHARGING;
}
else
{
color = PKGI_COLOR_TEXT_HEAD;
}
rightw = pkgi_text_width(battery);
pkgi_draw_text(
VITA_WIDTH - PKGI_MAIN_HLINE_EXTRA - rightw, 0, color, battery);
}
else
{
rightw = 0;
}
char text[256];
int left = pkgi_text_width(search_text) + PKGI_MAIN_TEXT_PADDING;
int right = rightw + PKGI_MAIN_TEXT_PADDING;
if (search_active)
pkgi_snprintf(
text,
sizeof(text),
"%s >> %s <<",
pkgi_mode_to_string(mode).c_str(),
search_text);
else
pkgi_snprintf(
text, sizeof(text), "%s", pkgi_mode_to_string(mode).c_str());
pkgi_clip_set(
left,
0,
VITA_WIDTH - right - left,
font_height + PKGI_MAIN_HLINE_EXTRA);
pkgi_draw_text(
(VITA_WIDTH - pkgi_text_width(text)) / 2,
0,
PKGI_COLOR_TEXT_TAIL,
text);
pkgi_clip_remove();
}
uint64_t last_progress_time;
uint64_t last_progress_offset;
uint64_t last_progress_speed;
uint64_t get_speed(const uint64_t download_offset)
{
const uint64_t now = pkgi_time_msec();
const uint64_t progress_time = now - last_progress_time;
if (progress_time < 1000)
return last_progress_speed;
const uint64_t progress_data = download_offset - last_progress_offset;
last_progress_speed = progress_data * 1000 / progress_time;
last_progress_offset = download_offset;
last_progress_time = now;
return last_progress_speed;
}
void pkgi_do_tail(Downloader& downloader)
{
char text[256];
pkgi_draw_rect(
0, bottom_y, VITA_WIDTH, PKGI_MAIN_HLINE_HEIGHT, PKGI_COLOR_HLINE);
const auto current_download = downloader.get_current_download();
uint64_t download_offset;
uint64_t download_size;
std::tie(download_offset, download_size) =
downloader.get_current_download_progress();
// avoid divide by 0
if (download_size == 0)
download_size = 1;
pkgi_draw_rect(
0,
bottom_y + PKGI_MAIN_HLINE_HEIGHT,
VITA_WIDTH * download_offset / download_size,
font_height + PKGI_MAIN_ROW_PADDING - 1,
PKGI_COLOR_PROGRESS_BACKGROUND);
if (current_download)
{
const auto speed = get_speed(download_offset);
std::string sspeed;
if (speed > 1000 * 1024)
sspeed = fmt::format("{:.3g} MB/s", speed / 1024.f / 1024.f);
else if (speed > 1000)
sspeed = fmt::format("{:.3g} KB/s", speed / 1024.f);
else
sspeed = fmt::format("{} B/s", speed);
pkgi_snprintf(
text,
sizeof(text),
"Downloading %s: %s (%s, %d%%)",
type_to_string(current_download->type).c_str(),
current_download->name.c_str(),
sspeed.c_str(),
static_cast<int>(download_offset * 100 / download_size));
}
else
pkgi_snprintf(text, sizeof(text), "Idle");
pkgi_draw_text(0, bottom_y, PKGI_COLOR_TEXT_TAIL, text);
const auto second_line = bottom_y + font_height + PKGI_MAIN_ROW_PADDING;
uint32_t count = db->count();
uint32_t total = db->total();
if (count == total)
{
pkgi_snprintf(text, sizeof(text), "Count: %u", count);
}
else
{
pkgi_snprintf(text, sizeof(text), "Count: %u (%u)", count, total);
}
pkgi_draw_text(0, second_line, PKGI_COLOR_TEXT_TAIL, text);
// get free space of partition only if looking at psx or psp games else show
// ux0:
char size[64];
if (mode == ModePsxGames || mode == ModePspGames)
{
pkgi_friendly_size(
size,
sizeof(size),
pkgi_get_free_space(pkgi_get_mode_partition()));
}
else
{
pkgi_friendly_size(size, sizeof(size), pkgi_get_free_space("ux0:"));
}
char free[64];
pkgi_snprintf(free, sizeof(free), "Free: %s", size);
int rightw = pkgi_text_width(free);
pkgi_draw_text(
VITA_WIDTH - PKGI_MAIN_HLINE_EXTRA - rightw,
second_line,
PKGI_COLOR_TEXT_TAIL,
free);
int left = pkgi_text_width(text) + PKGI_MAIN_TEXT_PADDING;
int right = rightw + PKGI_MAIN_TEXT_PADDING;
std::string bottom_text;
if (gameview || pkgi_dialog_is_open())
{
bottom_text = fmt::format(
"{} select {} close", pkgi_get_ok_str(), pkgi_get_cancel_str());
}
else if (pkgi_menu_is_open())
{
bottom_text = fmt::format(
"{} select " PKGI_UTF8_T " close {} cancel",
pkgi_get_ok_str(),
pkgi_get_cancel_str());
}
else
{
if (mode == ModeGames)
bottom_text += fmt::format("{} details ", pkgi_get_ok_str());
else
{
DbItem* item = db->get(selected_item);
if (item && item->presence == PresenceInstalling)
bottom_text += fmt::format("{} cancel ", pkgi_get_ok_str());
else if (item && item->presence != PresenceInstalled)
bottom_text += fmt::format("{} install ", pkgi_get_ok_str());
}
bottom_text += PKGI_UTF8_T " menu";
}
pkgi_clip_set(
left,
second_line,
VITA_WIDTH - right - left,
VITA_HEIGHT - second_line);
pkgi_draw_text(
(VITA_WIDTH - pkgi_text_width(bottom_text.c_str())) / 2,
second_line,
PKGI_COLOR_TEXT_TAIL,
bottom_text.c_str());
pkgi_clip_remove();
}
void pkgi_do_error(void)
{
pkgi_draw_text(
(VITA_WIDTH - pkgi_text_width(error_state)) / 2,
VITA_HEIGHT / 2,
PKGI_COLOR_TEXT_ERROR,
error_state);
}
void reposition(void)
{
uint32_t count = db->count();
if (first_item + selected_item < count)
{
return;
}
uint32_t max_items = (avail_height + font_height + PKGI_MAIN_ROW_PADDING -
1) / (font_height + PKGI_MAIN_ROW_PADDING) -
1;
if (count > max_items)
{
uint32_t delta = selected_item - first_item;
first_item = count - max_items;
selected_item = first_item + delta;
}
else
{
first_item = 0;
selected_item = 0;
}
}
void pkgi_reload()
{
try
{
configure_db(db.get(), search_active ? search_text : NULL, &config);
}
catch (const std::exception& e)
{
LOGF("error during reload: {}", e.what());
pkgi_dialog_error(
fmt::format(
"failed to reload db: {}, try to refresh?", e.what())
.c_str());
}
}
void pkgi_open_db()
{
try
{
first_item = 0;
selected_item = 0;
db = std::make_unique<TitleDatabase>(pkgi_get_config_folder());
comppack_db_games = std::make_unique<CompPackDatabase>(
std::string(pkgi_get_config_folder()) + "/comppack.db");
comppack_db_updates = std::make_unique<CompPackDatabase>(
std::string(pkgi_get_config_folder()) + "/comppack_updates.db");
}
catch (const std::exception& e)
{
LOGF("error during database open: {}", e.what());
throw formatEx<std::runtime_error>(
"DB initialization error: %s\nTry to delete them?");
}
pkgi_reload();
}
}
void pkgi_create_psp_rif(std::string contentid, uint8_t* rif)
{
SceNpDrmLicense license;
memset(&license, 0x00, sizeof(SceNpDrmLicense));
license.account_id = 0x0123456789ABCDEFLL;
memset(license.ecdsa_signature, 0xFF, 0x28);
strncpy(license.content_id, contentid.c_str(), 0x30);
memcpy(rif, &license, PKGI_PSP_RIF_SIZE);
}
void pkgi_download_psm_runtime_if_needed() {
if(!pkgi_is_installed("PCSI00011") && !runtime_install_queued) {
uint8_t rif[PKGI_PSM_RIF_SIZE];
char message[256];
pkgi_zrif_decode(PSM_RUNTIME_DRMFREE_LICENSE, rif, message, sizeof(message));
pkgi_start_bgdl(
BgdlTypeGame,
"PlayStation Mobile Runtime Package",
"http://ares.dl.playstation.net/psm-runtime/IP9100-PCSI00011_00-PSMRUNTIME000000.pkg",
std::vector<uint8_t>(rif, rif + PKGI_PSM_RIF_SIZE));
runtime_install_queued = true;
}
}
void pkgi_start_download(Downloader& downloader, const DbItem& item)
{
LOGF("[{}] {} - starting to install", item.content, item.name);
try
{
// download PSM Runtime if a PSM game is requested to be installed ..
if(mode == ModePsmGames)
pkgi_download_psm_runtime_if_needed();
// Just use the maximum size to be safe
uint8_t rif[PKGI_PSM_RIF_SIZE];
char message[256];
if (item.zrif.empty() ||
pkgi_zrif_decode(item.zrif.c_str(), rif, message, sizeof(message)))
{
if (
mode == ModeGames || mode == ModeDlcs || mode == ModeDemos || mode == ModeThemes || // Vita contents
(MODE_IS_PSPEMU(mode) && pkgi_is_module_present("NoPspEmuDrm_kern")) || // Psp Contents
(mode == ModePsmGames && pkgi_is_module_present("NoPsmDrm")) // Psm Contents
)
{
if (MODE_IS_PSPEMU(mode)) {
pkgi_create_psp_rif(item.content, rif);
}
pkgi_start_bgdl(
mode_to_bgdl_type(mode),
item.name,
item.url,
std::vector<uint8_t>(rif, rif + PKGI_PSM_RIF_SIZE));
pkgi_dialog_message(
fmt::format(
"Installation of {} queued in LiveArea",
item.name)
.c_str());
}
else {
downloader.add(DownloadItem{
mode_to_type(mode),
item.name,
item.content,
item.url,
item.zrif.empty()
? std::vector<uint8_t>{}
: std::vector<uint8_t>(
rif, rif + PKGI_PSM_RIF_SIZE),
item.has_digest ? std::vector<uint8_t>(
item.digest.begin(),
item.digest.end())
: std::vector<uint8_t>{},
!config.install_psp_as_pbp,
pkgi_get_mode_partition(),
""});
}
}
else
{
pkgi_dialog_error(message);
}
}
catch (const std::exception& e)
{
pkgi_dialog_error(
fmt::format("Failed to install {}: {}", item.name, e.what())
.c_str());
}
}
int main()
{
pkgi_start();
try
{
if (!pkgi_is_unsafe_mode())
throw std::runtime_error(
"PKGj requires unsafe mode to be enabled in HENkaku "
"settings!");
Downloader downloader;
downloader.refresh = [](const std::string& content)
{
std::lock_guard<Mutex> lock(refresh_mutex);
content_to_refresh = content;
need_refresh = true;
};
downloader.error = [](const std::string& error)
{
// FIXME this runs on the wrong thread
pkgi_dialog_error(("Download failure: " + error).c_str());
};
LOG("started");
config = pkgi_load_config();
pkgi_dialog_init();
font_height = pkgi_text_height("M");
avail_height = VITA_HEIGHT - 3 * (font_height + PKGI_MAIN_HLINE_EXTRA);
bottom_y = VITA_HEIGHT - 2 * font_height - PKGI_MAIN_ROW_PADDING;
pkgi_open_db();
pkgi_texture background = pkgi_load_png(background);
if (!config.no_version_check)
start_update_thread();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
// Build and load the texture atlas into a texture
uint32_t* pixels = NULL;
int width, height;
if (!io.Fonts->AddFontFromFileTTF(
"sa0:/data/font/pvf/ltn0.pvf",
20.0f,
0,
io.Fonts->GetGlyphRangesDefault()))
throw std::runtime_error("failed to load ltn0.pvf");
if (!io.Fonts->AddFontFromFileTTF(
"sa0:/data/font/pvf/jpn0.pvf",
20.0f,
0,
io.Fonts->GetGlyphRangesJapanese()))
throw std::runtime_error("failed to load jpn0.pvf");
io.Fonts->GetTexDataAsRGBA32((uint8_t**)&pixels, &width, &height);
vita2d_texture* font_texture =
vita2d_create_empty_texture(width, height);
const auto stride = vita2d_texture_get_stride(font_texture) / 4;
auto texture_data = (uint32_t*)vita2d_texture_get_datap(font_texture);
for (auto y = 0; y < height; ++y)
for (auto x = 0; x < width; ++x)
texture_data[y * stride + x] = pixels[y * width + x];
io.Fonts->TexID = font_texture;
init_imgui();
pkgi_input input;
while (pkgi_update(&input))
{
ImGuiIO& io = ImGui::GetIO();
io.DeltaTime = 1.0f / 60.0f;
io.DisplaySize.x = VITA_WIDTH;
io.DisplaySize.y = VITA_HEIGHT;
if (gameview || pkgi_dialog_is_open())
{
io.AddKeyEvent(
ImGuiKey_GamepadDpadUp, input.pressed & PKGI_BUTTON_UP);
io.AddKeyEvent(
ImGuiKey_GamepadDpadDown,
input.pressed & PKGI_BUTTON_DOWN);
io.AddKeyEvent(
ImGuiKey_GamepadDpadLeft,
input.pressed & PKGI_BUTTON_LEFT);
io.AddKeyEvent(
ImGuiKey_GamepadDpadRight,
input.pressed & PKGI_BUTTON_RIGHT);
io.AddKeyEvent(
ImGuiKey_GamepadFaceDown,
input.pressed & pkgi_ok_button());
if (input.pressed & pkgi_cancel_button() && gameview)
gameview->close();
input.active = 0;
input.pressed = 0;
}
if (need_refresh)
{
std::lock_guard<Mutex> lock(refresh_mutex);
pkgi_refresh_installed_packages();
if (!content_to_refresh.empty())
{
const auto item =
db->get_by_content(content_to_refresh.c_str());
if (item)
item->presence = PresenceUnknown;
else
LOGF("couldn't find {} for refresh",
content_to_refresh);
content_to_refresh.clear();
}
if (gameview)
gameview->refresh();
need_refresh = false;
}
ImGui::NewFrame();
pkgi_draw_texture(background, 0, 0);
pkgi_do_head();
switch (state)
{
case StateError:
pkgi_do_error();
break;
case StateRefreshing:
pkgi_do_refresh();
break;
case StateMain:
pkgi_do_main(
downloader,
pkgi_dialog_is_open() || pkgi_menu_is_open() ? NULL
: &input);
break;
}
pkgi_do_tail(downloader);
if (gameview)
{
gameview->render();
if (gameview->is_closed())
gameview = nullptr;
}
if (pkgi_dialog_is_open())
{
pkgi_do_dialog();
}
if (pkgi_dialog_input_update())
{
search_active = 1;
pkgi_dialog_input_get_text(search_text, sizeof(search_text));
configure_db(db.get(), search_text, &config);
reposition();
}
if (pkgi_menu_is_open())
{
if (pkgi_do_menu(&input))
{
Config new_config;
pkgi_menu_get(&new_config);
if (config_temp.sort != new_config.sort ||
config_temp.order != new_config.order ||
config_temp.filter != new_config.filter)
{
config_temp = new_config;
configure_db(
db.get(),
search_active ? search_text : NULL,
&config_temp);
reposition();
}
}
else
{
MenuResult mres = pkgi_menu_result();
switch (mres)
{
case MenuResultSearch:
pkgi_dialog_input_text("Search", search_text);
break;
case MenuResultSearchClear:
search_active = 0;
search_text[0] = 0;
configure_db(db.get(), NULL, &config);
break;
case MenuResultCancel:
if (config_temp.sort != config.sort ||
config_temp.order != config.order ||
config_temp.filter != config.filter)
{
configure_db(
db.get(),
search_active ? search_text : NULL,
&config);
reposition();
}
break;
case MenuResultAccept:
pkgi_menu_get(&config);
pkgi_save_config(config);
break;
case MenuResultRefresh:
pkgi_refresh_list();
break;
case MenuResultShowGames:
pkgi_set_mode(ModeGames);
break;
case MenuResultShowDlcs:
pkgi_set_mode(ModeDlcs);
break;
case MenuResultShowDemos:
pkgi_set_mode(ModeDemos);
break;
case MenuResultShowThemes:
pkgi_set_mode(ModeThemes);
break;
case MenuResultShowPsmGames:
pkgi_set_mode(ModePsmGames);
break;
case MenuResultShowPsxGames:
pkgi_set_mode(ModePsxGames);
break;
case MenuResultShowPspGames:
pkgi_set_mode(ModePspGames);
break;
case MenuResultShowPspDlcs:
pkgi_set_mode(ModePspDlcs);
break;
}
}
}
ImGui::EndFrame();
ImGui::Render();
pkgi_imgui_render(ImGui::GetDrawData());
pkgi_swap();
}
}
catch (const std::exception& e)
{
LOGF("Error in main: {}", e.what());
state = StateError;
pkgi_snprintf(
error_state, sizeof(error_state), "Fatal error: %s", e.what());
pkgi_input input;
while (pkgi_update(&input))
{
pkgi_draw_rect(0, 0, VITA_WIDTH, VITA_HEIGHT, 0);
pkgi_do_error();
pkgi_swap();
}
pkgi_end();
}
LOG("finished");
pkgi_end();
}
|
bf3f188a868a1d5f57928bd607197eae025bca8b
|
9f520bcbde8a70e14d5870fd9a88c0989a8fcd61
|
/pitzDaily/789/alphak
|
1d8249ee7b59e90cbb3be32a8a0506f84b057488
|
[] |
no_license
|
asAmrita/adjoinShapOptimization
|
6d47c89fb14d090941da706bd7c39004f515cfea
|
079cbec87529be37f81cca3ea8b28c50b9ceb8c5
|
refs/heads/master
| 2020-08-06T21:32:45.429939
| 2019-10-06T09:58:20
| 2019-10-06T09:58:20
| 213,144,901
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 68,779
|
alphak
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1806 |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "789";
object alphak;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 -1 0 0 0 0];
internalField nonuniform List<scalar>
6400
(
0.902764814852
1.4614917665
2.32975665171
2.93749786342
3.51679572594
4.09144001531
4.79671286059
5.58229833538
6.09143332654
6.845704835
8.14718751814
9.10819435556
9.92981956014
10.8356983655
11.9250034596
13.0725151095
14.1260859795
15.1204199456
15.9640975698
16.5026214382
16.8431024775
17.3368748354
18.1785862022
19.3363548808
20.5895209045
21.7357344018
22.7155532069
23.6345688101
24.5893915851
25.5953498174
26.5971878723
27.4131284586
27.966368844
28.3688624071
28.6679553123
28.8746445447
29.2455830314
29.8129104589
30.0897971346
30.1627983187
30.5828380624
31.4677414312
32.3430049062
32.8572488983
33.0473241668
33.0079883692
32.8042305397
32.4769171471
32.0390410272
31.5098482821
30.8139960142
29.7507412917
28.3108507159
26.5787358851
24.9656248781
23.4869953023
21.5431434155
18.9217016667
16.1839755533
13.813273037
11.4180238145
8.91461184191
6.6112215438
6.26235742297
9.17168293588
13.6798504625
16.4455208302
15.9919698016
13.8836785361
12.221492891
11.3646755585
11.6450893361
12.2949174651
12.2503576065
14.4450588448
13.9329265871
15.8972326695
9.7931395863
12.8541608948
4.80038134911
3.17190477824
2.56169065572
3.2062118573
4.48798320088
4.49451944719
4.50042302906
4.79990282525
5.32009424509
6.04486920907
6.95805299552
8.04516725064
9.13220441001
10.105431038
11.0415828122
12.0014476314
13.0921039779
14.2414387079
15.3365391964
16.4269980838
16.8050856042
16.9748905227
17.4522128653
18.2787841015
19.4277031109
20.7886997992
21.8855291993
22.8391266682
23.7917106198
24.7592646882
25.7369103785
26.7134163773
27.6065304132
28.1535886181
28.5486291993
28.8754607605
29.0106831428
29.4211364537
30.0132700578
30.2539246887
30.2127379307
30.6075823381
31.929510845
33.0498394022
33.4815769759
33.6197907702
33.5180942771
33.2366459963
32.8556549839
32.2855794895
31.6161611446
30.9758916006
30.3404890848
29.0613459017
26.8015123285
25.2821470185
23.6231719768
21.2275515807
18.6673636453
16.1230290257
13.5933273088
11.2084171433
9.20470170838
6.99229871853
6.77985636129
9.45672381673
14.7601854227
18.2670658467
16.8228644632
14.5413688777
12.5560925017
11.8776020952
12.3754401098
13.5958333297
13.0692654721
13.002111769
12.5507053928
11.421307843
9.62994660033
8.12697031077
4.20760004653
3.30894738226
2.94158314209
3.46901895537
3.82365577718
4.45311805798
4.95145717546
4.98383451078
5.21121930344
5.94072674502
6.93047197532
8.02882977082
9.13525657017
10.1516466355
11.0884071691
11.9039525779
12.9000122238
15.437422938
17.4434168444
17.9984876775
17.6505192164
16.7809366693
17.1585419975
18.386686332
19.5830575521
20.727653434
21.8802736019
22.9275833607
23.882210101
24.8300798209
25.8015035854
26.7487066729
27.720599585
28.2596564051
28.4551987144
29.0464287166
29.20074569
29.3508110115
30.0976498354
30.3919871324
30.4183322273
30.8278952751
31.6887829727
32.5370965713
33.0517478896
33.266790056
33.2680461431
33.0977700274
32.7757698283
32.305241891
31.7059446713
30.9751489178
30.0000550899
28.6566477205
27.1690880934
25.6210982265
23.5495347773
21.1488629562
18.6481972049
16.1273311182
13.6603880978
11.3474242712
9.13188795756
7.58431133195
8.18729398603
11.8534128624
15.8195715879
17.7222168147
17.6626961083
15.9907788544
14.2917666115
13.6258003124
13.5766798413
12.9475641607
12.4054782935
12.4670523386
12.2138430399
11.3065882954
9.72115394841
7.28672512928
7.49700039962
3.40030132465
5.5865194892
3.85955510477
4.03213095173
4.76574452052
11.9591357736
10.3890130787
5.7136973642
5.89799942756
6.91865941392
8.0480978341
9.17629898902
10.167650281
11.1065865921
12.7784759083
14.8449955426
16.5708679585
17.1765745106
16.4981554096
16.0853648386
16.6114212763
17.3909559788
18.3834645538
19.571369234
20.8034827777
21.9835636455
23.0549990313
23.992335951
24.9537229345
25.8650348062
26.9151247589
27.7163283756
28.4900139609
28.6660138566
28.6748920678
29.2659565721
29.504899416
29.7688326295
30.2133943532
30.6208725757
31.1323436752
31.8576184048
32.5883992208
33.0987103311
33.3516320436
33.3883166643
33.2449644082
32.9429400082
32.4911900615
31.8954001322
31.136683711
30.1511382133
28.8952796021
27.4236469026
25.6998714482
23.6001926905
21.2034199368
18.696930001
16.1993619138
13.8066769185
11.6348759442
9.89508621852
9.18192622499
9.78894815033
11.7315625802
16.3163792271
19.4639872813
19.4623571313
17.7047640637
15.2904442357
13.6621732755
12.8833366922
13.1028048956
14.6069946391
14.609494463
13.3440328379
13.2659759987
16.6148081495
12.9890484256
10.9837840667
5.83299039159
7.68574296897
4.72034480852
5.04203181989
6.77722469897
11.8587218301
8.48027029109
6.2564097669
6.42649648526
7.13437684163
8.18445490364
9.32354337724
10.7689162684
12.9684207487
14.0570822557
14.6012435768
14.8831541997
15.0282603209
15.4050542335
16.1253202458
16.732335923
17.4483736972
18.4740874461
19.6646055572
20.906729305
22.1114935079
23.1602657481
24.1998359371
25.0551355733
26.110765837
26.9554121773
28.220440646
28.432822961
28.3677948465
28.7424639153
28.8981396991
29.3124532863
29.8396455708
30.3623135057
30.8557766776
31.4007073897
32.0533299203
32.7041500647
33.1993678553
33.4774958821
33.546115676
33.4302892155
33.1511642065
32.7197993098
32.1353246586
31.3758533128
30.4001424984
29.179387695
27.7028283484
25.9092684018
23.7539505707
21.3466903398
18.8668948184
16.4567937988
14.2541581878
12.4445871256
11.3121513059
11.1486301714
11.2791788468
12.3439658656
16.094710793
19.663175712
20.8323122175
19.5590366706
16.7278172708
14.1896640054
13.8466172017
16.1656348515
17.0781377507
16.0813459701
15.2102943387
17.9389967133
20.9952380519
16.2617411028
15.3706392431
10.10887448
9.29691903758
5.88698002035
6.37880588545
12.1502569205
11.6545264986
7.06342420436
6.89202505744
7.07574358911
7.49023073121
8.41148820075
10.9504831566
14.0544059284
14.5951845893
14.4142364293
13.8153722515
13.8082081445
14.4276729603
15.4841172418
16.0824804608
16.6443678959
17.518223105
18.6077478538
19.8212684604
21.0012431969
22.2118981773
23.4653397296
24.2981896581
25.4808307519
26.1645497012
27.6261942947
28.0438421294
28.9227119077
28.5334597429
28.2842769862
28.6881540167
29.3335735416
29.9759071225
30.559418215
31.1032381286
31.6683228986
32.2834870753
32.8829204033
33.3612395791
33.6541010217
33.7492371831
33.6603257028
33.4068370379
33.0007490989
32.4385387332
31.6980572729
30.74425695
29.5403534581
28.0434259397
26.2018421863
24.0291919671
21.662004398
19.2839776286
17.0609491324
15.1688153677
13.8056440665
13.2100785821
13.4058047181
12.6788301194
14.3823675632
18.2229787073
21.1512465879
22.2171560571
21.1522922874
17.6981507222
15.4150834253
17.1779986181
19.3862026544
18.8700301496
17.9069089351
18.020759651
22.6853778687
24.3079588682
19.251959118
19.0562404985
12.2528613177
9.25965346974
7.15052812323
6.70301731701
12.1341054982
8.73421341569
7.37935223078
7.51978093249
7.6848084326
8.40899027043
8.98309164809
13.6709168447
14.4667157957
14.6159898165
13.5460256428
12.9227940896
13.4572427678
14.8351515222
15.4225761576
15.8164596225
16.6510009673
17.6207313492
18.7136417022
19.923647506
21.2545680284
22.5276441693
23.4873210259
24.9562569934
25.5749193331
27.1240028736
27.4189252287
28.5530081205
28.4816651978
28.3356118006
28.161560352
28.667228856
29.4294142048
30.1495422007
30.7786945227
31.360347293
31.9454787057
32.5457560563
33.1160866633
33.5816607237
33.8840701743
34.001203834
33.9391540917
33.7157083919
33.3427887525
32.81494534
32.1078691994
31.1831273173
29.9927804533
28.4855716651
26.6363159496
24.5061592468
22.2552530716
20.070879572
18.1129644574
16.5268932543
15.4853007338
15.0354748764
14.704255201
14.6767808321
16.3605674478
21.0780459844
22.788631221
22.7498686433
21.4799475081
19.0854963507
18.67086724
21.1225261414
21.4975415096
20.658316017
20.0909936931
22.1419175955
24.9728343214
26.4934140816
21.8664883893
20.7237165138
12.0252687703
9.03114909079
8.33171076607
12.3653019531
12.2978294482
7.94901707592
8.06871993334
8.24471415964
8.34302901614
8.94923592861
13.381696645
14.3611823102
14.556967386
14.2249494271
12.5301596543
12.5742368152
14.1496343108
14.9364222797
15.0946787963
15.6918311482
16.6764522857
17.7687729882
18.8962267128
20.15347304
21.3432613395
22.82258869
23.5549458894
24.9721863952
26.5900480039
27.2643159822
27.1642715493
28.1073713913
28.5134632429
27.9301652063
28.1721741113
28.8176831795
29.5883887904
30.3384122374
31.0112884775
31.6313298979
32.2395178827
32.8409398634
33.3992909694
33.858330113
34.1686021127
34.3057026441
34.2722666165
34.084886212
33.7545300461
33.2732942876
32.6129393169
31.7285535156
30.5656154695
29.0811435393
27.2855540332
25.2796131013
23.2299934352
21.285176635
19.536596728
18.1000712719
17.1567376902
16.7147891572
16.6051619217
16.8956532195
16.9258941433
21.7408073076
24.9026575457
24.4762868929
23.6031131848
22.4293877748
22.9903776368
24.1513517445
23.3538628613
22.6388613644
22.8791910134
25.3302959163
26.0922360251
26.7500800263
23.8640869665
21.7163132506
11.3811747667
9.0556821152
9.01720239591
13.3758269142
11.4052380587
8.65814490162
8.81888497977
9.12829507345
10.2162712845
9.10343321966
14.1503402681
14.9111165651
14.6184232979
13.1271332941
12.2543227175
12.7058647009
14.2030610274
14.6846112923
14.9907218776
15.7009170906
16.6689116959
17.8244467828
19.0418919612
20.657450162
22.028891722
22.7938621468
24.7033557589
24.9061152578
26.7328349733
26.8479017676
28.075655304
27.5761729161
27.601770973
27.8693996606
28.3476258555
29.0210382816
29.7814537512
30.544989485
31.257790468
31.9203823283
32.5572069815
33.1702596998
33.7296738916
34.1897746819
34.5091104447
34.6668118802
34.6660439062
34.5223110652
34.2447516411
33.8231239232
33.225302793
32.4013175984
31.2977013883
29.8917634329
28.2315669685
26.4394456408
24.6423677441
22.8760594081
21.1568489157
19.7268334009
18.9325927872
18.8096682762
19.0095759123
19.1443524463
18.9892266179
19.7936572613
25.4936169533
26.7319160529
26.3006022465
26.5154661298
27.173085348
26.5085209881
25.2884868017
25.0055909787
26.0665809942
27.4141855618
27.3929634519
26.8742442967
25.901583326
24.5503352634
10.9535763097
9.57283253508
10.1668463963
13.4809429379
9.65982548532
9.68773316903
9.57476806131
9.85977366113
12.754314044
11.5751566595
14.9849023833
15.2100803005
14.7309058282
12.5556727824
12.3223070061
13.8623179764
14.4110189813
14.4622341597
14.9511668718
15.8294701345
16.7838018185
17.8842653231
18.9623726296
20.780992728
22.9196304844
22.7450068968
24.6427572151
26.0658677631
26.9426336573
27.7713115048
27.5051958423
27.7508233219
27.3665357069
27.8024420804
28.5149343913
29.2468064841
30.002810112
30.7721381206
31.5185048092
32.2272631211
32.9019319858
33.536732813
34.1067888358
34.5753231323
34.9081863953
35.0897698891
35.1271039405
35.035909755
34.8227210088
34.4753692093
33.9604946451
33.227972402
32.2340558992
30.9838673904
29.5551730365
28.0508596153
26.4727904202
24.6876276589
22.8447905659
21.5785474483
21.2816192173
21.661507314
22.0276278695
21.9991588417
21.5474062516
20.1504649564
19.4654815241
28.7766736639
31.1348647389
31.5722074747
30.8685216828
28.9400097384
27.6214743202
27.7251346685
28.9940632024
29.5550578976
29.5338349375
29.4086753537
29.8530223899
30.0956246457
11.0447576705
10.475105529
13.4827112498
13.7305515264
9.8867496827
10.4782403607
10.3308947877
10.7675748053
12.3802918465
14.9583687649
15.8605701725
15.527726642
15.0291872811
12.6582928448
12.4951438922
14.3405434581
14.5314620061
14.452142555
14.966197437
15.9408344178
17.1012914575
18.2252700176
19.1148198202
20.410844333
23.064818853
24.3777092903
24.3426034451
26.1529196177
26.0265142395
27.7724229694
28.3462227491
27.7299328222
27.3577314658
27.9105320053
28.7083956951
29.4818351993
30.2478408236
31.0247887335
31.7963396414
32.5507809134
33.2735115103
33.9417549878
34.5317274877
35.0158806028
35.3684084242
35.5805423863
35.6637882412
35.6343376127
35.4972667192
35.2408139696
34.8346778968
34.2361096762
33.4206779182
32.4230984519
31.3226155788
30.1179623581
28.5912557117
26.6056799869
24.8344000647
24.1920651159
24.7650755652
25.6836789885
26.1306352687
25.91216657
25.0240518557
23.2589634097
20.7944506909
20.7690496476
32.8429795329
37.4219515562
35.4746069997
32.2267352166
30.6094335594
30.6789218779
31.6201145027
32.3947925421
33.1547832369
33.9777131382
34.7335684513
35.4873411796
11.4942722734
11.393497062
15.1531265674
14.5286782185
12.7556267519
11.7352730306
11.3200848429
12.2081971712
11.9679693967
15.9351222893
16.5659660173
15.9273385417
15.2025321356
13.3488123248
13.2519005685
14.7820324659
14.5831213553
14.5488473597
15.0710973568
15.966419143
17.2170116857
18.6632090012
20.3859105698
20.5052895919
22.5714513362
24.7119726598
24.2665392625
26.3584444443
27.4078054816
27.1073582385
27.5943882458
27.2696650981
27.6257740063
28.2167421356
28.9567162674
29.7377730525
30.5198666002
31.3101571697
32.0984843234
32.8885329179
33.6670159861
34.3864573848
35.0073566304
35.5133088217
35.8931828518
36.145663812
36.2848955902
36.3267531644
36.276853715
36.1280371175
35.8596019117
35.4480203764
34.8989290642
34.2619327893
33.5444960945
32.5141756858
30.881616165
28.9615324796
27.6813513055
28.1780630193
30.2904538021
31.8149634534
32.3517894574
32.0706566269
31.0187763868
28.9049654556
25.6616130042
21.1542512101
28.4681994922
38.664495836
40.8772844932
36.9007936896
34.6762452913
34.2299283579
34.9898046086
36.1231359531
37.9374770576
39.2304652964
39.3748189041
39.7112474483
12.1579856548
12.0807643873
14.9588638086
15.0830941736
15.1277544306
12.9340510501
12.4373024069
14.9821875715
12.4268246423
16.8031590338
17.1059729435
16.3343150837
15.367927408
14.0171885939
15.6753455891
15.8161872371
14.8160014575
14.7840464196
15.3113380602
16.0866641234
17.1563123382
18.6477231729
21.5580611217
22.5523945761
22.099090168
24.7339844546
25.8304488227
25.9524149447
27.3509360992
27.9953284152
27.8749829967
27.3135056776
27.8195739647
28.530344945
29.2592323269
30.027310165
30.8118677555
31.6262989989
32.4463159343
33.2593261146
34.0790414726
34.8596611007
35.5321674692
36.0718770472
36.4873321161
36.7918847489
36.9996701671
37.122461381
37.1678191204
37.1393674243
37.0373514381
36.8746445464
36.6924592447
36.5058480453
36.1109270489
35.0276104559
33.7963028736
33.2030092147
32.1889332872
33.9718078638
34.966184958
34.4370348468
32.7574945776
30.8294852091
27.702469318
23.9134119306
20.4387294985
12.5914777462
12.0467261342
30.1871821314
38.0570491474
36.870251145
32.7666776912
31.4928056081
33.9245565651
38.9385531371
43.0259125964
44.7115368245
44.9177481767
45.2222471524
12.8748742775
12.8192673102
12.4688695373
15.4527037162
15.7124776794
13.7681026889
13.436266975
16.0172024844
13.14860436
17.7101098623
17.5990296543
16.7546991253
15.6315601282
14.3744477909
16.8149912142
16.4540467681
15.307252444
15.2018021904
15.6617082288
16.377008376
17.2173859325
18.5102702211
22.0139609508
23.6062014983
22.4274112407
24.7055374102
26.3072759593
25.5466292597
26.9557728994
27.6118237819
27.154971122
27.6385400859
28.238327106
28.8950270408
29.5941935571
30.3653919086
31.1538274563
31.959308047
32.8137983402
33.6782269898
34.5347159141
35.3636035291
36.0959485423
36.6882839813
37.1553489776
37.5273577071
37.817656141
38.0282426718
38.1714055817
38.2689824057
38.3542923089
38.5057531981
38.7906237131
39.0827596886
38.7322654318
37.5785945808
38.0877151733
32.2987927091
26.5052414373
18.3580203979
0.000428613851217
8.70418185358e-08
3.01471232016e-10
3.07584429357e-11
2.44086458153e-12
6.87542306364e-13
8.09289026576e-12
8.26893545754e-11
9.34063578094e-10
2.43968783671e-09
4.05129180744e-06
0.00106344427469
0.970409702969
35.4032141626
42.7527833063
42.2863201089
45.0880525995
49.4675205243
51.6863093203
52.0689664172
13.7694837381
13.867851082
16.1067819251
16.1437547583
16.216026916
14.4811903998
14.5022383885
16.9207826878
14.2013474133
18.5091195145
18.0772537714
17.2010586704
15.9767947488
14.795823877
17.1281909167
16.7229924591
15.7909463356
15.6826825934
16.0585961498
16.6946697441
17.4547643073
18.4904723434
21.4761610269
24.3952635427
24.632384233
24.1332999651
26.4864290837
27.4581080848
26.0366981647
26.348953396
27.0897259864
27.8598622645
28.5840647594
29.2730930997
29.9833072963
30.7331806886
31.5293734185
32.357041213
33.2108076854
34.1190751814
35.0368320726
35.9162187746
36.7018505531
37.3550348509
37.8953535691
38.3570061689
38.7466711706
39.0546348911
39.2875311376
39.4913804957
39.7759342389
40.3021182783
41.1207411002
41.7680891919
40.9816942126
37.8614035459
24.9608844551
1.02232456912e-13
1.12445101085e-16
2.10794367029e-18
3.57310897555e-20
1.03378907985e-22
2.93780290156e-25
5.08528121769e-30
3.97772205616e-30
9.65699445903e-30
6.50957777768e-29
3.04904988764e-28
1.12632055048e-27
7.15759108234e-27
5.60423403833e-27
4.8619777248e-25
2.76727771181e-22
2.78170458817e-20
2.1108438813e-18
4.86076339358e-16
8.18219436055e-12
47.7476114371
56.56016525
55.2001857351
14.6138639555
14.8079112987
17.7425626857
16.8744503793
16.416363532
15.1915381052
15.5290948306
17.7023953572
17.6803366934
19.5065671091
18.6261110751
17.7445384805
16.4119867001
15.3564894873
17.4605867804
16.9206603397
16.2443114966
16.1676633217
16.4660901455
17.0144954997
17.7314458624
18.6960625057
20.9950957342
24.6319180183
25.9505564195
23.9361118588
25.966662146
27.5390921188
27.5928228762
26.7170245877
27.142980233
28.0570698238
28.9239271976
29.6881544083
30.3732587157
31.1315337015
31.9301119754
32.7827083767
33.6643116467
34.5970898158
35.5738505959
36.5213767138
37.3584193094
38.0626301531
38.6903260674
39.2931118444
39.8282436441
40.2236701438
40.4792898277
40.7586032604
41.2722519335
42.1935722437
43.568801488
44.3412583562
34.8684947198
10.7035708304
5.65335950655e-20
2.28933777773e-22
6.6203942594e-24
9.63808047013e-26
7.83073670997e-29
1.30663346322e-31
9.21051924794e-33
0
0
0
0
0
0
0
0
1.28102615571e-36
4.32063602034e-34
6.4627505489e-32
3.74948090462e-29
5.23710463784e-26
2.83602601163e-21
4.30684786286e-17
3.35778356116e-10
61.7843020991
15.3026670756
15.5184307236
19.8519000118
17.4496925424
16.3796936733
15.8154235368
16.2720679728
17.8323189968
19.2633630674
20.6434703691
19.329593009
18.4239272121
17.0964114735
16.1999372368
17.997961469
17.2651100197
16.7687251958
16.6960482667
16.9111640532
17.3709132
18.0123122956
18.9038986543
20.7909270365
24.4879815928
26.9139780104
26.2856722698
25.4611027232
26.8911331416
27.3971672693
26.7997818365
27.5536933411
28.4843347154
29.3968443409
30.151635441
30.860168967
31.5692096665
32.3812631845
33.2401647271
34.1568482396
35.1252624439
36.1438634622
37.1636086238
38.0883882178
38.8466368074
39.5597459881
40.3274932373
41.0371926564
41.503804317
41.750301363
42.0814243468
42.8051307823
44.0605413236
45.6964978264
34.7548169704
3.03383118575
8.18476861363e-23
2.68424773359e-26
1.08539892284e-27
1.47990875719e-29
4.05831200873e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
1.65060205531e-35
1.6402321091e-34
3.59574417033e-33
1.74352662614e-31
9.68220342993e-28
8.05911377411e-19
1.55352426466e-23
15.8346010669
16.0418350197
21.8718799853
17.8913276514
16.5667781778
16.3855604326
17.0728262693
17.3034287594
20.200959209
21.4572749675
20.0049160705
19.1147544404
17.9697224135
18.0208442164
18.7497902481
17.848507761
17.4845909234
17.4139068884
17.4633656054
17.8124871791
18.3451534463
19.1538676059
20.7657368922
24.3157102669
27.3013173264
27.8887404372
25.3999661063
25.9317662843
26.3150375207
26.88519608
27.8399690269
28.934563928
29.8612192062
30.6618644761
31.3963645274
32.1618321885
32.898323497
33.7603775281
34.6934173466
35.6829391493
36.7757183958
37.8815342663
38.8812442094
39.6479695802
40.3939035928
41.6687016888
43.2328544957
43.8825995842
43.4322283223
43.6078272062
44.4447810081
45.7792820191
34.0505920049
4.33123316291e-17
6.52773574577e-22
2.92844489e-33
2.95922983958e-30
4.8286475857e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2.55012842662e-34
1.72690485013e-33
3.18455571969e-31
97.842423383
16.284510444
16.4581060633
21.7378757601
17.4104410798
16.8091606429
16.8742374014
17.9755571618
17.3655297783
20.9994737574
22.2071027553
20.63860042
19.7493113485
18.6511144103
20.1625044081
19.7794850921
18.6307628298
18.3066336948
18.4664142921
18.2351722361
18.4216166005
18.7761313587
19.4511123438
20.8780624897
24.1323587505
27.1490935138
28.9539397813
27.87121532
27.1264402096
27.090919451
27.0849143367
28.0930404797
29.4925622239
30.3026701404
31.1841172667
32.1317419584
32.7646691219
33.5037407397
34.377213368
35.3357050227
36.3435527089
37.4226829654
38.5978593259
39.7363619705
40.8212499752
42.0102618319
43.6127527611
45.0142027208
45.3564058679
45.4819932634
45.9155887982
46.7671050912
37.5237482068
1.96967584138e-16
1.7979207124e-21
2.36304759235e-25
3.20947156022e-27
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7.84670405861e-34
5.71125196989e-23
16.7874848672
16.9367731541
21.405718472
17.1379182836
17.1173105422
17.2697839522
18.75202072
17.8548649117
21.7047586328
22.9412266642
21.2610776809
20.3739344093
19.2147785272
20.9367055746
20.7284611086
19.4724890138
19.1132397987
19.3682152811
19.1541682508
19.2466283479
19.4007084371
19.8072156487
21.1498098812
24.0835353797
26.842671384
29.2350076684
29.0308160478
27.714156106
26.6966414206
27.5374367951
28.5376334601
29.9067667736
31.0555928864
32.075172632
32.9451196856
33.4803884453
34.19407086
35.080706824
36.0630860952
37.1133228677
38.2162769921
39.4769119136
40.8990720083
42.4820883973
43.6740470936
44.4793428127
45.5781712752
46.5402510799
48.0568810509
49.4579826347
42.5715931266
1.79475772698e-15
2.38309562607e-21
4.10952622631e-25
8.42884992008e-28
2.04078670357e-29
6.85022824103e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.31866500777e-34
1.74471424941e-34
17.52275002
17.6714738035
21.1228672792
17.4417211361
17.6723029106
17.7567932426
18.8039092592
18.5768357332
22.2262819526
23.638913445
21.9104450212
21.0388253394
19.8832781109
21.6316824749
21.5736313816
20.3854950675
19.9651763524
20.2397187407
20.0508651256
20.212056317
20.2849052138
20.3184004334
21.6142141322
24.2369288194
26.6823087057
29.2821916617
29.5725208721
28.5114660505
27.220402078
27.7420603032
29.0731550855
30.0892921958
31.1363688455
32.3446363693
33.8333991275
34.4952602273
35.129102452
35.8963290705
36.8472582277
37.9722929968
39.1864558076
40.5793431663
42.5469192533
44.2968557996
44.8941008131
45.5886187132
47.219143689
50.469933473
54.833006035
46.5555483106
5.1276787216e-16
8.5179746555e-23
3.5249371022e-27
1.15571119183e-30
7.25146793718e-33
1.46981378478e-32
2.25708550974e-33
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9.7466400764e-36
4.42566286486e-35
18.6311214955
18.7433094682
21.4483883681
18.3724775965
18.8084419626
18.605745239
19.1472145425
19.8598480759
22.325704971
24.1726495861
22.6153079731
21.7666004124
20.6505089602
22.4215801849
22.4423155902
21.4483591838
20.9860640817
21.2456444572
20.9542533651
21.2682043711
21.4645749854
21.0426250036
22.1617076782
24.5977074675
26.7236406604
29.1271707989
29.805577661
29.1975476534
29.0969260633
28.5691179373
29.4262039079
30.7807652754
32.3655275609
32.928011983
34.1393280538
35.4934556256
36.1869416137
37.0064213338
37.8687518966
38.9208345395
40.2695361671
42.3031246747
44.8229512516
45.9148704949
46.1184376676
47.4965192513
51.742505676
58.8497721155
52.8067730913
22.3302637021
1.29051914021e-24
1.20487558285e-29
8.24415592731e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
20.1773580855
20.0709257347
22.2877926033
20.2147661023
20.714101797
19.8528905692
20.0909090454
21.7068496635
22.5806960667
24.8037583692
23.4261110905
22.5668634818
21.4911966318
23.2470167306
23.3059387836
22.614552828
22.4588826143
22.5525197358
21.9504179675
22.411293983
22.9275784721
22.0606493567
22.6019763229
25.0519433423
26.9747725922
29.0003100185
29.9519039762
29.3751622048
30.2630644629
30.1131445173
30.4277482009
30.5620146722
32.1759025621
34.0639336413
35.0777191051
36.2533922947
37.2443731812
38.1056494926
39.0921805673
40.1679720573
41.8808033865
44.8428193858
47.0772427208
47.7050964946
48.4919747004
51.8336527396
58.9980312682
55.7912478423
31.7791017305
1.1516816385e-26
2.01338258537e-29
9.21902214552e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
21.806998258
21.3142914485
23.1831230081
22.6441850637
22.3920295658
21.2835277557
21.1188929537
22.8247315127
21.9163107543
25.2999488419
24.3249636767
23.4309398146
22.3940904386
24.0788291951
24.1060762393
23.5901575439
24.4577474039
24.1159107661
23.0592848662
23.6563303796
24.240984832
23.3508259145
22.8011446814
25.0494777271
27.1445592203
28.9061447754
29.9956892641
29.4442420891
30.6545859166
31.3755603478
31.7994046816
31.3255723973
32.3513041415
34.0310323203
35.9698586545
37.4512433369
38.5259499832
39.3678737761
40.3417341553
41.7731758802
44.5406202898
47.727517247
49.5407190889
50.5999604153
52.9399555527
57.7977997428
54.3226002156
31.2503795366
3.10100257528e-26
4.48935548011e-29
1.57225889635e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
22.6094506417
22.1695053796
23.7452309607
23.6745872123
23.4331446502
22.6206952774
22.2777915707
24.1646211113
22.946384769
25.92581585
25.2324880347
24.3306777315
23.3535573499
24.9306548487
24.9039140461
24.3985921568
25.4213766485
25.2164841613
24.1158608906
24.8595499917
24.9802986081
24.1637329644
23.7640365842
23.9966840576
26.6035514068
28.3670424215
29.7429698699
29.3698826064
30.6973014557
31.9099185936
32.9275074679
33.0643398077
32.7623872317
34.0848386772
36.1936510078
38.3128344353
39.9204159072
41.0163930775
41.9822068869
44.3315247341
47.8516880238
50.7445168083
52.3956190592
54.3728291366
58.3383648195
55.0380538835
29.1238088278
14.7592701588
1.47570415904e-28
4.20288184356e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
22.6819158478
22.6788618005
24.0665669025
23.8758945555
24.0741023698
23.6426006073
23.2749900969
25.4800113053
24.5793828474
26.7137111565
26.1886929059
25.2508885637
24.3646838178
25.8177610976
25.7590978461
25.3208126966
26.2187207844
26.1645906082
25.200659853
25.8620247357
24.898683764
24.9010892314
24.7632125742
25.014599823
25.8144106483
26.8977424887
28.8309844551
29.0622001743
30.2496045383
31.9005589601
33.3549050746
34.3875840702
34.2496966388
34.8573575018
36.4081465889
38.5235416077
40.8383808317
42.7328010097
44.3587729689
47.6372722941
51.2088270742
53.6504359302
55.029998248
56.9702595556
52.704062258
34.7852209543
37.4031180424
5.12594061238e-28
1.14825864817e-30
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
22.8870619061
23.0140531053
24.3216170237
23.0209011942
24.3274812387
24.1868999616
23.9256770084
26.0739602014
25.402054421
27.4957566962
27.1629619704
26.1584301927
25.4323892519
26.7272900682
26.6473785824
26.3692470061
27.1131492969
27.2217301436
26.4125343145
27.241403781
26.2147163593
26.4643541542
25.9965320544
26.3004084853
27.5315120398
28.1627463235
28.3839261909
28.6691406027
29.7305002133
31.7487852944
33.2659945172
34.5827592298
35.4696851823
35.9174008954
37.6223795302
39.2236691874
41.5746465988
44.3094856239
47.2782869884
51.1880723765
54.4179682102
56.1587112673
55.8971708434
53.0992723697
51.0196805169
31.8321584071
4.30131113134e-27
9.79214526562e-30
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
23.5175915821
23.6094296551
24.5854141887
23.3672288065
24.5360200001
24.4638208254
24.357583818
26.2547752501
25.9500813733
28.05923058
28.0950179551
26.9927699676
26.5411771572
27.6093493139
27.4837323401
27.3759274069
27.9714482366
28.3558036134
27.6708080018
28.6461393037
27.9514060048
28.4448193263
28.3006124698
27.3163448632
28.3182607429
29.2300830451
29.4374255601
28.3777491936
29.1330470889
31.531055157
33.2891843299
34.1982242416
35.2470898639
36.1720008943
37.9697794506
39.8507818315
42.4075664371
45.8891302949
50.3783484236
54.8466630534
57.4158263845
57.7998348156
55.6777650567
50.6373895216
32.2146738532
38.4986627144
6.82355177757e-29
2.7669654164e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
24.3196692108
25.3140487666
24.9819344758
24.234206289
24.9970478354
24.7801631583
24.7539726924
26.3869641128
26.4303757217
28.2735877371
28.9741610187
27.7129252961
27.5040552545
28.3138506631
28.2441767423
28.1230703811
28.3011716303
29.3699513444
28.9709781074
29.8627294218
29.808021113
29.7629333678
29.6828018975
29.3479051603
28.7094536037
29.3901497045
30.2746044994
27.8361501039
28.477166943
30.7398607395
33.1946033097
34.5568370964
35.7112492943
36.0394313074
37.7122530492
39.9870515395
42.8787126194
47.3437417067
53.4820625359
58.3863171261
59.9540864585
56.5084581604
54.6547904093
55.3704038605
37.3379636533
4.62506529251e-28
1.18042790776e-30
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
24.8877680266
25.9261130515
25.578737534
24.989603358
25.5844676445
25.2407933925
25.1943930178
26.5735094028
26.8766267008
28.2137521744
29.7284903578
28.3697068688
28.0587660438
28.8622196185
29.0270879369
28.76564251
28.5394046073
30.0767490157
30.2711857541
30.9080778892
31.087900667
31.3248776559
30.3282157038
30.3605935035
29.9091202678
30.8778710262
31.4832467779
29.250599671
27.8291748588
29.547129291
32.2765234601
34.4898748688
35.8155914365
36.3773726104
37.1603514389
39.5049788584
42.6747718325
48.4101229948
56.4356282835
61.9696904041
61.2923366169
56.6504857936
50.7649681229
30.3432315921
43.6706350056
1.36371954551e-29
4.58287214123e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
25.2437752749
26.1777125004
26.0551406858
25.4627876615
26.1254548169
25.7975394636
25.6807452591
26.8803649701
27.3378453568
27.7801483738
30.2076072083
29.0373348446
28.4129527818
28.8135097839
29.7911191552
29.4964006386
29.0598607977
30.6443731333
30.9892571705
31.747896534
32.0327652473
32.5642681664
32.7788609227
32.8202093355
32.4951025136
32.0240814637
32.8593792393
30.943753859
27.6627036393
28.3815304093
30.2151386988
32.9408372216
35.1823310003
37.0186443583
37.2991237711
38.4127516002
41.345303335
48.336832935
59.1092354443
64.5106335868
61.1994216235
61.4999052462
59.9619980595
36.5824957992
1.9539249165e-28
5.34241028625e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
25.5383066396
26.3634493868
26.3852485541
25.7245484017
26.5493424744
26.4074326637
26.1434697546
27.25181649
27.9440522547
27.2246794285
30.4677465096
29.7682832245
28.9088400999
28.4039425676
30.4422914217
30.2718548332
29.8436104497
31.3477848454
31.5092494137
32.1406683451
32.9806722149
32.6250249647
34.141154986
34.696892943
34.7598831976
34.7112843407
34.8551141297
33.9217708708
29.5534919391
27.7961665337
28.84075469
30.5422593854
33.0779906486
35.1475845027
37.4250283427
37.8786868746
39.319261375
45.2131127913
62.2521697467
66.736264163
57.9830980028
54.5369499997
54.545658454
52.8777403643
6.62931502808e-30
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
25.7718173479
26.481389
26.2439336727
25.8305045768
26.8394531224
26.926172219
26.4784378895
27.1655342327
28.7410364887
28.0122450646
30.6244354857
30.5606291383
29.6254373917
28.9962891654
31.0956419995
31.0496303316
30.8911174473
32.2660940004
32.3107342531
32.1493041984
34.0033295505
33.9018221523
35.1736262089
35.807837095
36.3694639752
36.9862188214
37.4673486835
37.5088696489
35.1114275707
29.4342021094
28.6855229653
29.5329661025
31.749808485
33.2392185465
35.3013876282
37.09636794
37.9526561813
39.2082867927
58.667328434
67.8944605816
64.4595208433
52.9511151502
19.7308133124
37.3937984918
5.45768949615e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
25.9136921851
26.499671844
25.9534899117
26.0539484635
27.10339553
27.1628486334
26.7336130077
26.9167137351
29.0560351547
28.8244201928
30.4205862744
31.349678206
30.372835407
30.0766568257
31.7535624212
31.7707464558
32.0399673869
33.1253385331
33.4060609963
33.2493743908
34.9769100439
35.3532178185
36.3439248675
36.68056775
37.969003186
38.6770356819
39.8636203611
40.94225774
41.4522934403
37.2164800809
31.3052106898
30.8483420246
30.5735258258
32.546391702
33.9651007013
35.2492132566
36.0860072474
35.5734918299
38.5557504552
60.2092328686
70.6898382626
71.8471676186
47.1034243706
1.35731011799e-29
1.66250399987e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
26.0323927281
26.1809126187
26.3956610639
26.9697027778
27.4375130805
27.3826447617
27.050820826
27.1046735746
28.8489366268
29.2718385409
30.0364911482
31.9649527744
30.9970117614
30.8930120767
32.1147840212
32.4066937962
32.5061498946
33.5378670322
34.400830801
34.6191840648
35.8870782858
36.4038629353
37.2697167207
38.3337567196
39.3696203578
39.6002140466
41.4516476967
43.0296820249
44.7446274782
45.8828393428
41.0956128373
34.8024627092
33.0754480597
32.2397873834
32.5425423613
33.1552600116
33.5031717794
32.8523266239
29.6231406249
33.4594381518
51.6946425397
64.6137531323
63.9167626141
1.01437083386e-30
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
26.1302936805
26.233427702
27.7142336277
27.6954989391
27.6261023601
27.5338398434
27.419475875
27.4432380502
28.8084283202
29.7360589246
29.2916668548
32.0754098191
31.5689080701
31.0783291173
31.6894348968
32.9846209373
32.7718380173
32.9106257162
35.0080672344
35.2605280291
36.3865872496
37.4625947704
37.3778988823
39.6767924466
40.6376644855
41.8864072485
43.1422525142
44.626735028
46.6344550361
48.8528537932
50.2490213196
46.4410523752
41.5494792393
37.8091397073
36.277927189
35.7717744145
36.2380030175
36.3992660255
33.9972325186
30.3809021375
2.86163426801
26.5452228073
49.4139212243
1.28239459609e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3.89019676652e-36
26.0770387056
26.3013999072
26.561030686
27.437231605
27.4859038387
27.5417104831
27.7230611351
27.6254953588
28.7958008985
30.0484081308
29.5267221732
31.6018667592
32.2764979342
31.3578783798
31.0216438975
33.3873128933
33.2990547189
33.3252589347
35.3740704164
35.7773081496
36.0426831283
38.5255012058
38.7511605455
40.4669616543
41.4488579779
43.4570175203
44.587513641
46.1347319142
48.1565691051
50.3966660109
52.699207358
55.2066464807
54.1010117612
51.5763764721
49.8049173858
49.2524169006
49.5456681628
50.5828349024
52.5947537172
58.3706650314
51.0741343708
2.52637563714e-05
4.1317050195e-30
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9.7466400764e-36
25.8989940544
26.1589185666
26.0620750847
27.0551874999
27.4818214304
27.5414185387
27.7701158333
27.5641212879
28.2110155274
29.9443564829
29.8400109771
30.707857681
32.9046555951
31.922690951
31.7493509668
33.4950780169
33.9648563512
34.0937302672
35.527540837
36.5943006245
36.9545186633
39.0553682352
39.8308360317
41.0802513244
42.7548152513
44.2023291483
45.8462365676
47.6823939853
49.458264299
51.8726617957
53.8194593959
57.2083940913
59.6351529405
61.8176009462
61.5465148695
61.7229508979
62.077325965
64.3983012447
69.1708726176
76.914470666
84.7461670336
63.8822532719
5.58318548751e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9.7466400764e-36
9.7466400764e-36
25.7157484411
26.0046018405
26.5313575253
27.5514050145
27.7590173443
27.5432418925
27.5966317554
27.3704822394
27.6634754279
29.3611886494
30.0971251036
29.4277413841
32.3715130848
32.6252052605
32.0521120498
32.7170690828
34.5308149925
34.4306664378
34.8060248788
37.0759631646
37.6026176693
39.2490386641
40.7535510818
40.9822070061
43.535707296
44.3335209674
47.0756994298
48.4551292911
50.188142536
52.7925595511
55.0276691312
57.402978774
59.8306929169
62.4106487874
64.0510716221
64.6894178358
65.4300488835
66.9479506585
69.2345689992
73.239348036
84.7885704889
80.1365866178
7.77087567942e-32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
4.75696814071e-36
9.7466400764e-36
9.7466400764e-36
25.4850902936
25.7438451297
26.97684746
28.1642099947
27.6141672742
27.3375395207
27.3087981554
27.163663255
27.3187951831
28.7725247697
30.0253005186
29.8555278587
31.0307386659
33.3990239931
32.3781686583
32.2736988253
34.6483497686
34.9041388408
35.1335167312
37.2131036291
38.1397030255
38.8066798674
41.356527641
42.0328530021
43.9451786718
45.5712037686
47.3322565326
48.8524631321
50.930331555
52.8557890157
55.0604218011
57.1109841057
59.1790438437
61.373999096
63.1624502621
64.1205434879
63.9858704643
62.656264873
58.9123374431
53.7759793077
50.8391216736
62.1376272934
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5.92213845439e-36
9.7466400764e-36
1.56264974274e-34
1.64888544445e-34
25.1839672221
25.3604796274
26.2103188037
27.0384745401
27.0593615132
26.9033994754
26.8945281254
26.9414004611
26.8855860972
27.7256370554
29.3107658247
30.0344636865
29.4434210135
32.4529364331
33.0120661773
32.4169597005
33.4892600023
35.3454606924
35.4362999251
36.3488044515
38.6440931109
39.1644602124
41.3342780262
42.8889909347
43.2202593414
45.8994072989
47.4971908636
49.5804811099
51.1374856099
52.8847299016
55.4379551518
57.2606924204
59.253766641
61.2111347114
62.4644296369
63.7743193037
63.6080675003
61.9795669436
55.5784432803
56.3509764007
0.000266263353112
6.16004133405e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.21296196273e-34
4.09429208884e-34
6.10222787911e-34
24.8599589587
24.9537124833
25.6557153832
24.6590568612
26.0855459868
26.3290667451
26.3522512647
26.5231172289
26.2299027274
26.7101385962
28.337143686
29.777065885
29.9065045949
30.7784005624
33.3737620714
32.8888258635
32.9207252758
35.3841282342
36.0610482458
36.2018817019
38.7120294442
39.7523085922
40.4217297476
42.6871073462
43.9203742319
45.7521446262
47.9322111426
49.609595448
51.6491015098
53.7009712754
55.7372943847
57.686804287
59.9646148119
62.0990626798
63.881687609
65.1481421633
66.5038746342
67.3530562263
68.0444161397
66.4454768094
0.871971350647
1.82703090434e-31
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5.52238465419e-35
1.97837335093e-34
2.78140254557e-33
1.88607544376e-29
24.3326517589
24.4150940628
25.633092663
24.6926167294
25.2777882154
25.6147576891
25.6893660011
25.8177839473
25.5993276206
25.8589144722
26.9383662866
28.7117140137
30.1166512894
30.1852513832
31.8453978881
33.7089600632
33.0927893149
33.2514470683
36.211568253
36.2404389051
36.8647793558
39.6134947642
40.3536693674
42.3638806441
44.1085293651
45.3983830551
47.7207464477
49.6319717212
51.984412288
53.710760025
56.0456552837
58.918642211
61.6373830348
64.0131179794
66.4013884827
68.8512727903
70.880331669
72.2530375968
77.0862803984
76.4322771783
40.0384890593
4.8708368518e-33
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3.48460433899e-35
1.15832346986e-34
1.11132374471e-32
3.22140041226e-30
1.55552965931e-20
23.4279425123
23.4958391958
24.6496217138
24.9817979162
23.8587435159
24.749559264
24.9719890662
25.1323034543
25.2299304781
25.0946843574
25.6394332938
27.3541623479
29.0389348497
30.1469823909
30.0256881375
32.9484521973
33.8227563273
33.1606186742
35.4374317738
36.5454550612
36.7267375579
39.1265165321
40.5958854044
42.0736553669
43.954609558
45.9225060462
47.5735516098
50.2196891542
51.8619089806
53.7675477584
57.2719058922
60.247201353
63.3260949162
66.2015292915
69.85484727
73.036843209
76.0216633644
77.4987468824
79.9366084959
73.1755239814
16.1387362056
3.34669680746e-34
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.11986822551e-34
1.38677265112e-32
3.1890826787e-30
1.19760445087e-25
2.42822297282e-15
22.50678732
22.5243750707
22.5802773598
24.4579691057
22.9966237332
23.9065302835
24.3450798062
24.5347654699
24.817510354
24.4669245005
24.8500382742
25.3999370683
27.5679342221
29.4040431568
29.7634458459
30.1339773646
32.9867481037
33.4293987821
33.7334311318
36.0581940449
37.0741415648
38.1297755045
40.2988795075
41.9360999528
43.7461302124
45.615415047
47.7905512319
49.8627633048
52.0126843103
54.9913876122
58.1411832969
61.482674208
65.2578787861
69.5362408479
74.4627688919
79.719841162
84.2216595081
89.2451562384
97.1691791295
80.2749949621
0.0144108118531
8.14084586888e-34
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3.48460433899e-35
8.26657153146e-33
1.86175090223e-30
2.75595817375e-26
6.89895578383e-17
2.79909043223
22.0310716211
21.9973351551
21.9555505004
24.328282778
24.7708882165
23.8789114018
23.9373778845
24.0211303365
24.1846573878
24.1144619556
24.0518682733
24.7301648855
25.8906905488
27.8292187638
29.4742950043
29.3524940685
31.0046229417
33.0098858865
33.5396759615
34.1158549674
36.6665859169
38.038075087
39.2408955475
41.5046246511
43.3297845086
45.1184604641
47.4088498347
49.7448987966
53.1328956275
56.3484569789
60.2702880094
64.6320963875
68.7822383406
73.8487320006
79.7996136562
86.0556593256
94.6566526752
99.9999999525
100
100
66.3538649142
8.14084586888e-34
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.73665898719e-33
5.68859320253e-31
2.72019577099e-27
6.56076314554e-20
0.000609319010585
75.8596939491
21.8097244509
21.6662780731
22.1851406685
23.5257578279
24.5816730646
24.1008338307
24.1026139576
23.7709736384
23.6379022449
23.8116582777
23.336314649
23.9135368468
24.1760080526
25.9199579041
27.5920003575
29.1117507712
29.4396666083
31.710322954
33.0369070533
33.8230816793
34.5308969429
37.2872567298
38.9094919945
40.5977509924
42.5964332799
45.127215794
47.4608204526
51.0579511032
54.194381944
58.4041450132
62.0088147022
66.2463899928
71.0085487853
76.7762498787
82.8905215098
90.8408956685
99.9995340352
100
100
100
74.3196780524
2.18556467169e-36
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8.72970117014e-35
8.09503713462e-32
2.11820671745e-28
5.64621429057e-23
2.79826072491e-09
68.5120606594
67.8254381377
21.359565996
20.9408465841
21.7102870105
21.7016900887
23.1585026362
24.6705790962
25.3319723619
23.9593520304
23.1617706765
22.9774104441
22.8930688382
22.3920674159
23.3054164639
23.3179084146
24.9160642933
27.1995975879
28.7629491776
29.349545778
31.629085578
33.1044184631
34.2436563689
35.1737593979
38.0335448075
39.7968024107
41.97280938
44.9186461099
48.1262038398
51.2065166089
54.8055687248
58.1635414555
61.8972329918
66.8677648408
72.7142658933
78.3556013145
84.4841245086
93.571042432
99.9987103864
99.9999999415
100
99.999822187
99.9999895712
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.68556978656e-33
8.89771455349e-30
4.09896515874e-25
2.16488819222e-15
57.9809052039
57.101992575
59.6753113773
20.7849039378
19.7529143803
19.7778906915
19.9653526744
20.5668772839
23.0503971387
25.2456915753
23.6184235623
22.5405352401
21.994093667
21.9307930802
21.3685350929
22.0590902956
22.2463734816
22.9995108875
23.9962526845
27.1574784619
28.6993438387
29.3662106165
31.6425750973
33.2551731233
34.759129384
35.9517631136
38.9201248179
41.6434342891
44.4699482416
47.3989026279
50.4645738227
54.1739900696
57.9268749298
63.5080370627
68.4071800794
73.3630168993
78.5147152203
85.2930034914
92.45775322
98.9886886702
99.9686409853
99.9995470239
99.9985984338
99.9931842065
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.2397192136e-31
3.47921510064e-27
4.16409151626e-20
0.700366126921
53.2879682167
52.3023032756
50.7603937575
20.4906518272
18.4342669646
18.1255051292
18.262650721
18.6974618295
20.293688154
22.5169930222
22.9601277124
21.6726955924
20.9411649649
20.5602052655
20.6344574762
19.7189767546
20.7820914225
20.7839108575
23.176119785
24.3808119716
26.9514257854
28.6249593236
29.5441169326
31.6694958621
33.7259941545
35.7298561976
37.7672233213
41.08114173
44.1836424486
46.6333459578
50.6732464521
54.5496763201
60.0309336042
63.8862863995
68.0423078375
72.9641376345
79.0169044921
86.3496728966
94.4040393473
99.9917854121
99.999999606
99.9999574357
85.0206774258
0.000160873563062
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9.32911906381e-35
1.35966382217e-29
1.35214988221e-23
3.25362849996e-09
52.2525794446
52.1950999759
45.4361727414
43.8423822305
20.4435282887
17.3006303001
16.703361032
16.5399255755
16.8415875688
17.8046063208
19.8882519045
22.0181366919
20.8712359976
19.8236321713
19.1874560631
18.8426736752
18.7708392557
17.8065285938
19.856328317
19.8545935762
22.369887685
23.3895058571
26.4725231719
28.2816542715
30.2223208388
31.3780324338
35.0184787699
37.6128831792
40.5563165785
43.6876361162
47.2201200455
51.2118767964
56.3563605356
59.6153366127
62.8276975562
68.3924177067
74.2592965961
81.0987295649
88.9906334611
97.7029793964
99.9999824644
100
55.0929238134
1.50931190017e-17
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.12852311324e-33
3.02686497215e-27
8.78306345395e-15
53.457111419
53.8473551135
47.5199099444
41.6907811725
39.3599187236
19.2962775344
16.4484184759
15.4219411738
15.1636837795
15.0832019208
15.6445669323
15.9183595756
19.4332437745
20.2670042375
18.7776140653
17.7847005981
17.1219720537
16.7190811553
16.4824190116
17.6096551997
17.963232553
17.7519138626
21.5035581252
23.2431809233
24.8041784861
28.8481395659
31.1051869801
33.7292248519
37.0833244048
40.2112565752
43.4098241746
47.5208294378
52.0847914511
55.2727118657
58.0433657141
63.8160228049
69.2578974333
75.231623169
82.0698959289
89.6420885499
97.8436702715
99.9994647739
99.999998344
5.42781653407e-19
3.01371001742e-18
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.33176325278e-30
7.85276975215e-22
53.1571300975
60.6996373831
51.7162006456
44.4281005253
40.3260351366
39.0210236023
17.6279338067
15.8666327083
14.4138210295
14.0360150737
13.7739416664
13.5771994934
14.7207098864
15.1741391966
18.2279831275
17.6953255799
16.3742581783
15.4198678903
14.4219341447
14.3111568208
13.0164136473
14.7386992299
15.4800899754
18.8076742586
20.852059594
23.6439292992
26.2096341456
30.3449240431
33.3431091253
36.5762775031
39.5069968257
43.7227738857
47.5025883436
51.2020523198
54.0287127182
59.4872983656
64.5259006427
70.0514618412
75.899635953
82.2614526885
88.8971110284
94.731428902
99.5789431268
99.9981247717
7.61685941511e-18
1.34041360833e-12
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2.52927220253e-35
9.92781158601e-28
1.11915134627
65.7244930529
58.236980748
50.4874448117
44.4429701107
41.0436193267
40.2296259861
16.5443800697
14.9124125862
13.6143962666
12.8905164961
12.5966550018
12.0938993649
11.7333160915
13.5205049675
13.2648855965
16.2202826688
15.2434319576
13.8472067219
11.8581480449
10.4688561212
9.65365761209
8.05193262306
13.5698512156
14.465295812
18.4522185146
20.2363782033
25.5722115324
29.5839078069
32.8367093065
35.7726046196
39.2269511282
43.2346848403
47.7666458829
50.7771392371
55.7954328967
60.3373852097
65.516895573
70.2413047362
75.2925590206
80.4804905121
85.2372230045
90.5132582052
97.3807801527
83.8239055967
1.00908005152e-17
1.75832130796e-09
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7.8883834254e-34
1.20040132208e-15
66.8227837536
63.7071862029
56.4713142862
50.3372946162
45.8980506465
43.4702231657
43.1685671558
16.3451083487
13.537798296
12.5997632681
11.6600971103
11.3105051269
10.6677565535
9.46617714201
9.15024121521
10.7324733783
11.0671170752
14.8156793721
13.1830424736
9.3938407888
6.11335492758
3.04494314927
4.21221637303
4.59983631819
12.8561609202
14.6365774335
20.5838772163
24.2142127354
28.9565688249
32.2481885557
35.424362324
39.3173765552
43.8450075885
47.679068508
52.4910470003
56.6393122463
61.3128818184
65.5501282606
70.1966506113
74.4478824546
78.3611490693
81.824910401
86.8106794375
88.8211969202
42.1462849415
3.68776250797e-17
5.19584890783e-06
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3.34971082039e-29
59.8584690088
68.1761403876
61.6124080193
55.8184837404
51.2170735889
48.0491413756
46.2959609866
45.1168559806
16.743069217
12.1829377478
10.9169415171
10.2962157034
9.85546671299
9.31207827123
7.96647727714
4.78213013912
7.63972907031
7.47501292152
9.59990033066
12.331582456
1.37892076159
1.49604525983
0.64212994191
1.01711209658
3.54545364175
7.68401585952
15.7269216106
19.0328178833
24.3529366991
28.2247486936
32.0235253791
36.1209780108
39.9372178968
44.2003578915
49.1228077313
53.2309907746
57.7364822542
61.7250958494
66.3550813756
69.8758901174
73.0244134445
76.1951537334
79.5807822831
82.9067842072
79.7725833974
23.8487217711
6.25549002084e-16
76.9918392411
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5.57235065563e-35
45.7251577662
73.5673266237
67.7061721716
61.3111008585
56.7247588412
53.3617089572
50.9692495101
49.7329861463
48.9129945042
15.9428525177
10.9608177589
7.83988142977
8.05581842414
8.28392625362
8.08702610187
7.04882549588
2.95441427003
0.298335555584
3.36776992587
3.22309322429
11.0873614014
5.99173774068
0.111476877934
0.25313551711
0.459180653591
2.69873024929
10.4794076159
14.4264780407
20.2669704361
24.020604874
28.7609383448
32.9295655184
36.9148874329
40.8818170876
45.4613386995
49.5322059271
54.4536024858
58.30247166
62.673296292
66.1866499579
69.8082455464
72.5397000185
75.9824020118
78.4249915502
78.1118693875
79.5599806486
56.2669781803
9.32201410994e-15
99.9999989888
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
4.00331903657e-11
73.967526902
72.1196085709
66.9584798545
62.2354714454
58.9555157742
57.3791421047
56.0874018597
54.8880194764
54.6254420816
14.009020805
3.71817764504
0.869793253615
4.92076816087
6.79516498757
7.35860000327
6.78855290241
4.18808332508
0.0157006209476
5.27134951738
3.61671990882
1.93159809961
0.00484484988164
3.75117021453
0.128018313469
0.452586898705
7.41849743903
11.4981885059
16.4925789654
20.1677796195
24.9591541444
28.8240130845
33.6008935325
37.8515862264
41.5979540598
46.0553974865
50.9535888193
55.0587030271
59.4410532181
63.0976029064
67.345894076
70.2352497215
73.4519716011
77.4819662145
77.9542868744
79.1254143681
83.6190888509
74.7726692281
2.01879584217e-14
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3.80871197017e-34
67.9783234623
71.2673509114
70.4475324527
67.1031147738
64.2416403118
62.4995688679
62.1880951863
63.2176665097
61.2558565166
62.6822649411
12.1292622249
0.0244413372617
0.00989961928955
3.13546979812
6.42039881329
7.31149088694
7.101916815
5.70314353747
0.014084611482
0.00182929980072
0.0261402971564
0.0102903810202
0.00427928790018
0.0141186387672
0.0387078845317
6.80872335941
10.7227214399
13.3367783923
18.1596170831
21.8001710935
25.1764640993
30.0569947569
34.797041858
38.7639757802
42.6992401303
47.2697007011
51.411940649
56.2837941412
59.9792465011
64.1561637198
67.9005813514
72.2116065332
76.4111994632
78.3995889301
79.0189021854
79.8946497141
81.0517585982
82.1141129684
5.46757862531e-14
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
53.4624231456
75.032550718
73.1345370858
71.044093573
68.5589521591
66.7687191374
65.7985838026
65.4836823164
67.2963190149
66.2944059578
65.7364920403
10.2486459482
0.00781013629046
0.00130812627318
4.47758820936
7.31813083164
7.95422513916
7.55770361104
6.37204256551
1.55855623553
0.000840565505603
0.00037274223297
0.00155164515863
0.0140872557252
0.00618949261674
0.571019724141
8.41575490263
13.100150407
16.8864000184
21.0262285424
22.7921004329
26.7937950428
31.0642301071
35.5980171349
39.5933671191
43.2766956372
47.7414338228
52.6465581545
56.6055657493
60.9675019129
65.0974175653
71.0908186284
75.499969092
79.2416603111
81.0083608719
81.3911759169
78.5117541664
79.0635527949
83.9322503538
9.44882652229e-14
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2.40461388292e-28
80.5086267567
75.979381092
74.1241339435
72.2434609165
70.402168684
69.1073250411
68.290109569
67.7629614093
68.5462754987
68.2928521904
66.9683614093
6.94821255245
0.000625796067462
0.000234771361902
7.1405103211
8.90112643634
8.95026636839
8.23299594899
6.82584513557
4.04533037329
0.000348725972732
0.000155104000802
0.000166850511434
0.000841775053339
8.89302396074
9.57674741818
11.0476437298
14.1695970319
17.8613677729
21.3579765663
24.9189841257
28.9032835547
31.8072413725
36.1967945136
40.1965319483
44.1217169864
48.6792529046
52.9864405885
57.8597073666
61.9713672451
68.842393488
75.409576961
79.422297005
82.7770130392
85.7051818352
84.7639308997
82.6265615709
80.5660050491
81.3069093062
6.68146593647e-14
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
69.5080305587
71.1064173481
75.7699943993
74.7558551413
73.6598921706
72.3302045294
71.2889187435
70.5048068183
69.9143020237
70.3952700408
69.8472197138
68.6764967623
1.81469694239e-05
6.0456307711e-05
0.0504612480522
10.0960160453
10.5656186006
10.0789018244
8.92506694303
7.38390196472
4.86137487193
0.000160424827645
6.72871420962e-05
6.46680279838e-05
0.000210029314295
1.04676848743
10.9415013059
10.5832236841
16.4570507395
18.6037355298
21.9778986332
25.2456023727
29.2582710968
32.9135146024
36.5894988169
40.6736092181
44.7108976808
49.2484960721
54.3137129472
58.6163541709
65.895833067
73.5123195347
78.0919674408
83.3436702844
88.0606169674
91.0580765989
92.600841994
94.5723032391
94.78694741
99.994132949
56.8406097826
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5.06662725672e-13
91.55259131
81.8699959873
78.9877104476
76.8060279548
75.4455288306
74.2220864521
73.2691689725
72.5236819321
71.9581485703
72.114162363
71.362673839
70.9039706536
6.95120928551e-06
1.20228879647e-05
7.26532492255
10.2134545125
10.3583395601
10.0988566781
9.61318494591
8.02489844914
5.56043038325
7.80269569111e-05
3.02861472174e-05
2.88240067077e-05
4.60600758594e-05
4.91770801954
0.00304599965213
14.6074484119
17.443021328
20.0587030743
23.452215475
26.3744967681
29.9110425248
33.1817457215
37.0733391209
41.1105721053
45.4073597624
50.6769085671
55.3319992869
62.1182135889
69.5219327893
75.2861085939
81.1884426923
87.2855265175
94.0382532001
99.794966181
99.9999971703
99.9999999922
100
100
99.9999360182
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
88.8292070981
84.4937331106
83.1308890296
80.0854254474
78.0650658929
76.5544002445
75.3710731227
74.443631348
73.7594137029
73.2962163129
72.8971238502
72.1784215821
72.1163203845
6.47093010321e-06
5.15050538482e-06
6.26623249736
9.82190166877
10.2359941327
9.96013825056
9.2565420959
8.22025173919
6.35427876622
3.68334243109e-05
1.44190277084e-05
1.35544785579e-05
2.54342836138e-05
0.000127318932453
11.2691981129
16.240691738
17.165222163
21.6574028632
24.9503902145
26.9883024734
29.887067246
33.4734386506
37.7297369565
41.5361483746
46.7432852899
51.7618711822
57.4857761478
64.1765428613
71.0098948799
77.4671945509
83.9440175254
92.8568670338
99.9765572534
99.9999999698
100
100
100
100
98.9040554572
1.28583301865e-05
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2.01523879893e-20
85.5360394355
83.8580595054
82.1019739875
80.0296873622
78.2654922252
76.4841628966
75.1872205109
74.1024449096
73.278009113
73.0389532812
72.3629431948
71.5091784252
71.8787470497
8.70804614356e-06
2.61784783288e-06
2.6204266203e-05
10.0185356339
10.4502220922
9.97708594225
9.06578357541
7.70172533756
5.8328450656
7.46012634436e-05
7.89114206275e-06
7.09281935106e-06
1.42967500388e-05
4.50288494147
8.72431091189
13.3041932361
19.5491761688
22.4334413109
23.8514335824
27.8574524065
31.3258625318
33.9849432043
37.3961943306
42.6616878957
48.0474357125
52.4551341374
58.7037721889
65.9952441831
72.6870327187
79.0992146031
88.3828933536
98.6093078786
99.9999984606
99.9999999999
100
100
100
100
2.31313941557e-12
1.18899827127e-13
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
93.5018384142
83.1103307194
83.5810644259
81.2324284492
79.653967031
77.5234047881
75.4911168152
73.8923178085
72.507545731
71.3410944607
70.4049772514
69.9207892659
69.5987230995
70.5876750659
2.51085770911e-05
1.64364603499e-06
1.73556096779e-06
10.5175945725
10.7950644291
10.04810865
8.87451798163
7.21003179323
4.46981238417
8.15391052036e-06
5.1381213112e-06
4.63167829195e-06
7.40009890416e-06
4.40925537167
8.8357375954
12.5106006971
17.9537570846
22.2335888942
24.8999690218
28.6514013904
29.8516509626
33.9683925426
39.3612110854
44.0753747033
47.5821712007
53.9041874773
60.7407510565
66.6244055512
73.7769495363
82.6274418908
92.7123995007
99.9889527197
99.999999973
100
100
100
100
100
1.92718000447e-17
1.38337495716
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8.76151170554e-33
99.4282850464
89.3976460191
85.1384759474
81.8004882982
79.271095697
77.0249330332
74.2514080041
72.3099900287
70.7287925272
69.4728911264
68.5244532565
68.1743615779
67.5782879208
68.2315987472
0.00115211429931
1.47442326983e-06
7.45732005144e-07
10.7962135741
11.0092617801
10.0505979091
8.63066716371
6.77182942391
4.25957641948
4.79600740078e-06
2.74475433205e-06
3.0088354917e-06
8.72786126829e-06
5.52128007287
9.21417052914
12.9178958054
16.0237072521
20.6503900758
25.2980157618
27.55144474
30.6620061558
35.4528669931
40.1372595387
42.7286794312
48.7525410291
55.2994711597
60.7357569079
67.6115613818
75.9945738014
84.3539824334
94.5596538891
99.9998018399
99.999999998
100
100
100
100
100
4.53440250861e-22
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
95.5695491128
82.4106155031
88.9818121197
85.6199623366
82.3575314229
79.2469871407
76.2891696923
73.1859912429
70.9305280778
69.1838094989
67.8467139831
66.9864959309
66.7175140578
65.8459779269
65.1091622336
3.85034914718e-06
0.00152796229285
4.75545780438e-07
10.0614898308
11.0283956533
9.86712290012
8.0355679794
4.99539668144
2.68800613345e-06
1.21067220971e-06
9.94790898369e-07
1.18250429064e-06
2.36758019016e-06
5.84600329752
10.6931033485
13.9325089904
16.1700640661
18.552060509
22.7470662756
27.2605512284
30.7631131255
34.9051508426
38.1687985632
42.8748860252
49.967216613
55.611836587
60.4568378301
67.71056013
76.344878021
86.5553367498
96.8493672547
99.9999609239
99.9999999995
100
100
100
100
100
1.20307816851e-21
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
100
99.9996201456
94.3269221606
88.3845532856
83.9985987005
79.5964225824
75.6999716489
72.4960450127
69.9871285228
68.0700695367
66.5992636921
65.7497037698
65.2222723702
64.2914560879
63.5822662181
2.46077093493e-06
5.53284997641
2.89811917369e-07
9.10321807439
11.0867838631
9.71938880253
7.85233479796
6.59049276035
5.00975450073
3.97868419506e-05
6.38201900787e-06
4.93470033617e-06
1.40930170274e-05
6.65985242256
10.9806654365
14.0770904266
16.568571281
18.9584264709
21.0532276952
23.4915739591
28.2444152272
32.9817845898
37.0160594468
42.8049943582
49.3950170479
54.6685006355
60.4141222483
68.5700096229
77.8527665796
86.4148606094
96.9813350495
99.9999960271
100
100
100
100
100
100
1.55998562652e-15
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2.04340283704e-07
81.5766897427
99.7815593702
95.7365791216
90.698906151
84.988589666
80.6152953192
75.7290438911
72.2636951327
69.4694443006
67.3747761154
65.9101333341
65.3478314774
64.0085350157
63.0249172547
62.4371753953
5.10185076657e-07
6.19375816581
1.6803205859e-07
9.5735479771
10.3260904987
7.83727532888
4.68089992228
1.53906373559
2.12710588613e-07
1.22353910869e-07
1.1108745919e-07
1.40862078213e-07
3.03128740567e-07
4.96714761163
11.6334281348
15.2202084784
16.6669254607
17.9823562271
19.8128067186
22.4920037492
25.552248827
29.253423198
34.5854365397
41.9537015047
48.7161574184
54.6719701006
59.4925765122
67.1629706085
76.2605012125
87.04890559
98.9162444774
99.9999993544
99.9999999999
100
100
100
100
100
1.98195059634e-14
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
100
100
99.9999998886
99.7056566778
93.4785898155
87.0280169838
81.0609739007
76.2349891694
72.1812349129
68.9340989387
66.5616097244
64.9932601073
64.059457736
62.5732812014
61.7743608772
61.98999993
6.98877639372e-07
3.62510338951
9.80843833177e-08
9.12252494603
7.27512562386
4.79955584914
2.76216594273
1.8017825419
5.82685376244e-08
6.26025850353e-08
9.09519082978e-08
1.947362105e-07
2.76829578651e-06
7.02244221621
11.1900643048
13.2814782293
14.4040098366
15.4474724313
17.6286548071
21.3245459336
24.4513105509
28.3171679541
33.2747066546
39.5232692624
45.6826400208
50.8321144332
56.9904901157
66.2239438055
76.3164828897
88.1368171661
99.5076947796
99.9999957846
100
100
100
100
100
100
2.93661512876e-13
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.77509968759e-33
99.9998494827
100
99.9999999994
99.9998482343
95.396780851
88.8580938002
81.8613536808
76.3823865596
71.7541412552
67.9173478283
65.0833965965
63.291709897
61.7019987818
60.4007230869
59.4729329458
60.3487006297
4.41162928923
6.52623869815e-08
5.98076969383e-08
10.6679318701
8.61709391639
5.18148037215
2.81374374129
1.79465930364
4.17722802393e-08
3.94328453027e-08
4.15261487473e-08
5.00746070713e-08
9.30934128758e-08
4.85921319782
11.7879535092
13.7305230257
14.4530486681
15.017994788
16.0753746587
17.8644823176
21.1488608483
26.1107402614
31.6696828923
37.6539728877
42.721869674
47.9074202036
54.975509105
64.3811940262
75.6135505424
87.1839592825
97.8607448598
99.9999897754
100
100
100
100
100
100
1.17509584832e-12
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
90.4772235067
99.999999753
100
100
99.9999999377
98.9944635625
89.8537596187
82.4226483171
76.0649549848
70.8197716384
66.4918405352
63.077370208
60.621518355
58.4443747257
57.0304242401
55.9744501811
57.1454159454
8.45409834199
1.92632183144e-06
5.54241202012e-08
11.4090241268
10.215879722
4.86094601366
3.34196520796
2.20189983805
2.72862502555e-08
3.2182924116e-08
6.42204059996e-08
1.54274664025e-07
1.77050701935e-07
0.422878617692
10.4143771285
12.8977379288
13.4453938103
13.0837726314
12.7291294092
14.0180971465
17.5595403388
22.942838867
28.8092311536
34.791159903
40.7848714346
45.9919921876
53.6598534936
62.6873424948
72.6685479388
83.9939664837
95.5678941354
99.9999823669
100
100
100
100
100
100
5.01654931801e-11
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
100
100
100
100
100
99.9998641348
92.9300160739
83.3339621818
75.597333625
69.62846156
64.8032438727
60.0432783654
56.6611017302
54.2502471305
52.9032614177
51.9047542384
52.8977571734
9.72576843838
2.93573593039
7.18077762187e-08
2.78425260891
5.54849327006
5.68693636104
5.10616727095
5.01885229307
6.34705293739
1.94035330466e-07
6.16037364397e-08
4.56452388762e-08
4.58934304871e-08
9.18278020799e-08
8.90526437566
13.0482741024
12.9832433208
10.8267865867
6.89206611673
5.921035791
11.5927925896
20.2405309586
26.883693995
32.2393189692
37.34085072
43.2574484098
50.9739438344
60.140957757
70.3141157288
80.923040589
91.1631336546
99.9956357715
99.9999999994
100
100
100
100
100
1.98632277155e-10
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8.84000013653e-33
100
100
100
100
100
99.9999999191
97.0153809707
85.3674687149
75.5803325081
68.0322539468
62.3125557354
57.5835397928
53.7782051804
50.3639143879
48.1296375247
47.69364285
47.7449715163
7.49049943379
4.54437323917
2.06056237654e-07
4.19189457652e-05
6.8354257363
8.991016287
10.158869757
8.58173793168
6.14974669512
2.33841434841e-07
5.4916675869e-08
3.52801566095e-08
2.93153982328e-08
3.61914653872e-08
6.40717440056
12.9533550829
13.6725314709
11.1819384336
4.52849130876
0.0509663474518
8.56784900315
16.7793325133
22.8569769276
28.1181103759
33.4699526569
39.6695750243
47.6297064439
56.937830528
66.4120685901
75.3827345442
85.8727079507
99.3934852258
99.9999988743
99.9999999997
100
100
100
100
2.39624067245e-07
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
98.5254482678
100
100
100
100
100
100
99.9854181533
88.1976631815
76.2483933233
66.7585111657
59.676229283
53.931700291
49.6830793465
46.4072332524
42.773054471
42.8101706985
42.0382542453
4.92133400443
5.60761937796
8.74498091763e-07
1.67035333189e-06
9.32406765942
10.9534625326
10.4186397469
9.68245004849
8.65721060691
6.08733419781
1.25536727876e-07
3.48981338289e-08
2.38590647723e-08
2.38072851725e-08
0.160400342507
14.2174353099
14.6347316349
7.92440490642
1.09699482233e-06
5.71116006591e-08
6.1968025124e-08
8.144942654
18.6215446502
23.8424392379
28.8106773985
34.8287011989
42.7781446166
52.4456685192
60.9738362365
68.3705211645
78.06185
91.0687739079
99.9530999297
99.999999437
100
100
100
100
0.000569338586687
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
100
100
100
100
100
100
100
99.9999959583
91.6968734275
78.0379798218
66.4905721338
57.96075212
50.84777257
45.2506303016
41.4684832745
37.4624522756
36.8249952297
37.5416600367
4.54957231143
7.60676456599
3.14908024049e-05
5.13520529661e-07
11.2848421692
11.6287634061
11.6185454428
11.2486001536
10.5909615347
9.0744030981
0.0877217608611
5.1562025167e-08
1.92821342191e-08
1.59369127101e-08
7.96450573036
16.3519872445
14.1908316097
0.000256521092217
5.2530970405e-06
1.51997678486e-08
3.68583034178e-09
1.09021548997
9.90821051236
12.6758030105
19.9740837284
27.4990516175
35.6489611103
46.9637600313
54.8412703698
59.0883179013
66.6891280785
79.198937481
86.3203096797
99.9193105698
99.9999999052
100
100
100
99.9940726092
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2.05034632048e-33
100
100
100
100
100
100
100
99.9999999981
95.6082521772
80.4028154421
66.9898867286
56.6627739184
49.0928734516
42.1732214339
36.4052371403
31.8289647214
31.7832245386
36.0567480612
0.325336366462
1.0442681494
1.94543728671e-05
2.18290211016
13.0264473449
13.5503170709
13.820134408
13.633868494
13.3973788254
12.8076370903
10.503790282
6.88216099955e-05
3.4053139038e-08
1.01766455231e-08
6.57790518067e-09
15.1159792133
0.141285492429
0.000284725913803
0.00608343272749
12.2552981826
1.23077840703e-09
2.94624033774e-10
0.20977097577
18.0529205244
20.8997183755
21.4625487069
25.5447843563
39.0142874668
50.9869143175
47.0434920962
50.8514069385
59.7051599137
66.4723459089
76.1299480159
99.9532124455
99.999999921
100
100
100
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
100
100
100
100
100
100
100
100
100
98.9828773707
82.3322169822
67.871128292
56.2347750304
47.3697807244
40.4328398246
34.6836074061
30.324278349
30.2865644035
29.0533593488
1.49260726569
3.96256369488e-05
0.00625301082374
2.40172195069e-07
14.1373425564
16.0227583948
16.8603677627
16.7323071863
16.891981858
15.6311334589
14.1550155549
9.38667259205
2.02655837091e-07
7.74903935158e-09
5.36974447249e-09
7.38204945044e-08
5.73985161988e-05
0.986844147886
16.2527152653
12.0072388359
2.70749937739e-10
5.29523563426e-11
1.21127321079e-11
9.21486236565e-12
9.34646601609e-12
4.9894534367e-05
3.17511483573
4.16935554018e-09
26.0699025626
32.8969107906
28.6964782977
51.4221118083
48.285430179
65.0058139408
71.1215982233
96.4903427894
99.9758564458
100
100
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3.31954413346e-35
99.6637819313
100
100
100
100
100
100
100
100
99.9303127371
83.5630356447
69.2851759513
57.1832546632
47.4388701611
40.0799025694
33.9764633253
28.6439460193
25.3476887245
18.7673638974
1.12470281323
6.3004500351
3.47155131912
4.7597154741e-07
6.12876931373e-09
1.70327983719e-08
1.9161504878e-05
1.23933369027e-07
8.74329794358e-08
4.63772684304e-08
2.47217022331e-08
1.24119421163e-08
5.38001606114e-09
1.83116224923e-09
6.75635190179e-10
1.8982520976e-10
9.49940085778e-11
8.9040785481e-11
6.48435028379e-11
4.07530135989e-11
2.67913026621e-11
1.59544300322e-11
7.94175888248e-12
4.29447128573e-12
3.47287247915e-12
2.20868661872e-12
1.06748234599e-12
4.45547023669e-13
3.15587758209e-13
1.14483844521e-13
1.03398148031e-13
5.5657784829e-15
1.39242809683e-12
1.01589784819e-17
1.50191494673e-12
7.22023377449e-21
1.22241069451e-11
1.57073635515e-26
9.92985135616e-26
100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5.52238465419e-35
100
2.43883051211e-14
100
100
100
100
100
100
100
99.9221216818
82.7595704451
68.7633814518
56.8420930957
46.5133129358
38.1273291497
31.3623111306
26.0337193993
22.5354017633
12.7915824017
)
;
boundaryField
{
frontAndBack
{
type empty;
}
upperWall
{
type calculated;
value uniform 0;
}
lowerWall
{
type calculated;
value uniform 0;
}
inlet
{
type calculated;
value uniform 1.97369461547e-32;
}
outlet
{
type calculated;
value nonuniform List<scalar>
20
(
1.1366005011e-34
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9.7466400764e-36
2.2092438754e-34
)
;
}
}
// ************************************************************************* //
|
|
4e91c4f773c946436318b495e5238957ed627bf9
|
01351920bbf9efb2ee154c72f41b7890ff516fa4
|
/942. DI String Match/main.cpp
|
a7f12ab74e19284e2be22254ca90039076af7d9f
|
[
"MIT"
] |
permissive
|
dllexport/leetcode
|
0631c1748c4eed28ff0e2b7679d17b667629d49a
|
a0cfd5d759daa36fec808b2dbe19c045d218ed76
|
refs/heads/master
| 2022-08-25T12:54:44.596484
| 2019-07-23T15:13:04
| 2019-07-23T15:13:04
| 266,346,397
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 606
|
cpp
|
main.cpp
|
#include <vector>
#include <string>
using namespace std;
vector<int> diStringMatch(string S) {
auto size = S.size();
vector<int> vec(size + 1, 0);
int min = 0;
int max = size;
for (int j = 0; j < size; ++j)
{
switch (S[j])
{
case 'I':
{
vec[j] = min++;
break;
}
case 'D':
{
vec[j] = max--;
break;
}
}
}
vec.back() = max;
return vec;
}
int main()
{
auto i = diStringMatch("IDID");
return 0;
}
|
0520bc78ea562b429f402e563cb86c66398b8a55
|
011006ca59cfe75fb3dd84a50b6c0ef6427a7dc3
|
/stress_testing/my_code.cpp
|
4c3de2e0e9e7e5e739359f6adf45b7dbf8f590f0
|
[] |
no_license
|
ay2306/Competitive-Programming
|
34f35367de2e8623da0006135cf21ba6aec34049
|
8cc9d953b09212ab32b513acf874dba4fa1d2848
|
refs/heads/master
| 2021-06-26T16:46:28.179504
| 2021-01-24T15:32:57
| 2021-01-24T15:32:57
| 205,185,905
| 5
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,768
|
cpp
|
my_code.cpp
|
#include<bits/stdc++.h>
using namespace std;
# define C continue;
# define R return
# define D double
# define I insert
# define ll long long
# define ld long double
# define ull unsigned long long
# define ui unsigned int
#define FILE_READ_IN freopen("input.txt","r",stdin);
#define FILE_READ_OUT freopen("my_result.txt","w",stdout);
# define pb push_back
# define vi vector < int >
# define vc vector < char >
# define vs vector < string >
# define vb vector < bool >
# define vd vector < D >
# define vll vector < ll >
# define vull vector < ull >
# define vvi vector < vector < int > >
# define vvb vector < vector < bool > >
# define vvc vector < vector < char > >
# define vvll vector < vector < ll > >
# define vvd vector < vector < D > >
# define vld vector < ld >
# define all(v) (v).begin() , (v).end()
# define allrev(v) (v).rbegin() , (v).rend()
# define allcomp(v) v.begin() , v.end() , comp
# define allrevcomp(v) v.rbegin() , v.rend() , comp
# define pii pair < int , int >
# define pll pair < long , long >
# define pld pair < ld , ld >
# define pDD pair < D , D >
# define vpld vector < pld >
# define vpii vector < pii >
# define vpll vector < pll >
# define vpDD vector < pDD >
# define vvpii vector < vector < pii > >
# define F first
# define S second
# define mp make_pair
# define fast ios_base::sync_with_stdio(false) ; cin.tie(0) ; cout.tie(0);
# define dist(a,b,p,q) sqrt((p-a)*(p-a) + (q-b)*(q-b))
# define pp(n) printf("%.10Lf",n);
# define line cout<<"\n";
const ld pie = 3.14159265358979 ;
const ll mod = 1e9 + 7 ;
string vow = "aeiou";
void solve ( int test_case )
{
string s , r ;
cin >> s >> r ;
int a = s.size() , b = r.size() ;
if ( b < a ) { cout << "Impossible\n" ; R ; }
int h[26] = {} ;
for ( auto i : s ) h[i - 'a'] ++ ;
int t = 0 ;
for ( int i=0 ; i < b ; i++ )
{
int indx = r[i] - 'a' ;
if ( h[indx] )
{
h[indx] -- ;
r[i] = '.' ;
t ++ ;
}
}
if ( t != a ) { cout << "Impossible\n" ; R ; }
sort ( all ( r ) ) ;
bool ok = false ;
for ( int i=0 ; i < b ; i++ )
{
if ( r[i] == '.' ) C ;
if ( ok ) { cout << r[i] ; C ; }
if ( r[i] < s[0] ) { cout << r[i] ; C ; }
if ( r[i] > s[0] )
{
cout << s ; ok = true ;
cout << r[i] ; C ;
}
int e = 0 ;
for ( ; e < a && s[e] == s[0] ; e ++ ) ;
if ( e < a && s[e] < r[i] ) { cout << s << r[i] ; }
else { cout << r[i] << s ; }
ok = true ;
}
if ( !ok ) cout << s ;
line
}
int main()
{
FILE_READ_IN
FILE_READ_OUT
fast
int t = 1;
cin >> t;
for ( int i=0 ; i<t ; i++ ) solve(i);
return 0;
}
|
4a3913941023bc37ed3d9a644078f13ed98f82c5
|
e30e9a05829baf54b28a4a953c98f6ea2ca5f3cf
|
/Timus/T1255.cpp
|
282271ad9a83f661ccba71cbd30eb9712b33db09
|
[] |
no_license
|
ailyanlu/ACM-13
|
fdaf4fea13c3ef4afc39a522e12c5dee52a66a24
|
389ec1e7f9201639a22ce37ea8a44969424b6764
|
refs/heads/master
| 2018-02-24T00:33:02.205005
| 2013-01-09T18:03:08
| 2013-01-09T18:03:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 391
|
cpp
|
T1255.cpp
|
#include <iostream>
using namespace std;
int n, k;
int main (void)
{
#ifndef ONLINE_JUDGE
freopen ("T1255.in", "r", stdin);
freopen ("T1255.out", "w", stdout);
#endif
cin >> n >> k;
if (n<k)
cout << "0";
else if (2*(n%k)-k<0)
{
int ans =(n/k)*(n+n%k);
cout << ans;
}
else
{
int ans = (n/k)*(n+n%k) + 2*(n%k)-k;
cout << ans;
}
return 0;
}
|
e5713dc6a5f0b1e9b11de2e26ce4e8fb288cd264
|
f798e5955febcbb5e053604dde0056225954e956
|
/HackerEarth/MaximizeFunction.cpp
|
22b7331e300652c24d4fb56a2d27a0640c4a25cd
|
[] |
no_license
|
atulRanaa/problem-solving-directory
|
bd129da93f205602fd1b596a80d98ca3c164020f
|
3c261a7a57591203d0fb502859a0e388f9b09ae1
|
refs/heads/master
| 2022-09-02T00:22:02.199595
| 2022-08-22T07:14:56
| 2022-08-22T07:15:41
| 177,447,829
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,590
|
cpp
|
MaximizeFunction.cpp
|
// hackerearth
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 1e6+5;
const ll MOD = 1000000007;
#define all(x) x.begin(),x.end()
#define pii pair<int,int>
#define pis pair<ll,string>
#define F first
#define S second
#define LCM(a,b) ((a*b)/__gcd(a,b))
#define inf 1e15
#define test ll cse;cin>>cse;for(ll _i=1;_i<=cse;_i++)
#define PI 3.14159265
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const double EPS = 1E-9;
typedef vector< vector<double> > matrix;
typedef vector<int> vi;
ll n,k,ar[N], ans = -1;
ll S(ll y){
ll res = 0;
for(ll i=0;i<n;i++) res += max(0LL, ar[i] - y*(i+1));
// cout << "S: " << res << "\n";
return res;
}
void binarySearch(ll l,ll r){
ll res;
while(l <= r){
ll mid = (l+r)>>1;
res = S(mid);
// cout << mid << " " << res << " " << k << "\n";
if(res >= k){ ans = mid; l = mid+1;}
else
// res < k
r = mid-1;
}
}
ll binaryExponentiation(ll n, ll x){
ll result = 1LL;
while(n > 0){
if(n&1) result *= x;
x = x*x;
n >>= 1;
}
return result;
}
int main(){
fast;
test{
cin >> n >> k;
for(int i=0;i<n;i++) cin>>ar[i]; // for(int i=0;i<n;i++) cout<<ar[i]<<" "; cout << "\n";
binarySearch(0, 1000000000005L);
cout << ans << " " << S(ans) << "\n";
}
return 0;
}
|
300148b72065d8fa26bcce9df816758cfc9d61f9
|
9530eb5b4fc5acc39d71c6d8e6637e49093f58b8
|
/10773 Back to Intermediate Math.cpp
|
22042cc309cdc8548c27dfb546ecca36af1baa8c
|
[] |
no_license
|
Mahbub20/UVA-Solutions
|
9ea6ae47a22730b30168118edee0fa77eee1a1f6
|
3ed44a00130bfc9b6ce4cfe2d17c57940ffdc3c6
|
refs/heads/master
| 2021-01-13T08:18:12.680369
| 2018-10-03T16:15:08
| 2018-10-03T16:15:08
| 68,840,053
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 503
|
cpp
|
10773 Back to Intermediate Math.cpp
|
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0),cin.tie(0);
double d,v,u,diff,n,t1,t2;
int k = 1;
cin >> n;
while(n--)
{
cin >> d >> v >> u;
if(v==0 || u<=v || u==0)printf("Case %d: can't determine\n",k++);
else{
t1 = d/u;
t2 = d/(sqrt(pow(u,2)-pow(v,2)));
diff = t2-t1;
printf("Case %d: %.3lf\n",k++,diff);
}
}
return 0;
}
|
0b6f6b09f44313b9f12ef05e631199cc5955039e
|
82bbdeb7d87ab9d7409605c316e8f6b7ab33a36b
|
/misc/tensor.cc
|
083f6c7a217dfd2773b119feb1b5c07989a3689f
|
[] |
no_license
|
taozhijiang/study-tensorflow
|
0ae62139df14ed41f7bf242823a999a92447928b
|
f6d621745f5bdc2bc83b860f5c1017a97c7da265
|
refs/heads/master
| 2022-09-04T13:54:24.317737
| 2020-05-26T16:13:52
| 2020-05-26T16:13:52
| 266,824,092
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,170
|
cc
|
tensor.cc
|
#include <iostream>
#include <cassert>
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/tensor.h"
using tensorflow::Tensor;
using tensorflow::TensorShape;
// 一些Tensor使用方式展示
// 资源来自于tensorflow的代码库
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/tensor_testutil.h
//
// 单个变量组成的scalar类型
template <typename T>
tensorflow::Tensor AsScalar(const T& val) {
tensorflow::Tensor ret(tensorflow::DataTypeToEnum<T>::value, {});
ret.scalar<T>()() = val;
return ret;
}
// Constructs a flat tensor with 'vals'.
template <typename T>
tensorflow::Tensor AsTensor(const std::vector<T>& vals) {
tensorflow::Tensor ret(tensorflow::DataTypeToEnum<T>::value, {static_cast<tensorflow::int64>(vals.size())});
std::copy_n(vals.data(), vals.size(), ret.flat<T>().data());
return ret;
}
// 输入数据源为一维数组类型,然后可以根据shape进行变形
// 输入数据源的大小要和shape总数据匹配
template <typename T>
tensorflow::Tensor AsTensor(const std::vector<T>& vals, const tensorflow::TensorShape& shape) {
tensorflow::Tensor ret;
ret.CopyFrom(AsTensor(vals), shape);
return ret;
}
static void new_line() {
std::cout << "\n =============================== \n";
}
int main(int argc, char* argv[]) {
{
Tensor t1 = AsScalar(100);
::printf("t1.dims(): %d\n", t1.dims());
// t1.dims(): 0
::printf("t1.scalar(): %d\n", t1.scalar<int>()());
//t1.scalar(): 100
}
new_line();
{
std::vector<int> vec { 3, 8, 2, 9, 4};
Tensor t1 = AsTensor(vec);
::printf("t1.dims(): %d, t1.dim_size(0): %d\n",
t1.dims(), t1.dim_size(0));
// t1.dims(): 1, t1.dim_size(0): 5
auto t1_ft = t1.flat<int>();
for(size_t i=0; i<t1.dim_size(0); ++i) {
std::cout << "\t" << t1_ft(i);
}
std::cout << std::endl;
// 3 8 2 9 4
auto t1_vec = t1.vec<int>();
for(size_t i=0; i<t1.dim_size(0); ++i) {
std::cout << "\t" << t1_vec(i);
}
std::cout << std::endl;
}
new_line();
{
std::vector<int> vec { 1, 2, 3, 4, 5, 6};
Tensor t1 = AsTensor(vec, {3, 2}); // 3行2列
::printf("t1.dims(): %d, t1.dim_size(0): %d, t1.dim_size(1): %d\n",
t1.dims(), t1.dim_size(0), t1.dim_size(1));
// t1.dims(): 2, t1.dim_size(0): 3, t1.dim_size(1): 2
// 一个简便的元素个数的统计返回
::printf("t1.NumElements(): %lld\n", t1.NumElements());
// t1.NumElements(): 6
auto t1_ft = t1.flat<int>();
for(size_t i=0; i<t1.dim_size(0); ++i) {
for(size_t j=0; j<t1.dim_size(1); ++j) {
std::cout << "\t" << t1_ft(i * t1.dim_size(1) + j);
}
std::cout << std::endl;
}
std::cout << std::endl;
// 1 2
// 3 4
// 5 6
auto t1_mat = t1.matrix<int>();
for(size_t i=0; i<t1.dim_size(0); ++i) {
for(size_t j=0; j<t1.dim_size(1); ++j) {
std::cout << "\t" << t1_mat(i, j);
}
std::cout << std::endl;
}
std::cout << std::endl;
}
new_line();
{
std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8};
Tensor t1 = AsTensor(vec, {4, 2});
auto t1_mat = t1.matrix<int>();
for(size_t i=0; i<t1.dim_size(0); ++i) {
for(size_t j=0; j<t1.dim_size(1); ++j) {
std::cout << "\t" << t1_mat(i, j);
}
std::cout << std::endl;
}
std::cout << std::endl;
// 1 2
// 3 4
// 5 6
// 7 8
// 无论是Slice还是SubSlice,都是引用复用底层的存储结构
// Slice得到的结果是const的,不能修改;序该元素只能从最原始的Tensor操作
// 左闭右开的结构
// [dim_start, dim_limit)
Tensor t1_slice = t1.Slice(1, 3);
std::cout << "t1_slice: " << t1_slice.DebugString() << std::endl;
// t1_slice: Tensor<type: int32 shape: [2,2] values: [3 4][5...]...>
// 只按第一个维度切分
Tensor t1_subslice = t1.SubSlice(1);
std::cout << "t1_subslice: " << t1_subslice.DebugString() << std::endl;
// t1_subslice: Tensor<type: int32 shape: [2] values: 3 4>
std::cout << "t1.IsAligned(): " << t1.IsAligned() << std::endl; // true
std::cout << "t1_slice.IsAligned(): " << t1_slice.IsAligned() << std::endl; // false
std::cout << "t1_subslice.IsAligned(): " << t1_subslice.IsAligned() << std::endl; // false
// 性能优化,减少分配???
// 原始Tensor的数据变了,这边引用的Slice也看见了这个变化
auto ft = t1.flat<int>();
ft(2) = 100;
std::cout << "t1_slice: " << t1_slice.DebugString() << std::endl;
// t1_slice: Tensor<type: int32 shape: [2,2] values: [100 4][5...]...>
}
std::cout << "[INFO] Tensor finished." << std::endl;
return EXIT_SUCCESS;
}
|
327b3b0ef5547220d714e7117ef11ce6144b043f
|
9da88ab805303c25bd9654ad45287a62a6c4710f
|
/Cpp/LeetCode/wc208_3.cpp
|
692dd9cea9f2bdaf6ab76a6d7a2a820e49712e26
|
[] |
no_license
|
ms303956362/myexercise
|
7bb7be1ac0b8f40aeee8ca2df19255024c6d9bdc
|
4730c438354f0c7fc3bce54f8c1ade6e627586c9
|
refs/heads/master
| 2023-04-13T01:15:01.882780
| 2023-04-03T15:03:22
| 2023-04-03T15:03:22
| 232,984,051
| 2
| 0
| null | 2022-12-02T06:55:19
| 2020-01-10T06:47:00
|
C
|
UTF-8
|
C++
| false
| false
| 1,324
|
cpp
|
wc208_3.cpp
|
#include "usual.h"
class ThroneInheritance {
string kname;
unordered_set<string> live;
unordered_map<string, vector<string>> edges;
public:
ThroneInheritance(string kingName) : kname(kingName) {
live.insert(kingName);
edges.insert({kingName, {}});
}
void birth(string parentName, string childName) {
edges[parentName].push_back(childName);
live.insert(childName);
}
void death(string name) {
live.erase(name);
}
vector<string> getInheritanceOrder() {
vector<string> ans;
dfs(kname, ans);
return ans;
}
void dfs(const string& u, vector<string>& ans) {
if (live.count(u) != 0)
ans.push_back(u);
for (const auto& v : edges[u]) {
dfs(v, ans);
}
}
};
// [null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
/**
* Your ThroneInheritance object will be instantiated and called as such:
* ThroneInheritance* obj = new ThroneInheritance(kingName);
* obj->birth(parentName,childName);
* obj->death(name);
* vector<string> param_3 = obj->getInheritanceOrder();
*/
int main(int argc, char const *argv[])
{
return 0;
}
|
d56bc7e4d865f28a388fdd63e5305ea8e83eb7be
|
62d5fd2277ed20029b656d18d6738c248273eedd
|
/poj1979.cpp
|
8f5ac7f7fdedf4f40d16793af197c628002b6303
|
[] |
no_license
|
guinao/poj
|
c2bc9f8d498dd0bb2a36443b854f49583adb46ae
|
80795e41c22c6b4a2d046e58d49c337576577f8f
|
refs/heads/master
| 2021-01-01T05:41:22.621218
| 2015-09-05T12:05:38
| 2015-09-05T12:05:38
| 21,536,515
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 712
|
cpp
|
poj1979.cpp
|
#include <cstdio>
#include <cstring>
char grid[32][32];
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
int dfs(int x, int y)
{
int ret = 1;
grid[x][y] = '#';
for(int i=0; i<4; ++i){
int nx = x + dx[i];
int ny = y + dy[i];
if(grid[nx][ny] == '.'){
ret += dfs(nx, ny);
}
}
return ret;
}
int main()
{
int w, h;
scanf("%d %d", &w, &h);
while(w && h){
memset(grid, '#', sizeof grid);
bool find = false;
int x, y;
for(int i=1; i<=h; ++i){
scanf("%s", &grid[i][1]);
if(!find){
for(int j=1; j<=w; ++j){
if(grid[i][j] == '@'){
find = true;
x = i, y = j;
break;
}
}
}
}
printf("%d\n", dfs(x, y));
scanf("%d %d", &w, &h);
}
return 0;
}
|
6a17b4a1860501ca82fa31aed4da6a704e453ff1
|
67ed24f7e68014e3dbe8970ca759301f670dc885
|
/win10.19042/System32/trie.dll.cpp
|
e57fc58e743be54cb2f521067cc266b29d091aa1
|
[] |
no_license
|
nil-ref/dll-exports
|
d010bd77a00048e52875d2a739ea6a0576c82839
|
42ccc11589b2eb91b1aa82261455df8ee88fa40c
|
refs/heads/main
| 2023-04-20T21:28:05.295797
| 2021-05-07T14:06:23
| 2021-05-07T14:06:23
| 401,055,938
| 1
| 0
| null | 2021-08-29T14:00:50
| 2021-08-29T14:00:49
| null |
UTF-8
|
C++
| false
| false
| 204
|
cpp
|
trie.dll.cpp
|
#pragma comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\System32\\trie.DllCanUnloadNow\"")
#pragma comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\System32\\trie.DllGetClassObject\"")
|
2c6adc168e301eee21d49a761bf0022050f9dafe
|
fd6ab01556ae8de49ffb0231c5dd6ccab91cf7a5
|
/Estructura de Datos/Practicas/Practica1/ejercicio8.cpp
|
0e0da9815df2ac3d45618c07bd5ae7a546e70291
|
[] |
no_license
|
carlosyyxy/2nd-semester
|
d622c92397967374adb445d201991bc474ddda9b
|
18bae911ae0a085a482a3a8cc8343e8271f2e219
|
refs/heads/master
| 2023-06-05T00:14:51.812127
| 2021-06-21T05:29:37
| 2021-06-21T05:29:37
| 364,369,883
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,311
|
cpp
|
ejercicio8.cpp
|
/*Ejercicio 3: Para las siguientes instrucciones, construya el estado de todas
las variables en la memoria(de forma gráfica) que muestre que ocurre en ella,
y cuál es la salida del programa.*/
#include<iostream>
using namespace std;
struct node {
int info;
node *next;
};
void main2();
int main(){
main2();
return 0;
}
void main2() {
node *p, *r, *s;
p = new node; //Se reserva un espacio de memoria para p
s = new node; //Se reserva un espacio de memoria para s
r = new node; //Se reserva un espacio de memoria para r
(*p).next = r; //r sera el siguiente nodo de p.
(*r).next = s; //s sera el siguiente nodo de r.
(*s).next = p; //p sera el siguiente nodo de s.
(*s).info = 3; //el valor de info de s valdrá 3
(*((*((*((*p).next)).next)).next)).info = 2; /*El siguiente nodo
de p, es r, el que le sigue es s y el que le sigue a s es p, es decir el info
de p valdrá 2*/
(*((*((*s).next)).next)).info = 1; /*El nodo que le sigue a s es p y el que
le sigue a p es r. R valdrá 1.*/
p = (*s).next; //P es igualado al siguiente de s que sigue siendo p.
cout<<((*p).info+(*s).info+(*r).info)<<endl; // Imprime por pantala 2+3+1
cout<<"p.info: "<<p->info<<endl;
cout<<"s.info: "<<s->info<<endl;
cout<<"r.info: "<<r->info<<endl;
}
|
8933a0dd451fc304d3389ff982c6513be5f82ae6
|
fbb149fdbf7ae06e93091f1846d6e68057a10360
|
/main.cpp
|
4e5f2e1c341dcf1b1f23562188aefe455f1a5fdc
|
[] |
no_license
|
adeljck/DatastructLearning
|
f3315ab0af7686e507f6bb66fcf17ee628f1d41d
|
a3727abd7cb28c4b633eb8a8af5dad35be48e682
|
refs/heads/master
| 2023-07-17T06:09:02.555874
| 2021-08-23T13:30:01
| 2021-08-23T13:30:01
| 399,069,613
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 396
|
cpp
|
main.cpp
|
#include <iostream>
#include <stdio.h>
#include "sortA/sort.h"
using namespace std;
int main() {
int maxsize = 9;
int data[9] = {0, 4, 5, 2, 7, 9, 8, 10, 6};
for (int i = 0; i < maxsize; ++i) {
cout << data[i] << ",";
}
QuickSort(data, 0, maxsize - 1);
cout << endl;
for (int i = 0; i < maxsize; ++i) {
cout << data[i] << ",";
}
return 0;
}
|
8c20adb2c974031fb2ba07dde5154ec8dc1abcb9
|
81e8a52cfc99e6fd1f473fb227525b203b7b1503
|
/CSCE_121_LabWork33/LabWork33/Person.cpp
|
9f674e9476b30d1eda7b43def2165645c0946bf6
|
[] |
no_license
|
jtiu-cse-school-assignments/csce-121-labs-part2
|
9968447e959eb20f93098bb6dbb1db9ce7fc4f33
|
0b48293af8496afc7ab9637f6b6a5e0771f2be82
|
refs/heads/master
| 2020-07-20T15:01:38.863262
| 2019-09-05T22:00:28
| 2019-09-05T22:00:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,312
|
cpp
|
Person.cpp
|
#include <string>
#include <ostream>
#include "Person.h"
using namespace std;
// Fix 2b
/*
Write the definitions for any functions in the
predicate function object class: comp_firstname
- If you do option 1, you'll need to apply
the scope resolution operator twice.
*/
// Default Constructor
Person::Person() : firstname(""), lastname("") {}
Person::Person(string firstname, string lastname) :
firstname(firstname), lastname(lastname) {}
// Accessor Functions
string Person::getFirstname() const {
return firstname;
}
string Person::getLastname() const {
return lastname;
}
void Person::setFirstname(string firstname) {
this->firstname = firstname;
}
void Person::setLastname(string lastname) {
this->lastname = lastname;
}
// Required for default sorting in an STL container
bool Person::operator<(const Person& p) const {
if (lastname < p.lastname)
return true;
if (lastname == p.lastname) {
if (firstname < p.firstname)
return true;
}
return false;
}
ostream& operator<<(ostream& os, const Person& p) {
os << p.getFirstname() << " " << p.getLastname();
return os;
}
bool comp_firstname::operator()(const Person& a, const Person& b) const {
return a.getFirstname() < b.getFirstname();
}
|
5d7e56851f9a01f39d55a40112a57c493b921285
|
d1092749d8360f5ea9440d02313f83f9c10f77a6
|
/Test1/Test1/Player.cpp
|
e8e24ac99b7466410f53557fe740b71df0af2db1
|
[] |
no_license
|
cat5778/KatanaZero
|
d6fc7b56bab9a9f36f700940eb2cdfac1e916b3a
|
6baa2248d2eddb6512dd45884f36809e0f555f75
|
refs/heads/master
| 2020-12-05T13:47:08.833923
| 2020-01-27T13:21:52
| 2020-01-27T13:21:52
| 232,127,346
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 5,905
|
cpp
|
Player.cpp
|
#include "stdafx.h"
#include "Player.h"
CPlayer::CPlayer()
{
}
CPlayer::~CPlayer()
{
}
void CPlayer::Initialize()
{
SetPos(WinCX*0.5, WinCY*0.5);
SetSize(50,50);
ZeroMemory(&m_tAimInfo, sizeof(INFO));
SetObjType(PLAYER);
m_fSpeed = 5.0f;
m_fAtkRange = 70;
m_fRadian = 0;
m_iCount = 0;
m_iAnim = 0;
m_fAtkPower = 60;
m_bIsAttk = false;
m_fJumpForce = 20.0f;
m_bIsJump = false;
m_fJumpAcc = 0;
m_pImage = Image::FromFile(L"../Image/Player/Player6.bmp");
m_LocInfo = m_tInfo;
}
int CPlayer::Update()
{
m_iCount++;
if (IsDead() == DEAD_OBJ)
return DEAD_OBJ;
KeyInput();
Jump();
ScrollOffset();
if (GetIsAttk())
{
m_tInfo.fPosX += cosf(m_fRadian)*m_fAtkPower;
m_tInfo.fPosY -= sinf(m_fRadian)*m_fAtkPower;
if (m_iCount % 100)
{
m_bIsAttk = false;
}
}
return ALLIVE_OBJ;
}
void CPlayer::Render(HDC _hDC)
{
UpdateRect();
HDC hMemDC = CBmpMgr::GetInstance()->GetMemDC(L"Player");
NULL_CHECK(hMemDC);
//Rectangle(_hDC, m_tRect.left, m_tRect.top, m_tRect.right, m_tRect.bottom);
if (m_iCount % 13 == 0)
{
m_iAnim += 50;
if (m_iAnim >= 550)
m_iAnim = 0;
}
// Source DC에 그려진 비트맵을 Dest DC로 복사하는 함수. 이 때 지정한 색상을 제거할 수 있다.
GdiTransparentBlt(_hDC, (m_tRect.left)- m_tInfo.fCX*0.5-g_fScrollX, m_tRect.top- m_tInfo.fCY * 0.5, (int)m_tInfo.fCX*2, (int)m_tInfo.fCY*2,
hMemDC, m_iAnim, 0, (int)m_tInfo.fCX, (int)m_tInfo.fCY, RGB(0,0,0));
MoveToEx(_hDC, m_tInfo.fPosX-g_fScrollX, m_tInfo.fPosY, nullptr);
if (g_tArea.bStart)
{
LineTo(_hDC, g_tArea.ptStart.x, g_tArea.ptStart.y);
Rectangle(_hDC, m_tHitBox.left, m_tHitBox.top, m_tHitBox.right, m_tHitBox.bottom);
}
}
void CPlayer::KeyInput()
{
if (CKeyMgr::GetInstance()->KeyPressing(KEY_LEFT))
{
m_tInfo.fPosX -= m_fSpeed;
//g_fScrollX -= m_fSpeed;
//m_LocInfo.fPosX -= m_fSpeed;
}
if (CKeyMgr::GetInstance()->KeyPressing(KEY_RIGHT))
{
m_tInfo.fPosX += m_fSpeed;
//m_LocInfo.fPosX += m_fSpeed;
//g_fScrollX += m_fSpeed;
}
if (CKeyMgr::GetInstance()->KeyDown(KEY_SPACE))
{
m_bIsJump = true;
}
if (CKeyMgr::GetInstance()->KeyUp(KEY_SPACE))
{
m_bIsJump = false;
}
if (CKeyMgr::GetInstance()->KeyDown(KEY_LBUTTON))//공격
{
//if(!g_tArea.bStart)
SetAngle(g_tArea.ptStart.x, g_tArea.ptStart.y);
m_bIsAttk = true;
g_tArea.bStart = true;
}
if (CKeyMgr::GetInstance()->KeyUp(KEY_LBUTTON))//
{
g_tArea.bStart = false;
}
}
void CPlayer::Jump()
{
// 지형 충돌
float fY = m_tInfo.fPosY; //fY <= 바닥 높이
bool bIsColl = CLineMgr::GetInstance()->CollisionLine(this, &fY);
if (m_bIsJump)//상승
{
fLeftVal = m_fJumpForce * m_fJumpAcc;
fRightVal = GRAVITY * m_fJumpAcc * m_fJumpAcc * 0.5f;
m_tInfo.fPosY -= fLeftVal - fRightVal;
m_fJumpAcc += 0.3f;
if (m_tInfo.fPosY > fY)
{
m_tInfo.fPosY = fY-m_tInfo.fCY*0.5f;
m_fJumpAcc = 0;
}
}
else//하강
{
//cout << "PosY= "<<m_tInfo.fPosY <<"바닥= " <<fY - m_tInfo.fCY*0.5f << endl;
if (m_tInfo.fPosY >= fY - m_tInfo.fCY*0.5f-11)//바닥보다 아래에잇을때
{
m_tInfo.fPosY = fY - m_tInfo.fCY*0.5f;
m_fJumpAcc = 0;
}
else //위에
{
fRightVal = GRAVITY * m_fJumpAcc * m_fJumpAcc * 0.5f;
m_fJumpAcc += 0.3f;
m_tInfo.fPosY += fRightVal;
}
}
//if (m_bIsJump)
//{
// //자유 낙하 공식
// //y = 힘 * 가속도 * sin(90) - 중력(9.8) * 가속도^2 * 0.5
// float fLeftVal = m_fJumpForce * m_fJumpAcc;
// float fRightVal = GRAVITY * m_fJumpAcc * m_fJumpAcc * 0.5f;
// m_tInfo.fPosY -= fLeftVal - fRightVal;
// //착지할 때
// if (bIsColl && fLeftVal < fRightVal && m_tInfo.fPosY > fY - m_tInfo.fCY * 0.5f)
// {
// m_bIsJump = false;
// m_fJumpAcc = 0.f;
// m_tInfo.fPosY = fY - m_tInfo.fCY * 0.5f;
//
// }
//}
//else if (bIsColl)
//{
// m_tInfo.fPosY = fY - m_tInfo.fCY * 0.5f;
//}
}
void CPlayer::Attack()
{
cout << m_fDegree <<"도 " << endl;
if (m_fDegree >= -22.5 && m_fDegree < 22.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX),(LONG)(m_tInfo.fPosY- m_fAtkRange*0.5),(LONG)(m_tInfo.fPosX + m_fAtkRange), (LONG)(m_tInfo.fPosY + m_fAtkRange*0.5) };
else if (m_fDegree >= 22.5 && m_fDegree < 67.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX),(LONG)(m_tInfo.fPosY- m_fAtkRange), (LONG)(m_tInfo.fPosX + m_fAtkRange), (LONG)(m_tInfo.fPosY) };
else if (m_fDegree >= 67.5 && m_fDegree < 112.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX - m_fAtkRange*0.5),(LONG)(m_tInfo.fPosY - m_fAtkRange), (LONG)(m_tInfo.fPosX + m_fAtkRange*0.5),(LONG)(m_tInfo.fPosY) };
else if (m_fDegree >= 112.5 && m_fDegree < 157.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX - m_fAtkRange), (LONG)(m_tInfo.fPosY - m_fAtkRange),(LONG)(m_tInfo.fPosX), (LONG)m_tInfo.fPosY };
else if (m_fDegree >= 157.5 || m_fDegree < -157.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX - m_fAtkRange), (LONG)(m_tInfo.fPosY - m_fAtkRange*0.5), (LONG)(m_tInfo.fPosX), (LONG)(m_tInfo.fPosY+ m_fAtkRange*0.5) };
else if (m_fDegree <= -112.5 && m_fDegree > -157.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX - m_fAtkRange), (LONG)(m_tInfo.fPosY),(LONG)(m_tInfo.fPosX),(LONG)(m_tInfo.fPosY + m_fAtkRange) };
else if (m_fDegree <= -67.5 && m_fDegree > -112.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX - m_fAtkRange*0.5), (LONG)(m_tInfo.fPosY), (LONG)(m_tInfo.fPosX+ m_fAtkRange*0.5),(LONG)(m_tInfo.fPosY + m_fAtkRange) };
else if (m_fDegree <= -22.5 && m_fDegree > -67.5)
m_tHitBox = { (LONG)(m_tInfo.fPosX), (LONG)(m_tInfo.fPosY), (LONG)(m_tInfo.fPosX + m_fAtkRange), (LONG)(m_tInfo.fPosY + m_fAtkRange) };
}
void CPlayer::Release()
{
}
void CPlayer::ScrollOffset()
{
// 플레이어가 화면에서 일정 범위를 벗어났을 때 스크롤을 움직인다.
if (WinCX * 0.5f + 200.f <= m_tInfo.fPosX - g_fScrollX)
{
g_fScrollX += m_fSpeed;
//m_LocInfo.fPosX += m_fSpeed;
}
if (WinCX* 0.5f - 200.f >= m_tInfo.fPosX - g_fScrollX)
{
g_fScrollX -= m_fSpeed;
//m_LocInfo.fPosX += m_fSpeed;
}
}
|
de80ea3c10059fb87c64c1e5369b1522c3552f8e
|
19fc6e6c6767d91b37775f5707d1536df747369e
|
/mex/include/wildmagic-5.7/include/Wm5CubicPolynomialCurve3.h
|
f24e0c95c24051e0512a0c878e31e9eb5af3ca5c
|
[
"BSD-2-Clause"
] |
permissive
|
HanLab-BME-MTU/extern
|
ef062722ffc3877e5691bc46135d9ff56d7199e6
|
8f0ab6a554006ebc60e12b1595ecaafd0aec541b
|
refs/heads/master
| 2021-04-29T23:51:26.091473
| 2020-01-31T03:07:12
| 2020-01-31T03:07:12
| 121,562,896
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,805
|
h
|
Wm5CubicPolynomialCurve3.h
|
// Geometric Tools, LLC
// Copyright (c) 1998-2011
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.2 (2011/07/23)
#ifndef WM5CUBICPOLYNOMIALCURVE3_H
#define WM5CUBICPOLYNOMIALCURVE3_H
#include "Wm5MathematicsLIB.h"
#include "Wm5PolynomialCurve3.h"
namespace Wm5
{
template <typename Real>
class WM5_MATHEMATICS_ITEM CubicPolynomialCurve3
: public PolynomialCurve3<Real>
{
public:
// Construction and destruction. CubicPolynomialCurve3 accepts
// responsibility for deleting the input polynomials.
CubicPolynomialCurve3 (Polynomial1<Real>* xPoly,
Polynomial1<Real>* yPoly, Polynomial1<Real>* zPoly);
virtual ~CubicPolynomialCurve3 ();
// Tessellation data.
int GetNumVertices () const;
const Vector3<Real>* GetVertices () const;
Vector3<Real>* GetVertices ();
// Tessellation by recursive subdivision.
void Tessellate (int level);
protected:
using PolynomialCurve3<Real>::mTMin;
using PolynomialCurve3<Real>::mTMax;
using PolynomialCurve3<Real>::GetPosition;
using PolynomialCurve3<Real>::GetSecondDerivative;
// Support for precomputation.
class WM5_MATHEMATICS_ITEM IntervalParameters
{
public:
int I0, I1;
Vector3<Real> Xuu[2];
};
// Subdivide curve into two halves.
void Subdivide (int level, Real dsqr, Vector3<Real>* X,
IntervalParameters& IP);
// Tessellation data.
int mNumVertices;
Vector3<Real>* mVertices;
};
typedef CubicPolynomialCurve3<float> CubicPolynomialCurve3f;
typedef CubicPolynomialCurve3<double> CubicPolynomialCurve3d;
}
#endif
|
38269576992d165957fbb20a3b1832b45740991c
|
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
|
/EngineTesting/x64/ReleaseWindows/Resource/OutputCodeTesting/OutputCSVTestingFwd.h
|
054c0a674ae6d90f1aabc22c80fa2dc4a91621d2
|
[
"BSD-3-Clause"
] |
permissive
|
WuyangPeng/Engine
|
d5d81fd4ec18795679ce99552ab9809f3b205409
|
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
|
refs/heads/master
| 2023-08-17T17:01:41.765963
| 2023-08-16T07:27:05
| 2023-08-16T07:27:05
| 246,266,843
| 10
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 745
|
h
|
OutputCSVTestingFwd.h
|
/// Copyright (c) 2010-
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 自动生成
#ifndef OUTPUT_C_S_V_TESTING_FWD_H
#define OUTPUT_C_S_V_TESTING_FWD_H
#include "CoreTools/TextParsing/TextParsingFwd.h"
namespace OutputCSVTesting
{
class Input1;
class Input1Base;
class Input1Container;
using Input1MappingType = Input1Base;
class Input2;
class Input2Base;
class Input2Container;
using Input2MappingType = Input2Base;
class Input3;
class Input3Base;
class Input3Container;
using Input3MappingType = Input3Base;
class OutputCSVTestingContainer;
}
#endif // OUTPUT_C_S_V_TESTING_FWD_H
|
99cf5aa76312ec30d9bf013dcd627726378f7fc7
|
de2aa648e1193d508d9fba837e26088144599cd5
|
/Cognac.h
|
bf18cf5a199a6eb1b4801f30925e7ce48e7eaa25
|
[] |
no_license
|
vverenich/Drinks
|
54350310ff2964f1451e5e3971c47f4795fd863b
|
c4c565df0412aa550361d7e4fef2bb5116f291ba
|
refs/heads/master
| 2023-02-09T02:40:39.439893
| 2020-12-27T19:29:03
| 2020-12-27T19:29:03
| 324,828,896
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 381
|
h
|
Cognac.h
|
#ifndef MYCLASS_H4
#define MYCLASS_H4
#include "AlcoholicDrink.h"
#include<string>
enum class Grape {
UnyBlanc,
FoilBlanche,
Colombard,
Montil,
JurensonBlanc,
Semillon,
};
class Cognac : public AlcoholicDrink {
private:
Grape grape;
public:
Cognac(std::string nam, double volum, double streng, Grape g);
std::string GetGrape() const;
void SetGrape(Grape g);
};
#endif
|
dfd4bad02fc438c239a7c9151e10b17ae7f1de5c
|
9d02a593be808ccdb10039df110ddc050e3e88fa
|
/HW/HW6/3SAT.h
|
4109aff14896fff784a0adcadc339cbca72138f1
|
[] |
no_license
|
HO-COOH/CS4750
|
f57e15dad071edbd66334c74fc9191f2aa856787
|
a3f163edb2e4cb2aea4dce490c9b8acc4185b710
|
refs/heads/master
| 2020-07-17T03:28:48.097230
| 2020-02-06T11:45:08
| 2020-02-06T11:45:08
| 205,930,423
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,575
|
h
|
3SAT.h
|
#pragma once
#include <vector>
#include <string>
#include <list>
#include <queue>
#include <variant>
struct variable
{
size_t index;
bool value; //the value of the variable
std::vector<bool> remain = { true,false }; //the remaining value of the variable {T,F}
bool assigned = false; //assigned?
size_t degree = 0;
std::vector<std::pair<size_t, size_t>> appearance; //which clauses it is in and position(0,1,2)
bool operator<(const variable& v2) const
{
//if (remain.size() > v2.remain.size())
// return true;
//else if (remain.size() < v2.remain.size())
// return false;
//else
return degree < v2.degree;
}
};
struct SAT
{
size_t count = 3;
size_t vars[3];
bool sign[3]; //positive or negative
};
class Three_SAT
{
std::vector<variable> variables;
std::vector<SAT> constraints;
std::list<size_t> assignment;
std::list<size_t> unassigned;
bool satisfied(size_t clause_index) const; //Is the constraints[clause_index] satisfied? Used by IsConsistent()
public:
Three_SAT(const std::string& fileName);
variable& PickVar();
bool IsConsistent(variable& var, bool value);
void AssignVar(variable& var, bool value);
void UnassignVar(variable& var);
bool _checking(size_t clause_index) const;
size_t assignments;
/*Forward_checking*/
std::pair<std::vector<variable>, bool> Forward_Checking(variable& var);
void Restore(std::vector<variable>& modified);
/*DEBUG*/
bool IsFinished() const;
void PrintResult() const;
};
bool Recursive_Backtracking(Three_SAT& problem);
void BacktrackingSearch(Three_SAT& problem);
|
fee0dcc2dfbd5dca8330fd70f48eb6d28c7a146b
|
53c3fe38014ae2235502673d706d49848aae145e
|
/Stack.cpp
|
f7a49599abb4652b3d985da777ef2fbd699178fb
|
[] |
no_license
|
ifebles/notacion_polaca_inversa_itla
|
9c988310a05a2e19a04f1a409764c86c8aab73f4
|
de3abcd587b905490e4976865857204aa9901c91
|
refs/heads/master
| 2021-01-26T10:39:08.649304
| 2020-02-27T01:53:32
| 2020-02-27T01:53:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 968
|
cpp
|
Stack.cpp
|
#include <iostream>
#include "Stack.h"
using namespace std;
Stack::Stack() : _first(NULL), _count(0)
{ }
void Stack::push(double num)
{
Element* elem = new Element(num);
if(_first == NULL)
_first = elem;
else
{
elem->_next = _first;
_first = elem;
}
_count++;
}
double Stack::pop()
{
if(_first == NULL)
return 0;
double temp = _first->_val;
Element* elem = _first;
_first = _first->_next;
delete elem;
_count--;
return temp;
}
void Stack::clear()
{
if(_first == NULL)
return;
Element* elem = _first;
for(int x = 0; x < _count; x++)
{
Element* temp = elem;
elem = elem->_next;
delete temp;
}
/*int x = 0;
while(elem != NULL)
{
cout << "Cantidad de iteraciones: " << ++x << endl;
cout << "Cantidad en la pila: " << _count << endl;
cout << "elem == NULL: " << (elem == NULL) << endl;
Element* temp = elem;
elem = elem->_next;
delete temp;
cout << "Eliminado en iteracion " << x << endl;
}*/
_count = 0;
}
|
807f7787257c7b4932ef0b904e5750eef1449975
|
d5749c8baa3c653f7fb8a6006a0776306cd3cfca
|
/test1.cpp
|
290c17c8a6d3cdf3c23e1b590be68b12e4983bd9
|
[] |
no_license
|
kupull74/test_c--
|
dd2d714501924a3592a9af121c425a09ffc94f4b
|
06567488268cdcde1f23c84e439f4e2e4e2ab095
|
refs/heads/master
| 2023-01-23T03:57:31.883412
| 2020-11-27T01:14:39
| 2020-11-27T01:14:39
| 311,860,275
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 846
|
cpp
|
test1.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <ncurses.h>
#include <string.h>
int main()
{
initscr(); // curses 초기화
WINDOW *w;
w = initscr();
curs_set(1); // 커서 보이게 하는 옵션..?
using namespace std;
noecho(); // ?? 일단 넣어봤음
cbreak(); //?
box(w, 0, 0); // 안의 숫자 바꾸면 라인 형태 바뀜
int i, j, m, n;
int rows, cols, rows1, cols1;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
mvprintw(i, j, "");
for (m <= 0; m < rows - 5; m++)
{
for (n <= 0; n < cols - 5; n++)
{
mvprintw(m, n, "");
// WINDOW * win = newwin(m, n, rows1, cols1);
// initscr();
}
}
getch(); // end main
endwin();
return 0;
}
}
}
|
62717aa3a1b523f06a8a1c75aac32a459ab8967c
|
a721f9d0543faa7b1a78660e8985f6753ed95f2c
|
/804.唯一摩尔斯密码词.cpp
|
911e4dfaee744a0b6da2b5f0c714d1999a6c2c04
|
[] |
no_license
|
fflq/LeetCode
|
c510bc8763df013d1bff3069815ae6d86c615c2c
|
21ddf5e1090ec288b251b9153ed164fc5b7a7f2d
|
refs/heads/main
| 2023-04-20T14:52:01.123621
| 2021-03-12T02:28:01
| 2021-03-12T02:28:01
| 346,647,663
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 648
|
cpp
|
804.唯一摩尔斯密码词.cpp
|
/*
* @lc app=leetcode.cn id=804 lang=cpp
*
* [804] 唯一摩尔斯密码词
*/
#ifdef FLQ
#include "heads.h"
#endif
// @lc code=start
class Solution {
public:
vector<string> dict = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."} ;
int uniqueMorseRepresentations(vector<string>& words) {
set<string> sets ;
for (auto s : words) {
string ss = "" ;
for (auto c : s) ss += dict[c-'a'] ;
sets.insert(ss) ;
}
return sets.size() ;
}
};
// @lc code=end
|
9dedec9f81a7d51583fc72e0b9dad88a6c06bb63
|
adc999db9af574e6e5f87e73b06c9d7fc4d23c79
|
/ReaderWriter/ReaderWriter/Source.cpp
|
2b0ec0264190700de7571db57b7dd03dc80cebb1
|
[] |
no_license
|
C00192124/GamesEngineering
|
fc82a092a5619aee1a83b1249d454783020b2c7c
|
3909ac8018a1649d362f02e4f11e8ea11bb91b78
|
refs/heads/master
| 2021-09-10T09:10:22.943291
| 2018-03-23T09:33:54
| 2018-03-23T09:33:54
| 103,931,254
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,447
|
cpp
|
Source.cpp
|
#pragma once
#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include <mutex>
#include <condition_variable>
using namespace std;
struct Semaphore
{
public:
int m_lock = 1;
mutex m_mutex;
condition_variable m_con;
};
void Reader();
void Writer();
void P(Semaphore &s);
void V(Semaphore &s);
//lock for reader
Semaphore readerSem;
//lock for db
Semaphore dbSem;
int readerCount = 0;
void main()
{
thread tReader(Reader);
thread tWriter(Writer);
thread tReader2(Reader);
thread tWriter2(Writer);
tReader.join();
tWriter.join();
tReader2.join();
tWriter2.join();
}
void Reader()
{
bool running = true;
while (running)
{
P(readerSem);
readerCount += 1;
if (readerCount == 1)
{
cout << "reading..." << endl;
P(dbSem);
}
V(readerSem);
P(readerSem);
readerCount -= 1;
if (readerCount == 0)
{
cout << "reader finished" << endl;
V(dbSem);
}
V(readerSem);
this_thread::sleep_for(chrono::seconds(1));
}
}
void Writer()
{
bool running = true;
while (running)
{
P(dbSem);
cout << "writing..." << endl;
cout << "writer finished" << endl;
V(dbSem);
this_thread::sleep_for(chrono::seconds(1));
}
}
//Try
void P(Semaphore &s)
{
unique_lock<mutex> lock(s.m_mutex);
while (s.m_lock <= 0)
{
s.m_con.wait(lock);
}
s.m_lock -= 1;
}
//Increment
void V(Semaphore &s)
{
unique_lock<mutex> lock(s.m_mutex);
s.m_lock += 1;
s.m_con.notify_one();
}
|
05b158004bec4d0e8bd2706dae45a2a632ef43bd
|
d669decf6a6537d3c2e5cd092629fdd7f77f6419
|
/requests/src/main.cpp
|
0137e655d467ea55b360784e7a9a018116d29d39
|
[] |
no_license
|
dariaomelkina/parallel-crawling-research
|
4a2a7eacddbd65952f7db146e5359d3fd9b61f7b
|
9b794b7d282e21e7839d3d67abed0c0de22849d6
|
refs/heads/main
| 2023-07-03T16:27:15.888363
| 2021-08-12T22:45:26
| 2021-08-12T22:45:26
| 362,185,582
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 469
|
cpp
|
main.cpp
|
#include <iostream>
#include "requests.h"
/* For testing and demonstration purposes. */
int main() {
std::string url = "http://google.com/";
std::string additional_params = "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36\r\n";
char buffer[5000];
std::cout << get_html(buffer, 5000, url, additional_params) << std::endl;
std::cout << buffer << std::endl;
return 0;
}
|
23a74808179f89a2263ffa8b8279c94b09a309e5
|
ae672d17c4a8eb1143b7091b8988d6b16778f936
|
/T/satori.cxx
|
40b6d83e2a65da72378a4fafd8cca1d03f5589f3
|
[] |
no_license
|
Maciej-Poleski/ASD2
|
5797266bfcbde6def703b0dfc5d3af747c7ef5e8
|
a9724046fabf514105ff81b0e42f448f1f699a21
|
refs/heads/master
| 2023-04-18T09:54:07.455397
| 2013-06-13T19:26:21
| 2013-06-13T19:26:21
| 363,194,562
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,599
|
cxx
|
satori.cxx
|
//Maciej Poleski
#ifdef DEBUG
#define _GLIBCXX_CONCEPT_CHECKS
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cassert>
namespace
{
namespace Wrapper
{
std::ifstream in;
std::ofstream out;
}
void init(int argc, char **argv)
{
if (argc != 3) {
std::cerr << "Potrzeba dokładnie dwóch argumentów\n";
std::abort();
}
Wrapper::in.open(argv[1]);
Wrapper::out.open(argv[2]);
}
}
#define check(x) assert(x)
#else
#ifndef NDEBUG
#define NDEBUG
#endif
#define check(x)
#include <iostream>
namespace
{
namespace Wrapper
{
std::istream &in = std::cin;
std::ostream &out = std::cout;
}
}
#endif
#include <tr1/cstdint>
namespace
{
namespace Wrapper
{
typedef std::tr1::uint_fast64_t uint_fast64_t;
typedef std::tr1::uint_fast32_t uint_fast32_t;
typedef std::tr1::uint_fast16_t uint_fast16_t;
typedef std::tr1::uint_fast8_t uint_fast8_t;
typedef std::tr1::uint64_t uint64_t;
typedef std::tr1::uint32_t uint32_t;
typedef std::tr1::uint16_t uint16_t;
typedef std::tr1::uint8_t uint8_t;
typedef std::tr1::int_fast64_t int_fast64_t;
typedef std::tr1::int_fast32_t int_fast32_t;
typedef std::tr1::int_fast16_t int_fast16_t;
typedef std::tr1::int_fast8_t int_fast8_t;
typedef std::tr1::int64_t int64_t;
typedef std::tr1::int32_t int32_t;
typedef std::tr1::int16_t int16_t;
typedef std::tr1::int8_t int8_t;
typedef std::size_t size_t;
}
}
#include <string>
#include <algorithm>
#include <limits>
#include <locale>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <tr1/random>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <list>
#include <iomanip>
#include <set>
#include <map>
#include <tr1/memory>
#include <tr1/functional>
#include <tr1/unordered_map>
#include <tr1/unordered_set>
#include <complex>
namespace
{
using namespace Wrapper;
template<typename T,class Compare = std::less<T> >
class LeftistTree : public std::tr1::enable_shared_from_this<LeftistTree<T,Compare> >
{
struct Node
{
friend class LeftistTree<T,Compare>;
private:
Node() : left(0), right(0),s(1) {}
Node(const T &value) : left(0), right(0),s(1),value(value) {}
Node(const Node &) = delete;
Node & operator=(const Node &) = delete;
~Node()
{
delete left;
delete right;
}
static Node * merge(Node *a,Node *b);
private:
Node *left,*right;
size_t s;
T value;
};
public:
LeftistTree() : root(0) {}
~LeftistTree()
{
delete root;
}
LeftistTree(const LeftistTree&) = delete;
LeftistTree & operator=(const LeftistTree&)=delete;
bool isEmpty() const
{
return root==0;
}
T getMin() const
{
return root->value;
}
void swap(LeftistTree &v)
{
Node *t=root;
root=v.root;
v.root=t;
}
std::tr1::shared_ptr<LeftistTree<T,Compare> > merge(std::tr1::shared_ptr<LeftistTree<T,Compare> > rhs);
void deleteMin();
void insert(const T &value);
private:
LeftistTree(Node *root) : root(root) {}
static std::tr1::shared_ptr<LeftistTree<T,Compare> >
merge(std::tr1::shared_ptr<LeftistTree<T,Compare> > lhs,
std::tr1::shared_ptr<LeftistTree<T,Compare> > rhs);
private:
Node *root;
};
template<typename T,class Compare >
std::tr1::shared_ptr<LeftistTree<T,Compare> >
merge(std::tr1::shared_ptr<LeftistTree<T,Compare> > lhs,
std::tr1::shared_ptr<LeftistTree<T,Compare> > rhs)
{
return lhs.merge(rhs);
}
template<typename T,class Compare>
void swap(LeftistTree<T,Compare> &lhs,LeftistTree<T,Compare> &rhs)
{
lhs.swap(rhs);
}
template<typename T,class Compare >
std::tr1::shared_ptr<LeftistTree<T,Compare> >
LeftistTree<T,Compare>::merge(std::tr1::shared_ptr<LeftistTree<T,Compare> > rhs)
{
using std::swap;
std::tr1::shared_ptr<LeftistTree<T,Compare> > t = LeftistTree<T,Compare>::merge(this->shared_from_this(),rhs);
swap(*this,*t);
return this->shared_from_this();
}
template<typename T,class Compare>
void LeftistTree<T,Compare>::deleteMin()
{
check(root);
Node *left=root->left;
Node *right=root->right;
root->left=0;
root->right=0;
delete root;
root=0;
if(left==0)
root=right;
else if(right==0)
root=left;
else
{
using std::swap;
std::tr1::shared_ptr<LeftistTree<T,Compare> > l(new LeftistTree<T,Compare>(left));
std::tr1::shared_ptr<LeftistTree<T,Compare> > r(new LeftistTree<T,Compare>(right));
std::tr1::shared_ptr<LeftistTree<T,Compare> > t(merge(l,r));
swap(*this,*t);
}
}
template<typename T,class Compare >
void LeftistTree<T,Compare>::insert(const T& value)
{
Node *node=new Node;
node->value=value;
std::tr1::shared_ptr<LeftistTree<T,Compare> > t(new LeftistTree<T,Compare>(node));
merge(t);
}
template<typename T,class Compare >
std::tr1::shared_ptr<LeftistTree<T,Compare> >
LeftistTree<T,Compare>::merge(std::tr1::shared_ptr<LeftistTree<T,Compare> > lhs,
std::tr1::shared_ptr<LeftistTree<T,Compare> > rhs)
{
if(lhs==rhs)
return lhs;
std::tr1::shared_ptr<LeftistTree<T,Compare> > result(new LeftistTree<T,Compare>(Node::merge(lhs->root,rhs->root)));
lhs->root=0;
rhs->root=0;
return result;
}
template<typename T,class Compare>
typename LeftistTree<T,Compare>::Node* LeftistTree<T,Compare>::Node::merge(Node* a, Node* b)
{
using std::swap;
if(a==0)
return b;
else if(b==0)
return a;
check(a);
check(b);
Compare comp;
if(comp(b->value,a->value))
swap(a,b);
a->right=merge(a->right,b);
if((a->left==0) ||( (a->right!=0) && (a->left->s < a->right->s)))
swap(a->left,a->right);
a->s=(a->right?a->right->s:0)+1;
return a;
}
struct Curve
{
uint16_t left,right;
uint16_t id;
uint8_t color;
bool onStack;
std::vector<uint16_t> edges;
Curve() : color(255),onStack(false) {}
};
static Curve *G;
static size_t n,k;
const bool operator<(const Curve &lhs,const Curve &rhs) __attribute__((pure));
const bool operator<(const Curve &lhs,const Curve &rhs)
{
return (lhs.left<rhs.left) || ((lhs.left==rhs.left) && (lhs.right>rhs.right));
}
struct CurvePtrComp
{
const bool operator()(const Curve * const &lhs,const Curve * const &rhs) const
{
return lhs->right<rhs->right;
}
};
static void makeColor(uint16_t k,uint8_t color)
{
if(G[k].color!=255)
return;
G[k].color=color;
for(std::vector<uint16_t>::const_iterator i=G[k].edges.begin(),e=G[k].edges.end(); i!=e; ++i)
{
makeColor(*i,color^1);
}
}
struct CurveComp
{
const bool operator()(const Curve &lhs,const Curve &rhs) const
{
return lhs.id<rhs.id;
}
};
struct Event
{
uint16_t id;
bool right;
};
const bool operator==(const Event &lhs,const Event &rhs)
{
return (lhs.id==rhs.id) && (lhs.right==rhs.right);
}
const bool operator<(const Event &lhs,const Event &rhs)
{
if(lhs==rhs)
return false;
uint16_t l=lhs.right?G[lhs.id].right:G[lhs.id].left;
uint16_t r=rhs.right?G[rhs.id].right:G[rhs.id].left;
if(l!=r)
return l<r;
if(lhs.right!=rhs.right)
return lhs.right;
bool c=G[lhs.id]<G[rhs.id];
if(!lhs.right)
return c;
else
return !c;
}
inline static void solution()
{
using std::swap;
std::tr1::uint_fast32_t z;
in >> z;
//z=1;
while (z--) {
in>>n>>k;
G=new Curve[k];
for(size_t i=0; i<k; ++i)
{
uint16_t a,b;
in>>a>>b;
G[i].left=a;
G[i].right=b;
G[i].id=i;
}
std::sort(G,G+k);
typedef std::tr1::shared_ptr<LeftistTree<Curve*,CurvePtrComp> > TreePtr;
std::stack<TreePtr> stack;
for(size_t i=0; i<k; ++i)
{
while(!stack.empty())
{
TreePtr tree=stack.top();
while(!tree->isEmpty())
{
if(tree->getMin()->right<=G[i].left)
tree->deleteMin();
else
break;
}
if(tree->isEmpty())
stack.pop();
else
break;
}
TreePtr newConnectedComponent(new LeftistTree<Curve*,CurvePtrComp>());
newConnectedComponent->insert(&G[i]);
while(!stack.empty())
{
TreePtr tree=stack.top();
if(tree->getMin()->right<G[i].right)
{
G[i].edges.push_back(tree->getMin()-G);
G[tree->getMin()-G].edges.push_back(i);
newConnectedComponent->merge(tree);
stack.pop();
}
else
break;
}
stack.push(newConnectedComponent);
}
for(size_t i=0; i<k; ++i)
makeColor(i,0);
std::vector<Event> events[2];
for(size_t i=0; i<k; ++i)
{
check(G[i].color==0 || G[i].color==1);
events[G[i].color].push_back({i,false});
events[G[i].color].push_back({i,true});
}
std::sort(events[0].begin(),events[0].end());
std::sort(events[1].begin(),events[1].end());
bool ok=true;
for(size_t q=0; q<2 && ok; ++q)
{
std::stack<uint16_t> stack;
for(std::vector<Event>::const_iterator i=events[q].begin(),e=events[q].end(); i!=e && ok; ++i)
{
if(G[i->id].onStack)
{
if(stack.top()==i->id)
{
stack.pop();
}
else
{
ok=false;
}
}
else
{
stack.push(i->id);
G[i->id].onStack=true;
}
}
}
std::sort(G,G+k,CurveComp());
if(ok)
for(size_t i=0; i<k; ++i)
{
out<<(G[i].color==0?"N\n":"S\n");
}
else
out<<"NIE\n";
delete [] G;
}
}
} // namespace
int main(int argc, char **argv)
{
std::ios_base::sync_with_stdio(false);
#ifdef DEBUG
init(argc, argv);
#else
(void)argc;
(void)argv;
#endif
solution();
return 0;
}
|
5438abd534d05391a723287b1280fef4813423b2
|
c904606638a9e3ccc7f9e2142848f4c041d404dd
|
/engine/core/main/plugin.cpp
|
477337331a76e7373606eb81813692c98bd191c7
|
[
"MIT"
] |
permissive
|
Geniok/echo
|
bd367238cbe3fad6b6a3f3b675ba2c19ca9444f8
|
5b65c438739c040d04117308e8eac1e2805890a6
|
refs/heads/master
| 2020-04-24T01:48:05.430729
| 2019-02-20T05:11:02
| 2019-02-20T05:11:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,044
|
cpp
|
plugin.cpp
|
#include "Plugin.h"
#include "engine/core/util/PathUtil.h"
#include "engine/core/log/Log.h"
#ifdef ECHO_PLATFORM_WINDOWS
#define DYNLIB_HANDLE HMODULE
#define DYNLIB_LOAD( a) LoadLibraryEx( a, NULL, LOAD_WITH_ALTERED_SEARCH_PATH)
#define DYNLIB_GETSYM( a, b) GetProcAddress( a, b)
#define DYNLIB_UNLOAD( a) FreeLibrary( a)
#else
#include <dlfcn.h>
#define DYNLIB_HANDLE void*
#define DYNLIB_LOAD( a) dlopen( a, RTLD_LOCAL|RTLD_LAZY)
#define DYNLIB_GETSYM( handle, symbolName) dlsym( handle, symbolName)
#define DYNLIB_UNLOAD( a) dlclose( a)
#endif
namespace Echo
{
// plugins
static map<String, Plugin*>::type g_plugins;
Plugin::Plugin()
{
}
Plugin::~Plugin()
{
}
void Plugin::load(const char* path)
{
m_handle = DYNLIB_LOAD(path);
}
void Plugin::unload()
{
DYNLIB_UNLOAD(m_handle);
}
void* Plugin::getSymbol(const char* symbolName)
{
return (void*)DYNLIB_GETSYM(m_handle, symbolName);
}
void Plugin::loadAllPlugins()
{
#ifdef ECHO_EDITOR_MODE
typedef bool(*LOAD_PLUGIN_FUN)();
// get plugin path
String pluginDir = PathUtil::GetCurrentDir() + "/plugins";
PathUtil::FormatPath(pluginDir, false);
// get all plugins
StringArray plugins;
PathUtil::EnumFilesInDir( plugins, pluginDir, false, false, true);
// iterate
for (String& pluginPath : plugins)
{
String ext = PathUtil::GetFileExt(pluginPath, true);
if(ext==".dll" || ext==".dylib")
{
String name = StringUtil::Replace(PathUtil::GetPureFilename(pluginPath, false), "lib", "");
String symbolName = StringUtil::Format("load%sPlugin", name.c_str());
Plugin* plugin = EchoNew(Plugin);
plugin->load(pluginPath.c_str());
LOAD_PLUGIN_FUN pFunc = (LOAD_PLUGIN_FUN)plugin->getSymbol(symbolName.c_str());
if (pFunc)
{
(*pFunc)();
}
else
{
EchoLogError("Can't find symbol %s in plugin [%s]", symbolName.c_str(), pluginPath.c_str());
}
g_plugins[name] = plugin;
}
}
#endif
}
}
|
de3e1ba75a6c36d64557c5e02d394a805eb8a434
|
a33aac97878b2cb15677be26e308cbc46e2862d2
|
/program_data/PKU_raw/78/1736.c
|
b2a0e1eca80063a8bcaecb9ea42a6184161622ae
|
[] |
no_license
|
GabeOchieng/ggnn.tensorflow
|
f5d7d0bca52258336fc12c9de6ae38223f28f786
|
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
|
refs/heads/master
| 2022-05-30T11:17:42.278048
| 2020-05-02T11:33:31
| 2020-05-02T11:33:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 893
|
c
|
1736.c
|
int compare (int z, int q, int s, int l, int i)
{
int a[4] = {z, q, s, l};
int j, k, t;
for (j = 4; j > 0; j--)
for (k = 1; k < j; k++)
{
if(a[k] > a[k - 1])
{
t = a[k];
a[k] = a[k - 1];
a[k - 1] = t;
}
}
return (a[i - 1]);
}
int fout( int z, int q, int s, int l, int sum)
{
if(sum == z) cout << "z";
if(sum == q) cout << "q";
if(sum == s) cout << "s";
if(sum == l) cout << "l";
return 0;
}
int main()
{
int z, q, s, l, i, sum;
for(z = 10; z < 60; z += 10)
for(q = 10; q < 60; q += 10)
for(s = 10; s < 60; s += 10)
for(l = 10; l < 60; l += 10)
if( (z - q) * (z - s) * (z - l) * (q - s) * (q - l) * (s - l) != 0
&& z + q == s + l
&& z + l > s + q
&& z + s < q )
{
for(i = 1; i <= 4; i++)
{
sum = compare(z, q, s, l, i);
fout(z, q, s, l, sum);
cout << " " << sum <<endl;
}
}
return 0;
}
|
ffb5604802864ea6f733c88e481ba05aa3da82e0
|
6ffd23679939f59f0a09c9507a126ba056b239d7
|
/dnn/test/cuda/region_restricted_convolution.cpp
|
db10790c532fd225e191708e296243a661dee100
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
MegEngine/MegEngine
|
74c1c9b6022c858962caf7f27e6f65220739999f
|
66b79160d35b2710c00befede0c3fd729109e474
|
refs/heads/master
| 2023-08-23T20:01:32.476848
| 2023-08-01T07:12:01
| 2023-08-11T06:04:12
| 248,175,118
| 5,697
| 585
|
Apache-2.0
| 2023-07-19T05:11:07
| 2020-03-18T08:21:58
|
C++
|
UTF-8
|
C++
| false
| false
| 44,841
|
cpp
|
region_restricted_convolution.cpp
|
#include "megdnn/dtype.h"
#include "megdnn/opr_param_defs.h"
#include "megdnn/oprs.h"
#include "megdnn/oprs/nn.h"
#include "test/common/checker.h"
#include "test/common/conv_bias.h"
#include "test/common/rng.h"
#include "test/common/tensor.h"
#include "test/common/workspace_wrapper.h"
#include "test/cuda/benchmark.h"
#include "test/cuda/fixture.h"
#include "test/cuda/utils.h"
#include <cudnn.h>
#include <gtest/gtest.h>
#define V1(x) #x
#define V(x) V1(x)
#define CUDNN_VERSION_STRING \
"v" V(CUDNN_MAJOR) "." V(CUDNN_MINOR) "." V(CUDNN_PATCHLEVEL)
namespace megdnn {
namespace test {
TEST_F(CUDA, REGION_RESTRICTED_CONV_FORWARD_LARGE_FILTER) {
Checker<RegionRestrictedConvolutionForward> checker(handle_cuda());
auto opr = handle_cuda()->create_operator<ConvolutionForward>();
for (auto dt : std::vector<DType>{dtype::Int32(), dtype::Uint8()}) {
auto run = [&checker, &dt, &opr](
size_t n, size_t g, size_t h, size_t fh, size_t padding,
size_t stride) {
RegionRestrictedConvolution::Param cur_param;
cur_param.mode =
RegionRestrictedConvolution::Param::Mode::CROSS_CORRELATION;
cur_param.sparse = RegionRestrictedConvolution::Param::Sparse::GROUP;
checker.set_dtype(2, dt).set_dtype(3, dt);
float scale = 64.f / sqrt(fh * fh);
UniformFloatRNG rng(scale, 2 * scale);
UniformIntRNG r_rng{0, 2};
checker.set_rng(0, &rng).set_rng(1, &rng).set_rng(2, &r_rng).set_rng(
3, &r_rng);
cur_param.pad_h = cur_param.pad_w = padding;
cur_param.stride_h = cur_param.stride_w = stride;
size_t ho = infer_conv_shape(h, fh, stride, padding);
checker.set_param(cur_param).execs(
{{n, g, h, h}, {g, 1, 1, fh, fh}, {n, h, h}, {n, ho, ho}, {}});
};
run(1, 1, 3, 2, 1, 1);
run(1, 1, 5, 2, 1, 1);
run(1, 1, 6, 2, 1, 1);
run(1, 1, 7, 2, 1, 1);
run(1, 1, 9, 2, 1, 1);
run(1, 1, 10, 2, 1, 1);
run(1, 1, 11, 2, 1, 1);
run(1, 1, 13, 2, 1, 1);
run(1, 1, 14, 2, 1, 1);
run(1, 1, 15, 2, 1, 1);
run(1, 1, 17, 2, 1, 1);
run(1, 1, 18, 2, 1, 1);
run(1, 1, 19, 2, 1, 1);
run(1, 1, 21, 2, 1, 1);
run(1, 1, 22, 2, 1, 1);
run(1, 1, 23, 2, 1, 1);
run(1, 1, 25, 2, 1, 1);
run(1, 1, 26, 2, 1, 1);
run(1, 1, 27, 2, 1, 1);
run(1, 1, 29, 2, 1, 1);
run(1, 1, 30, 2, 1, 1);
run(1, 1, 31, 2, 1, 1);
run(4, 8, 32, 3, 3 / 2, 1);
run(4, 8, 32, 5, 5 / 2, 1);
run(4, 8, 32, 7, 7 / 2, 1);
run(4, 8, 32, 9, 9 / 2, 1);
run(4, 8, 32, 11, 11 / 2, 1);
run(4, 8, 32, 13, 13 / 2, 1);
run(4, 8, 32, 15, 15 / 2, 1);
run(4, 8, 32, 17, 17 / 2, 1);
run(4, 8, 32, 19, 19 / 2, 1);
run(4, 8, 32, 21, 21 / 2, 1);
run(4, 8, 32, 23, 23 / 2, 1);
run(4, 8, 32, 25, 25 / 2, 1);
run(4, 8, 32, 27, 27 / 2, 1);
run(4, 8, 32, 29, 29 / 2, 1);
run(4, 8, 32, 31, 31 / 2, 1);
run(4, 8, 31, 3, 3 / 2, 1);
run(4, 8, 31, 5, 5 / 2, 1);
run(4, 8, 31, 7, 7 / 2, 1);
run(4, 8, 31, 9, 9 / 2, 1);
run(4, 8, 31, 11, 11 / 2, 1);
run(4, 8, 31, 13, 13 / 2, 1);
run(4, 8, 31, 15, 15 / 2, 1);
run(4, 8, 31, 17, 17 / 2, 1);
run(4, 8, 31, 19, 19 / 2, 1);
run(4, 8, 31, 21, 21 / 2, 1);
run(4, 8, 31, 23, 23 / 2, 1);
run(4, 8, 31, 25, 25 / 2, 1);
run(4, 8, 31, 27, 27 / 2, 1);
run(4, 8, 31, 29, 29 / 2, 1);
run(4, 8, 31, 31, 31 / 2, 1);
}
}
#if MEGDNN_WITH_BENCHMARK
TEST_F(CUDA, BENCHMARK_REGION_RESTRICTED_CONV_FORWARD_LARGE_FILTER_FP32_INT32) {
require_compute_capability(7, 5);
Benchmarker<ConvBiasForward> bencher(handle_cuda());
bencher.set_display(false);
bencher.set_before_exec_callback(conv_bias::ConvBiasAlgoChecker<ConvBiasForward>(
ConvBiasForward::algo_name<ConvBiasForward::DirectParam>(
"DEPTHWISE_LARGE_FILTER", {})
.c_str()));
Benchmarker<RegionRestrictedConvolutionForward> rr_bencher(handle_cuda());
rr_bencher.set_display(false);
ConvBias::Param param;
param.format = ConvBias::Param::Format::NCHW;
using NonlineMode = ConvBias::Param::NonlineMode;
param.nonlineMode = NonlineMode::IDENTITY;
param.sparse = ConvBias::Param::Sparse::GROUP;
RegionRestrictedConvolutionForward::Param rr_param;
rr_param.format = RegionRestrictedConvolutionForward::Param::Format::NCHW;
rr_param.sparse = RegionRestrictedConvolutionForward::Param::Sparse::GROUP;
UniformIntRNG r_rng{0, 2};
auto run_bench = [&](size_t batch, size_t g, size_t hi, size_t wi, size_t fh,
size_t fw, size_t sh, size_t sw, size_t nr_times) {
param.pad_h = fh / 2;
param.pad_w = fw / 2;
param.stride_h = sh;
param.stride_w = sw;
rr_param.pad_h = fh / 2;
rr_param.pad_w = fw / 2;
rr_param.stride_h = sh;
rr_param.stride_w = sw;
bencher.set_param(param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Float32())
.set_dtype(4, dtype::Float32());
bencher.set_times(nr_times);
rr_bencher.set_param(rr_param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Int32())
.set_dtype(3, dtype::Int32());
rr_bencher.set_rng(2, &r_rng).set_rng(3, &r_rng);
rr_bencher.set_times(nr_times);
size_t ho = infer_conv_shape(hi, fh, sh, param.pad_h);
size_t wo = infer_conv_shape(wi, fw, sw, param.pad_w);
TensorShape inp{batch, g, hi, wi}, kern{g, 1, 1, fh, fw}, rin{batch, hi, wi},
rout{batch, ho, wo}, out{batch, g, ho, wo};
float bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
float rr_bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
rin.total_nr_elems() + rout.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
auto time_in_ms = bencher.execs({inp, kern, {}, {}, out}) / nr_times;
auto ops = 2.0 * batch * g * ho * wo * fh * fw / (time_in_ms * 1e-3) * 1e-12;
auto rr_time_in_ms = rr_bencher.execs({inp, kern, rin, rout, out}) / nr_times;
auto rr_ops =
2.0 * batch * g * ho * wo * fh * fw / (rr_time_in_ms * 1e-3) * 1e-12;
printf("RegionRestrictedDepthwiseLargeFilter vs DepthwiseLargeFilter: inp=%s, "
"kern=%s, out=%s\n"
"time: %.2f ms, time(rr): %.2f ms, perf: %.2fTops, perf(rr): %.2f Tops\n"
"bandwidth: %.2fGB/s, bandwidth(rr): %.2fGB/s, speedup: %.2f.\n",
inp.to_string().c_str(), kern.to_string().c_str(),
out.to_string().c_str(), time_in_ms, rr_time_in_ms, ops, rr_ops,
bandwith * 4 / time_in_ms, rr_bandwith * 4 / rr_time_in_ms,
time_in_ms / rr_time_in_ms);
};
run_bench(64, 384, 32, 32, 3, 3, 1, 1, 1000);
run_bench(64, 384, 32, 32, 5, 5, 1, 1, 1000);
run_bench(64, 384, 32, 32, 7, 7, 1, 1, 1000);
run_bench(64, 384, 32, 32, 9, 9, 1, 1, 1000);
run_bench(64, 384, 32, 32, 11, 11, 1, 1, 1000);
run_bench(64, 384, 32, 32, 13, 13, 1, 1, 1000);
run_bench(64, 384, 32, 32, 15, 15, 1, 1, 1000);
run_bench(64, 384, 32, 32, 17, 17, 1, 1, 1000);
run_bench(64, 384, 32, 32, 19, 19, 1, 1, 1000);
run_bench(64, 384, 32, 32, 21, 21, 1, 1, 1000);
run_bench(64, 384, 32, 32, 23, 23, 1, 1, 1000);
run_bench(64, 384, 32, 32, 25, 25, 1, 1, 1000);
run_bench(64, 384, 32, 32, 27, 27, 1, 1, 1000);
run_bench(64, 384, 32, 32, 29, 29, 1, 1, 1000);
run_bench(64, 384, 32, 32, 31, 31, 1, 1, 1000);
}
TEST_F(CUDA, BENCHMARK_REGION_RESTRICTED_CONV_BACKWARD_DATA_FP32_INT32) {
require_compute_capability(7, 5);
Benchmarker<ConvolutionBackwardData> bencher(handle_cuda());
bencher.set_display(false);
bencher.set_before_exec_callback(
AlgoChecker<ConvolutionBackwardData>("DEPTHWISE_LARGE_FILTER"));
Benchmarker<RegionRestrictedConvolutionBackwardData> rr_bencher(handle_cuda());
rr_bencher.set_display(false);
ConvolutionBackwardData::Param param;
param.format = ConvolutionBackwardData::Param::Format::NCHW;
param.sparse = ConvolutionBackwardData::Param::Sparse::GROUP;
RegionRestrictedConvolutionBackwardData::Param rr_param;
rr_param.format = RegionRestrictedConvolutionBackwardData::Param::Format::NCHW;
rr_param.sparse = RegionRestrictedConvolutionBackwardData::Param::Sparse::GROUP;
UniformIntRNG r_rng{1, 3};
auto run_bench = [&](size_t batch, size_t g, size_t hi, size_t wi, size_t fh,
size_t fw, size_t sh, size_t sw, size_t nr_times) {
param.pad_h = fh / 2;
param.pad_w = fw / 2;
param.stride_h = sh;
param.stride_w = sw;
rr_param.pad_h = fh / 2;
rr_param.pad_w = fw / 2;
rr_param.stride_h = sh;
rr_param.stride_w = sw;
bencher.set_param(param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Float32())
.set_dtype(4, dtype::Float32());
bencher.set_times(nr_times);
rr_bencher.set_param(rr_param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Int32())
.set_dtype(3, dtype::Int32());
rr_bencher.set_rng(2, &r_rng).set_rng(3, &r_rng);
rr_bencher.set_times(nr_times);
size_t ho = infer_conv_shape(hi, fh, sh, param.pad_h);
size_t wo = infer_conv_shape(wi, fw, sw, param.pad_w);
TensorShape inp{batch, g, hi, wi} /*src*/, kern{g, 1, 1, fh, fw} /*filter*/,
rin{batch, hi, wi}, rout{batch, ho, wo},
out{batch, g, ho, wo} /*output*/;
float bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
float rr_bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
rin.total_nr_elems() + rout.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
auto time_in_ms = bencher.execs({kern, out, inp}) / nr_times;
auto ops = 2.0 * batch * g * ho * wo * fh * fw / (time_in_ms * 1e-3) * 1e-12;
auto rr_time_in_ms = rr_bencher.execs({kern, out, rin, rout, inp}) / nr_times;
auto rr_ops =
2.0 * batch * g * ho * wo * fh * fw / (rr_time_in_ms * 1e-3) * 1e-12;
printf("[DGRAD]RegionRestrictedDepthwiseLargeFilter vs DepthwiseLargeFilter: "
"grad=%s, "
"kern=%s, diff=%s\n"
"time: %.2f ms, time(rr): %.2f ms, perf: %.2fTops, perf(rr): %.2f Tops\n"
"bandwidth: %.2fGB/s, bandwidth(rr): %.2fGB/s, speedup: %.2f.\n",
inp.to_string().c_str(), kern.to_string().c_str(),
out.to_string().c_str(), time_in_ms, rr_time_in_ms, ops, rr_ops,
bandwith * 4 / time_in_ms, rr_bandwith * 4 / rr_time_in_ms,
time_in_ms / rr_time_in_ms);
};
run_bench(64, 384, 32, 32, 3, 3, 1, 1, 1000);
run_bench(64, 384, 32, 32, 5, 5, 1, 1, 1000);
run_bench(64, 384, 32, 32, 7, 7, 1, 1, 1000);
run_bench(64, 384, 32, 32, 9, 9, 1, 1, 1000);
run_bench(64, 384, 32, 32, 11, 11, 1, 1, 1000);
run_bench(64, 384, 32, 32, 13, 13, 1, 1, 1000);
run_bench(64, 384, 32, 32, 15, 15, 1, 1, 1000);
run_bench(64, 384, 32, 32, 17, 17, 1, 1, 1000);
run_bench(64, 384, 32, 32, 19, 19, 1, 1, 1000);
run_bench(64, 384, 32, 32, 21, 21, 1, 1, 1000);
run_bench(64, 384, 32, 32, 23, 23, 1, 1, 1000);
run_bench(64, 384, 32, 32, 25, 25, 1, 1, 1000);
run_bench(64, 384, 32, 32, 27, 27, 1, 1, 1000);
run_bench(64, 384, 32, 32, 29, 29, 1, 1, 1000);
run_bench(64, 384, 32, 32, 31, 31, 1, 1, 1000);
}
TEST_F(CUDA, BENCHMARK_REGION_RESTRICTED_CONV_BACKWARD_DATA_FP32_UINT8) {
require_compute_capability(7, 5);
Benchmarker<ConvolutionBackwardData> bencher(handle_cuda());
bencher.set_display(false);
bencher.set_before_exec_callback(
AlgoChecker<ConvolutionBackwardData>("DEPTHWISE_LARGE_FILTER"));
Benchmarker<RegionRestrictedConvolutionBackwardData> rr_bencher(handle_cuda());
rr_bencher.set_display(false);
ConvolutionBackwardData::Param param;
param.format = ConvolutionBackwardData::Param::Format::NCHW;
param.sparse = ConvolutionBackwardData::Param::Sparse::GROUP;
RegionRestrictedConvolutionBackwardData::Param rr_param;
rr_param.format = RegionRestrictedConvolutionBackwardData::Param::Format::NCHW;
rr_param.sparse = RegionRestrictedConvolutionBackwardData::Param::Sparse::GROUP;
UniformIntRNG r_rng{1, 3};
auto run_bench = [&](size_t batch, size_t g, size_t hi, size_t wi, size_t fh,
size_t fw, size_t sh, size_t sw, size_t nr_times) {
param.pad_h = fh / 2;
param.pad_w = fw / 2;
param.stride_h = sh;
param.stride_w = sw;
rr_param.pad_h = fh / 2;
rr_param.pad_w = fw / 2;
rr_param.stride_h = sh;
rr_param.stride_w = sw;
bencher.set_param(param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Float32())
.set_dtype(4, dtype::Float32());
bencher.set_times(nr_times);
rr_bencher.set_param(rr_param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Uint8())
.set_dtype(3, dtype::Uint8());
rr_bencher.set_rng(2, &r_rng).set_rng(3, &r_rng);
rr_bencher.set_times(nr_times);
size_t ho = infer_conv_shape(hi, fh, sh, param.pad_h);
size_t wo = infer_conv_shape(wi, fw, sw, param.pad_w);
TensorShape inp{batch, g, hi, wi} /*src*/, kern{g, 1, 1, fh, fw} /*filter*/,
rin{batch, hi, wi}, rout{batch, ho, wo},
out{batch, g, ho, wo} /*output*/;
float bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
float rr_bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
rin.total_nr_elems() + rout.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
auto time_in_ms = bencher.execs({kern, out, inp}) / nr_times;
auto ops = 2.0 * batch * g * ho * wo * fh * fw / (time_in_ms * 1e-3) * 1e-12;
auto rr_time_in_ms = rr_bencher.execs({kern, out, rin, rout, inp}) / nr_times;
auto rr_ops =
2.0 * batch * g * ho * wo * fh * fw / (rr_time_in_ms * 1e-3) * 1e-12;
printf("[DGRAD]RegionRestrictedDepthwiseLargeFilter vs DepthwiseLargeFilter: "
"grad=%s, "
"kern=%s, diff=%s\n"
"time: %.2f ms, time(rr): %.2f ms, perf: %.2fTops, perf(rr): %.2f Tops\n"
"bandwidth: %.2fGB/s, bandwidth(rr): %.2fGB/s, speedup: %.2f.\n",
inp.to_string().c_str(), kern.to_string().c_str(),
out.to_string().c_str(), time_in_ms, rr_time_in_ms, ops, rr_ops,
bandwith * 4 / time_in_ms, rr_bandwith * 4 / rr_time_in_ms,
time_in_ms / rr_time_in_ms);
};
run_bench(64, 384, 32, 32, 3, 3, 1, 1, 1000);
run_bench(64, 384, 32, 32, 5, 5, 1, 1, 1000);
run_bench(64, 384, 32, 32, 7, 7, 1, 1, 1000);
run_bench(64, 384, 32, 32, 9, 9, 1, 1, 1000);
run_bench(64, 384, 32, 32, 11, 11, 1, 1, 1000);
run_bench(64, 384, 32, 32, 13, 13, 1, 1, 1000);
run_bench(64, 384, 32, 32, 15, 15, 1, 1, 1000);
run_bench(64, 384, 32, 32, 17, 17, 1, 1, 1000);
run_bench(64, 384, 32, 32, 19, 19, 1, 1, 1000);
run_bench(64, 384, 32, 32, 21, 21, 1, 1, 1000);
run_bench(64, 384, 32, 32, 23, 23, 1, 1, 1000);
run_bench(64, 384, 32, 32, 25, 25, 1, 1, 1000);
run_bench(64, 384, 32, 32, 27, 27, 1, 1, 1000);
run_bench(64, 384, 32, 32, 29, 29, 1, 1, 1000);
run_bench(64, 384, 32, 32, 31, 31, 1, 1, 1000);
run_bench(64, 384, 31, 31, 3, 3, 1, 1, 1000);
run_bench(64, 384, 31, 31, 5, 5, 1, 1, 1000);
run_bench(64, 384, 31, 31, 7, 7, 1, 1, 1000);
run_bench(64, 384, 31, 31, 9, 9, 1, 1, 1000);
run_bench(64, 384, 31, 31, 11, 11, 1, 1, 1000);
run_bench(64, 384, 31, 31, 13, 13, 1, 1, 1000);
run_bench(64, 384, 31, 31, 15, 15, 1, 1, 1000);
run_bench(64, 384, 31, 31, 17, 17, 1, 1, 1000);
run_bench(64, 384, 31, 31, 19, 19, 1, 1, 1000);
run_bench(64, 384, 31, 31, 21, 21, 1, 1, 1000);
run_bench(64, 384, 31, 31, 23, 23, 1, 1, 1000);
run_bench(64, 384, 31, 31, 25, 25, 1, 1, 1000);
run_bench(64, 384, 31, 31, 27, 27, 1, 1, 1000);
run_bench(64, 384, 31, 31, 29, 29, 1, 1, 1000);
run_bench(64, 384, 31, 31, 31, 31, 1, 1, 1000);
}
TEST_F(CUDA, BENCHMARK_REGION_RESTRICTED_CONV_FORWARD_LARGE_FILTER_UINT8) {
require_compute_capability(7, 5);
Benchmarker<ConvBiasForward> bencher(handle_cuda());
bencher.set_display(false);
bencher.set_before_exec_callback(conv_bias::ConvBiasAlgoChecker<ConvBiasForward>(
ConvBiasForward::algo_name<ConvBiasForward::DirectParam>(
"DEPTHWISE_LARGE_FILTER", {})
.c_str()));
Benchmarker<RegionRestrictedConvolutionForward> rr_bencher(handle_cuda());
rr_bencher.set_display(false);
ConvBias::Param param;
param.format = ConvBias::Param::Format::NCHW;
using NonlineMode = ConvBias::Param::NonlineMode;
param.nonlineMode = NonlineMode::IDENTITY;
param.sparse = ConvBias::Param::Sparse::GROUP;
RegionRestrictedConvolutionForward::Param rr_param;
rr_param.format = RegionRestrictedConvolutionForward::Param::Format::NCHW;
rr_param.sparse = RegionRestrictedConvolutionForward::Param::Sparse::GROUP;
UniformIntRNG r_rng{0, 2};
auto run_bench = [&](size_t batch, size_t g, size_t hi, size_t wi, size_t fh,
size_t fw, size_t sh, size_t sw, size_t nr_times) {
param.pad_h = fh / 2;
param.pad_w = fw / 2;
param.stride_h = sh;
param.stride_w = sw;
rr_param.pad_h = fh / 2;
rr_param.pad_w = fw / 2;
rr_param.stride_h = sh;
rr_param.stride_w = sw;
bencher.set_param(param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Float32())
.set_dtype(4, dtype::Float32());
bencher.set_times(nr_times);
rr_bencher.set_param(rr_param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Uint8())
.set_dtype(3, dtype::Uint8());
rr_bencher.set_rng(2, &r_rng).set_rng(3, &r_rng).set_rng(0, &r_rng);
rr_bencher.set_times(nr_times);
size_t ho = infer_conv_shape(hi, fh, sh, param.pad_h);
size_t wo = infer_conv_shape(wi, fw, sw, param.pad_w);
TensorShape inp{batch, g, hi, wi}, kern{g, 1, 1, fh, fw}, rin{batch, hi, wi},
rout{batch, ho, wo}, out{batch, g, ho, wo};
float bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
float rr_bandwith = static_cast<float>(
inp.total_nr_elems() + kern.total_nr_elems() +
rin.total_nr_elems() + rout.total_nr_elems() +
out.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
auto time_in_ms = bencher.execs({inp, kern, {}, {}, out}) / nr_times;
auto ops = 2.0 * batch * g * ho * wo * fh * fw / (time_in_ms * 1e-3) * 1e-12;
auto rr_time_in_ms = rr_bencher.execs({inp, kern, rin, rout, out}) / nr_times;
auto rr_ops =
2.0 * batch * g * ho * wo * fh * fw / (rr_time_in_ms * 1e-3) * 1e-12;
printf("RegionRestrictedDepthwiseLargeFilter vs DepthwiseLargeFilter: inp=%s, "
"kern=%s, out=%s\n"
"time: %.2f ms, time(rr): %.2f ms, perf: %.2fTops, perf(rr): %.2f Tops\n"
"bandwidth: %.2fGB/s, bandwidth(rr): %.2fGB/s, speedup: %.2f.\n",
inp.to_string().c_str(), kern.to_string().c_str(),
out.to_string().c_str(), time_in_ms, rr_time_in_ms, ops, rr_ops,
bandwith * 4 / time_in_ms, rr_bandwith * 4 / rr_time_in_ms,
time_in_ms / rr_time_in_ms);
};
run_bench(64, 384, 32, 32, 3, 3, 1, 1, 1000);
run_bench(64, 384, 32, 32, 5, 5, 1, 1, 1000);
run_bench(64, 384, 32, 32, 7, 7, 1, 1, 1000);
run_bench(64, 384, 32, 32, 9, 9, 1, 1, 1000);
run_bench(64, 384, 32, 32, 11, 11, 1, 1, 1000);
run_bench(64, 384, 32, 32, 13, 13, 1, 1, 1000);
run_bench(64, 384, 32, 32, 15, 15, 1, 1, 1000);
run_bench(64, 384, 32, 32, 17, 17, 1, 1, 1000);
run_bench(64, 384, 32, 32, 19, 19, 1, 1, 1000);
run_bench(64, 384, 32, 32, 21, 21, 1, 1, 1000);
run_bench(64, 384, 32, 32, 23, 23, 1, 1, 1000);
run_bench(64, 384, 32, 32, 25, 25, 1, 1, 1000);
run_bench(64, 384, 32, 32, 27, 27, 1, 1, 1000);
run_bench(64, 384, 32, 32, 29, 29, 1, 1, 1000);
run_bench(64, 384, 32, 32, 31, 31, 1, 1, 1000);
run_bench(64, 384, 31, 31, 3, 3, 1, 1, 1000);
run_bench(64, 384, 31, 31, 5, 5, 1, 1, 1000);
run_bench(64, 384, 31, 31, 7, 7, 1, 1, 1000);
run_bench(64, 384, 31, 31, 9, 9, 1, 1, 1000);
run_bench(64, 384, 31, 31, 11, 11, 1, 1, 1000);
run_bench(64, 384, 31, 31, 13, 13, 1, 1, 1000);
run_bench(64, 384, 31, 31, 15, 15, 1, 1, 1000);
run_bench(64, 384, 31, 31, 17, 17, 1, 1, 1000);
run_bench(64, 384, 31, 31, 19, 19, 1, 1, 1000);
run_bench(64, 384, 31, 31, 21, 21, 1, 1, 1000);
run_bench(64, 384, 31, 31, 23, 23, 1, 1, 1000);
run_bench(64, 384, 31, 31, 25, 25, 1, 1, 1000);
run_bench(64, 384, 31, 31, 27, 27, 1, 1, 1000);
run_bench(64, 384, 31, 31, 29, 29, 1, 1, 1000);
run_bench(64, 384, 31, 31, 31, 31, 1, 1, 1000);
}
TEST_F(CUDA, BENCHMARK_REGION_RESTRICTED_CONV_BACKWARD_FILTER_FP32) {
require_compute_capability(7, 5);
Benchmarker<ConvolutionBackwardFilter> bencher(handle_cuda());
bencher.set_display(false);
bencher.set_before_exec_callback(AlgoChecker<ConvolutionBackwardFilter>(
"FLOAT32_NCHW_FMA_IMPLICIT_BATCHED_GEMM_128X128X8_32X64X8_2stage"));
Benchmarker<RegionRestrictedConvolutionBackwardFilter> rr_bencher(handle_cuda());
rr_bencher.set_display(false);
ConvolutionBackwardFilter::Param param;
param.format = ConvolutionBackwardFilter::Param::Format::NCHW;
param.sparse = ConvolutionBackwardFilter::Param::Sparse::GROUP;
RegionRestrictedConvolutionBackwardFilter::Param rr_param;
rr_param.format = RegionRestrictedConvolutionBackwardFilter::Param::Format::NCHW;
rr_param.sparse = RegionRestrictedConvolutionBackwardFilter::Param::Sparse::GROUP;
UniformIntRNG r_rng{1, 3};
auto run_bench = [&](size_t batch, size_t g, size_t hi, size_t wi, size_t fh,
size_t fw, size_t sh, size_t sw, size_t nr_times) {
param.pad_h = fh / 2;
param.pad_w = fw / 2;
param.stride_h = sh;
param.stride_w = sw;
rr_param.pad_h = fh / 2;
rr_param.pad_w = fw / 2;
rr_param.stride_h = sh;
rr_param.stride_w = sw;
bencher.set_param(param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Float32())
.set_dtype(4, dtype::Float32());
bencher.proxy()->target_execution_policy = {};
bencher.set_times(nr_times);
rr_bencher.set_param(rr_param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Int32())
.set_dtype(3, dtype::Int32());
rr_bencher.set_rng(2, &r_rng).set_rng(3, &r_rng);
rr_bencher.set_times(nr_times);
size_t ho = infer_conv_shape(hi, fh, sh, param.pad_h);
size_t wo = infer_conv_shape(wi, fw, sw, param.pad_w);
TensorShape src{batch, g, hi, wi}, diff{batch, g, ho, wo}, rin{batch, hi, wi},
rout{batch, ho, wo}, grad{g, 1, 1, fh, fw};
float bandwith = static_cast<float>(
src.total_nr_elems() + diff.total_nr_elems() +
grad.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
float rr_bandwith = static_cast<float>(
src.total_nr_elems() + diff.total_nr_elems() +
rin.total_nr_elems() + rout.total_nr_elems() +
grad.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
auto time_in_ms = bencher.execs({src, diff, grad}) / nr_times;
auto ops = 2.0 * batch * g * hi * wi * fh * fw / (time_in_ms * 1e-3) * 1e-12;
auto rr_time_in_ms = rr_bencher.execs({src, diff, rin, rout, grad}) / nr_times;
auto rr_ops =
2.0 * batch * g * hi * wi * fh * fw / (rr_time_in_ms * 1e-3) * 1e-12;
printf("[WGRAD]RegionRestrictedDepthwiseLargeFilter vs DepthwiseLargeFilter: "
"src=%s, "
"diff=%s, grad=%s\n"
"time: %.2f ms, time(rr): %.2f ms, perf: %.2fTops, perf(rr): %.2f Tops\n"
"bandwidth: %.2fGB/s, bandwidth(rr): %.2fGB/s, speedup: %.2f.\n",
src.to_string().c_str(), diff.to_string().c_str(),
grad.to_string().c_str(), time_in_ms, rr_time_in_ms, ops, rr_ops,
bandwith * 4 / time_in_ms, rr_bandwith * 4 / rr_time_in_ms,
time_in_ms / rr_time_in_ms);
};
run_bench(64, 384, 32, 32, 3, 3, 1, 1, 1000);
run_bench(64, 384, 32, 32, 5, 5, 1, 1, 1000);
run_bench(64, 384, 32, 32, 7, 7, 1, 1, 1000);
run_bench(64, 384, 32, 32, 9, 9, 1, 1, 1000);
run_bench(64, 384, 32, 32, 11, 11, 1, 1, 1000);
run_bench(64, 384, 32, 32, 13, 13, 1, 1, 1000);
run_bench(64, 384, 32, 32, 15, 15, 1, 1, 1000);
run_bench(64, 384, 32, 32, 17, 17, 1, 1, 1000);
run_bench(64, 384, 32, 32, 19, 19, 1, 1, 1000);
run_bench(64, 384, 32, 32, 21, 21, 1, 1, 1000);
run_bench(64, 384, 32, 32, 23, 23, 1, 1, 1000);
run_bench(64, 384, 32, 32, 25, 25, 1, 1, 1000);
run_bench(64, 384, 32, 32, 27, 27, 1, 1, 1000);
run_bench(64, 384, 32, 32, 29, 29, 1, 1, 1000);
run_bench(64, 384, 32, 32, 31, 31, 1, 1, 1000);
}
TEST_F(CUDA, BENCHMARK_REGION_RESTRICTED_CONV_BACKWARD_FILTER_FP32_RINT8) {
require_compute_capability(7, 5);
Benchmarker<ConvolutionBackwardFilter> bencher(handle_cuda());
bencher.set_display(false);
bencher.set_before_exec_callback(AlgoChecker<ConvolutionBackwardFilter>(
"FLOAT32_NCHW_FMA_IMPLICIT_BATCHED_GEMM_128X128X8_32X64X8_2stage"));
Benchmarker<RegionRestrictedConvolutionBackwardFilter> rr_bencher(handle_cuda());
rr_bencher.set_display(false);
ConvolutionBackwardFilter::Param param;
param.format = ConvolutionBackwardFilter::Param::Format::NCHW;
param.sparse = ConvolutionBackwardFilter::Param::Sparse::GROUP;
RegionRestrictedConvolutionBackwardFilter::Param rr_param;
rr_param.format = RegionRestrictedConvolutionBackwardFilter::Param::Format::NCHW;
rr_param.sparse = RegionRestrictedConvolutionBackwardFilter::Param::Sparse::GROUP;
UniformIntRNG r_rng{1, 3};
auto run_bench = [&](size_t batch, size_t g, size_t hi, size_t wi, size_t fh,
size_t fw, size_t sh, size_t sw, size_t nr_times) {
param.pad_h = fh / 2;
param.pad_w = fw / 2;
param.stride_h = sh;
param.stride_w = sw;
rr_param.pad_h = fh / 2;
rr_param.pad_w = fw / 2;
rr_param.stride_h = sh;
rr_param.stride_w = sw;
bencher.set_param(param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Float32())
.set_dtype(4, dtype::Float32());
bencher.proxy()->target_execution_policy = {};
bencher.set_times(nr_times);
rr_bencher.set_param(rr_param)
.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dtype::Uint8())
.set_dtype(3, dtype::Uint8());
rr_bencher.set_rng(2, &r_rng).set_rng(3, &r_rng);
rr_bencher.set_times(nr_times);
size_t ho = infer_conv_shape(hi, fh, sh, param.pad_h);
size_t wo = infer_conv_shape(wi, fw, sw, param.pad_w);
TensorShape src{batch, g, hi, wi}, diff{batch, g, ho, wo}, rin{batch, hi, wi},
rout{batch, ho, wo}, grad{g, 1, 1, fh, fw};
float bandwith = static_cast<float>(
src.total_nr_elems() + diff.total_nr_elems() +
grad.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
float rr_bandwith = static_cast<float>(
src.total_nr_elems() + diff.total_nr_elems() +
rin.total_nr_elems() + rout.total_nr_elems() +
grad.total_nr_elems()) /
(1024 * 1024 * 1024) * 1e3;
auto time_in_ms = bencher.execs({src, diff, grad}) / nr_times;
auto ops = 2.0 * batch * g * hi * wi * fh * fw / (time_in_ms * 1e-3) * 1e-12;
auto rr_time_in_ms = rr_bencher.execs({src, diff, rin, rout, grad}) / nr_times;
auto rr_ops =
2.0 * batch * g * hi * wi * fh * fw / (rr_time_in_ms * 1e-3) * 1e-12;
printf("[WGRAD]RegionRestrictedDepthwiseLargeFilter vs DepthwiseLargeFilter: "
"src=%s, "
"diff=%s, grad=%s\n"
"time: %.2f ms, time(rr): %.2f ms, perf: %.2fTops, perf(rr): %.2f Tops\n"
"bandwidth: %.2fGB/s, bandwidth(rr): %.2fGB/s, speedup: %.2f.\n",
src.to_string().c_str(), diff.to_string().c_str(),
grad.to_string().c_str(), time_in_ms, rr_time_in_ms, ops, rr_ops,
bandwith * 4 / time_in_ms, rr_bandwith * 4 / rr_time_in_ms,
time_in_ms / rr_time_in_ms);
};
run_bench(64, 384, 32, 32, 3, 3, 1, 1, 1000);
run_bench(64, 384, 32, 32, 5, 5, 1, 1, 1000);
run_bench(64, 384, 32, 32, 7, 7, 1, 1, 1000);
run_bench(64, 384, 32, 32, 9, 9, 1, 1, 1000);
run_bench(64, 384, 32, 32, 11, 11, 1, 1, 1000);
run_bench(64, 384, 32, 32, 13, 13, 1, 1, 1000);
run_bench(64, 384, 32, 32, 15, 15, 1, 1, 1000);
run_bench(64, 384, 32, 32, 17, 17, 1, 1, 1000);
run_bench(64, 384, 32, 32, 19, 19, 1, 1, 1000);
run_bench(64, 384, 32, 32, 21, 21, 1, 1, 1000);
run_bench(64, 384, 32, 32, 23, 23, 1, 1, 1000);
run_bench(64, 384, 32, 32, 25, 25, 1, 1, 1000);
run_bench(64, 384, 32, 32, 27, 27, 1, 1, 1000);
run_bench(64, 384, 32, 32, 29, 29, 1, 1, 1000);
run_bench(64, 384, 32, 32, 31, 31, 1, 1, 1000);
}
#endif
TEST_F(CUDA, REGION_RESTRICTED_CONV_BWD_DATA_FP32) {
Checker<RegionRestrictedConvolutionBackwardData> checker(handle_cuda());
for (auto dt : std::vector<DType>{dtype::Int32(), dtype::Uint8()}) {
auto run = [&checker, &dt](
size_t n, size_t g, size_t ih, size_t fh, size_t padding,
size_t stride) {
RegionRestrictedConvolutionBackwardData::Param cur_param;
cur_param.mode = RegionRestrictedConvolutionBackwardData::Param::Mode::
CROSS_CORRELATION;
cur_param.compute_mode = RegionRestrictedConvolutionBackwardData::Param::
ComputeMode::DEFAULT;
cur_param.sparse =
RegionRestrictedConvolutionBackwardData::Param::Sparse::GROUP;
checker.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dt)
.set_dtype(3, dt);
float scale = 64.f / sqrt(fh * fh);
UniformFloatRNG rng(scale, 2 * scale);
UniformIntRNG r_rng{1, 2};
checker.set_rng(0, &rng).set_rng(1, &rng).set_rng(2, &r_rng).set_rng(
3, &r_rng);
cur_param.pad_h = cur_param.pad_w = padding;
cur_param.stride_h = cur_param.stride_w = stride;
size_t oh = (ih + 2 * padding - fh + 1) / stride;
checker.set_param(cur_param).execs({
{g, 1, 1, fh, fh}, // filter
{n, g * 1, oh, oh}, // diff
{n, ih, ih}, // rin
{n, oh, oh}, // rout
{n, g * 1, ih, ih} // grad
});
};
run(1, 1, 3, 2, 1, 1);
run(1, 1, 5, 2, 1, 1);
run(1, 1, 6, 2, 1, 1);
run(1, 1, 7, 2, 1, 1);
run(1, 1, 9, 2, 1, 1);
run(1, 1, 10, 2, 1, 1);
run(1, 1, 11, 2, 1, 1);
run(1, 1, 13, 2, 1, 1);
run(1, 1, 14, 2, 1, 1);
run(1, 1, 15, 2, 1, 1);
run(1, 1, 17, 2, 1, 1);
run(1, 1, 18, 2, 1, 1);
run(1, 1, 19, 2, 1, 1);
run(1, 1, 21, 2, 1, 1);
run(1, 1, 22, 2, 1, 1);
run(1, 1, 23, 2, 1, 1);
run(1, 1, 25, 2, 1, 1);
run(1, 1, 26, 2, 1, 1);
run(1, 1, 27, 2, 1, 1);
run(1, 1, 29, 2, 1, 1);
run(1, 1, 30, 2, 1, 1);
run(1, 1, 31, 2, 1, 1);
run(4, 8, 32, 3, 3 / 2, 1);
run(4, 8, 32, 5, 5 / 2, 1);
run(4, 8, 32, 7, 7 / 2, 1);
run(4, 8, 32, 9, 9 / 2, 1);
run(4, 8, 32, 11, 11 / 2, 1);
run(4, 8, 32, 13, 13 / 2, 1);
run(4, 8, 32, 15, 15 / 2, 1);
run(4, 8, 32, 17, 17 / 2, 1);
run(4, 8, 32, 19, 19 / 2, 1);
run(4, 8, 32, 21, 21 / 2, 1);
run(4, 8, 32, 23, 23 / 2, 1);
run(4, 8, 32, 25, 25 / 2, 1);
run(4, 8, 32, 27, 27 / 2, 1);
run(4, 8, 32, 29, 29 / 2, 1);
run(4, 8, 32, 31, 31 / 2, 1);
run(4, 8, 31, 3, 3 / 2, 1);
run(4, 8, 31, 5, 5 / 2, 1);
run(4, 8, 31, 7, 7 / 2, 1);
run(4, 8, 31, 9, 9 / 2, 1);
run(4, 8, 31, 11, 11 / 2, 1);
run(4, 8, 31, 13, 13 / 2, 1);
run(4, 8, 31, 15, 15 / 2, 1);
run(4, 8, 31, 17, 17 / 2, 1);
run(4, 8, 31, 19, 19 / 2, 1);
run(4, 8, 31, 21, 21 / 2, 1);
run(4, 8, 31, 23, 23 / 2, 1);
run(4, 8, 31, 25, 25 / 2, 1);
run(4, 8, 31, 27, 27 / 2, 1);
run(4, 8, 31, 29, 29 / 2, 1);
run(4, 8, 31, 31, 31 / 2, 1);
}
}
TEST_F(CUDA, REGION_RESTRICTED_CONV_BWD_DATA_FP32_RIN_EQ_ROUT) {
Checker<RegionRestrictedConvolutionBackwardData> checker(handle_cuda());
for (auto dt : std::vector<DType>{dtype::Int32()}) {
auto run = [&checker, &dt](
size_t n, size_t g, size_t ih, size_t fh, size_t padding,
size_t stride) {
RegionRestrictedConvolutionBackwardData::Param cur_param;
cur_param.mode = RegionRestrictedConvolutionBackwardData::Param::Mode::
CROSS_CORRELATION;
cur_param.compute_mode = RegionRestrictedConvolutionBackwardData::Param::
ComputeMode::DEFAULT;
cur_param.sparse =
RegionRestrictedConvolutionBackwardData::Param::Sparse::GROUP;
checker.set_dtype(2, dt).set_dtype(3, dt);
float scale = 64.f / sqrt(fh * fh);
UniformFloatRNG rng(scale, 2 * scale);
// value 0 mask may cause unexpected behaviour.
UniformIntRNG r_rng{1, 1};
checker.set_rng(0, &rng).set_rng(1, &rng).set_rng(2, &r_rng).set_rng(
3, &r_rng);
cur_param.pad_h = cur_param.pad_w = padding;
cur_param.stride_h = cur_param.stride_w = stride;
size_t oh = (ih + 2 * padding - fh + 1) / stride;
checker.set_param(cur_param).execs(
{/*filter*/ {g, 1, 1, fh, fh},
/*diff*/ {n, g * 1, oh, oh},
/*rin*/ {n, ih, ih},
/*rout*/ {n, oh, oh},
/*grad*/ {n, g * 1, ih, ih}});
};
run(1, 1, 3, 2, 1, 1);
run(1, 1, 5, 2, 1, 1);
run(1, 1, 6, 2, 1, 1);
run(1, 1, 7, 2, 1, 1);
run(1, 1, 9, 2, 1, 1);
run(1, 1, 10, 2, 1, 1);
run(1, 1, 11, 2, 1, 1);
run(1, 1, 13, 2, 1, 1);
run(1, 1, 14, 2, 1, 1);
run(1, 1, 15, 2, 1, 1);
run(1, 1, 17, 2, 1, 1);
run(1, 1, 18, 2, 1, 1);
run(1, 1, 19, 2, 1, 1);
run(1, 1, 21, 2, 1, 1);
run(1, 1, 22, 2, 1, 1);
run(1, 1, 23, 2, 1, 1);
run(1, 1, 25, 2, 1, 1);
run(1, 1, 26, 2, 1, 1);
run(1, 1, 27, 2, 1, 1);
run(1, 1, 29, 2, 1, 1);
run(1, 1, 30, 2, 1, 1);
run(1, 1, 31, 2, 1, 1);
run(4, 8, 32, 3, 3 / 2, 1);
run(4, 8, 32, 5, 5 / 2, 1);
run(4, 8, 32, 7, 7 / 2, 1);
run(4, 8, 32, 9, 9 / 2, 1);
run(4, 8, 32, 11, 11 / 2, 1);
run(4, 8, 32, 13, 13 / 2, 1);
run(4, 8, 32, 15, 15 / 2, 1);
run(4, 8, 32, 17, 17 / 2, 1);
run(4, 8, 32, 19, 19 / 2, 1);
run(4, 8, 32, 21, 21 / 2, 1);
run(4, 8, 32, 23, 23 / 2, 1);
run(4, 8, 32, 25, 25 / 2, 1);
run(4, 8, 32, 27, 27 / 2, 1);
run(4, 8, 32, 29, 29 / 2, 1);
run(4, 8, 32, 31, 31 / 2, 1);
run(4, 8, 31, 3, 3 / 2, 1);
run(4, 8, 31, 5, 5 / 2, 1);
run(4, 8, 31, 7, 7 / 2, 1);
run(4, 8, 31, 9, 9 / 2, 1);
run(4, 8, 31, 11, 11 / 2, 1);
run(4, 8, 31, 13, 13 / 2, 1);
run(4, 8, 31, 15, 15 / 2, 1);
run(4, 8, 31, 17, 17 / 2, 1);
run(4, 8, 31, 19, 19 / 2, 1);
run(4, 8, 31, 21, 21 / 2, 1);
run(4, 8, 31, 23, 23 / 2, 1);
run(4, 8, 31, 25, 25 / 2, 1);
run(4, 8, 31, 27, 27 / 2, 1);
run(4, 8, 31, 29, 29 / 2, 1);
run(4, 8, 31, 31, 31 / 2, 1);
}
}
TEST_F(CUDA, REGION_RESTRICTED_CONV_BWD_FILTER_FP32) {
require_compute_capability(6, 1);
Checker<RegionRestrictedConvolutionBackwardFilter> checker(handle_cuda());
for (auto dt : std::vector<DType>{dtype::Int32(), dtype::Uint8()}) {
auto run = [&checker, &dt](
size_t n, size_t g, size_t ih, size_t fh, size_t padding,
size_t stride) {
RegionRestrictedConvolutionBackwardFilter::Param cur_param;
cur_param.mode = RegionRestrictedConvolutionBackwardFilter::Param::Mode::
CROSS_CORRELATION;
cur_param.compute_mode = RegionRestrictedConvolutionBackwardFilter::Param::
ComputeMode::DEFAULT;
cur_param.sparse =
RegionRestrictedConvolutionBackwardFilter::Param::Sparse::GROUP;
checker.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dt)
.set_dtype(3, dt);
float scale = 64.f / sqrt(fh * fh);
UniformFloatRNG rng(scale, 2 * scale);
UniformIntRNG r_rng{1, 2};
checker.set_rng(0, &rng).set_rng(1, &rng).set_rng(2, &r_rng).set_rng(
3, &r_rng);
cur_param.pad_h = cur_param.pad_w = padding;
cur_param.stride_h = cur_param.stride_w = stride;
size_t oh = (ih + 2 * padding - fh + 1) / stride;
checker.set_param(cur_param).execs({
{n, g * 1, ih, ih}, // src
{n, g * 1, oh, oh}, // diff
{n, ih, ih}, // rin
{n, oh, oh}, // rout
{g, 1, 1, fh, fh} // grad
});
};
run(4, 8, 32, 5, 5 / 2, 1);
run(1, 2, 2, 2, 0, 1);
run(1, 2, 3, 3, 0, 1);
run(1, 2, 4, 4, 0, 1);
run(1, 2, 5, 5, 0, 1);
run(1, 2, 6, 6, 0, 1);
run(1, 2, 7, 7, 0, 1);
run(4, 8, 32, 7, 7 / 2, 1);
run(4, 8, 32, 9, 9 / 2, 1);
run(4, 8, 32, 11, 11 / 2, 1);
run(4, 8, 32, 13, 13 / 2, 1);
run(4, 8, 32, 15, 15 / 2, 1);
run(4, 8, 32, 17, 17 / 2, 1);
run(4, 8, 32, 19, 19 / 2, 1);
run(4, 8, 32, 21, 21 / 2, 1);
run(4, 8, 32, 23, 23 / 2, 1);
run(4, 8, 32, 25, 25 / 2, 1);
run(4, 8, 32, 27, 27 / 2, 1);
run(4, 1, 32, 27, 27 / 2, 1);
run(4, 8, 32, 29, 29 / 2, 1);
run(4, 8, 32, 31, 31 / 2, 1);
}
}
TEST_F(CUDA, REGION_RESTRICTED_CONV_BWD_FILTER_FP32_RIN_EQ_ROUT) {
require_compute_capability(6, 1);
Checker<RegionRestrictedConvolutionBackwardFilter> checker(handle_cuda());
for (auto dt : std::vector<DType>{dtype::Int32(), dtype::Uint8()}) {
auto run = [&checker, &dt](
size_t n, size_t g, size_t ih, size_t fh, size_t padding,
size_t stride) {
RegionRestrictedConvolutionBackwardFilter::Param cur_param;
cur_param.mode = RegionRestrictedConvolutionBackwardFilter::Param::Mode::
CROSS_CORRELATION;
cur_param.compute_mode = RegionRestrictedConvolutionBackwardFilter::Param::
ComputeMode::DEFAULT;
cur_param.sparse =
RegionRestrictedConvolutionBackwardFilter::Param::Sparse::GROUP;
checker.set_dtype(0, dtype::Float32())
.set_dtype(1, dtype::Float32())
.set_dtype(2, dt)
.set_dtype(3, dt);
float scale = 64.f / sqrt(fh * fh);
UniformFloatRNG rng(scale, 2 * scale);
UniformIntRNG r_rng{1, 1};
checker.set_rng(0, &rng).set_rng(1, &rng).set_rng(2, &r_rng).set_rng(
3, &r_rng);
cur_param.pad_h = cur_param.pad_w = padding;
cur_param.stride_h = cur_param.stride_w = stride;
size_t oh = (ih + 2 * padding - fh + 1) / stride;
checker.set_param(cur_param).execs({
{n, g * 1, ih, ih}, // src
{n, g * 1, oh, oh}, // diff
{n, ih, ih}, // rin
{n, oh, oh}, // rout
{g, 1, 1, fh, fh} // grad
});
};
run(4, 8, 32, 5, 5 / 2, 1);
run(1, 2, 2, 2, 0, 1);
run(1, 2, 3, 3, 0, 1);
run(1, 2, 4, 4, 0, 1);
run(1, 2, 5, 5, 0, 1);
run(1, 2, 6, 6, 0, 1);
run(1, 2, 7, 7, 0, 1);
run(4, 8, 32, 7, 7 / 2, 1);
run(4, 8, 32, 9, 9 / 2, 1);
run(4, 8, 32, 11, 11 / 2, 1);
run(4, 8, 32, 13, 13 / 2, 1);
run(4, 8, 32, 15, 15 / 2, 1);
run(4, 8, 32, 17, 17 / 2, 1);
run(4, 8, 32, 19, 19 / 2, 1);
run(4, 8, 32, 21, 21 / 2, 1);
run(4, 1, 32, 21, 21 / 2, 1);
run(4, 8, 32, 23, 23 / 2, 1);
run(4, 8, 32, 25, 25 / 2, 1);
run(4, 8, 32, 27, 27 / 2, 1);
run(4, 8, 32, 29, 29 / 2, 1);
run(4, 8, 32, 31, 31 / 2, 1);
}
}
} // namespace test
} // namespace megdnn
// vim: syntax=cpp.doxygen
|
9d8e57bb2f1f694eefa0b62276da921f8c9f02ad
|
592b53b4453899ab9e5947e7a45a38f4b2a31b50
|
/GNURadio/OOT_Modules/gr-ccsds/lib/rs_decode_pdu_impl.cc
|
f51ec33c1fae65338ce32e0743a6bd3bd8a3cf48
|
[
"MIT"
] |
permissive
|
ClydeSpace-GroundStation/GroundStation
|
9b4e2cc86edfa2598958d081ba6bc74a64e40584
|
21b4da25a7061b59447cf5a6686e5a575350a3f4
|
refs/heads/master
| 2021-01-18T23:17:13.095811
| 2016-06-13T10:39:31
| 2016-06-13T10:39:31
| 54,881,024
| 5
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,817
|
cc
|
rs_decode_pdu_impl.cc
|
/* -*- c++ -*- */
/*
* Copyright 2016 - Thomas Parry - Clyde Space.
*
* This 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, or (at your option)
* any later version.
*
* This software 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 software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "rs_decode_pdu_impl.h"
#include "fec.h"
#include <iomanip>
#include <gnuradio/io_signature.h>
namespace gr {
namespace ccsds {
rs_decode_pdu::sptr
rs_decode_pdu::make(int interleave)
{
return gnuradio::get_initial_sptr
(new rs_decode_pdu_impl(interleave));
}
/*
* The private constructor
*/
rs_decode_pdu_impl::rs_decode_pdu_impl(int interleave)
: gr::block("rs_decode_pdu",
gr::io_signature::make(0, 0, 0),
gr::io_signature::make(0, 0, 0))
{
_interleave = interleave;
// create a PDU output port
message_port_register_out(pmt::mp("pdu_out"));
// create a PDU input port and bind the to message handler function
message_port_register_in(pmt::mp("pdu_in"));
set_msg_handler(pmt::mp("pdu_in"), boost::bind(&rs_decode_pdu_impl::output_frame, this, _1));
}
/*
* Our virtual destructor.
*/
rs_decode_pdu_impl::~rs_decode_pdu_impl()
{
}
/*
* Receiced PDU handler. Once called this function rearranges the data
* into the correct RS codeblocks, performs decoding and transmits a PDU
* of the original space frame packet
*/
void rs_decode_pdu_impl::output_frame(pmt::pmt_t input_pdu)
{
// deconstruct the input PDU
pmt::pmt_t meta = pmt::car(input_pdu);
pmt::pmt_t vector = pmt::cdr(input_pdu);
// retrieve the data
size_t offset(0);
const uint8_t* input_data = (const uint8_t*) pmt::uniform_vector_elements(vector, offset);
// sort the input data into the RS codeblocks
for(int n=0; n < _interleave*NN; n++) {
_data[n%_interleave][(int)n/_interleave] = input_data[n];
}
// reset the failure flag
_failure = 0;
// perfrom decoding of each block and copy to output
for(int n=0; n < _interleave; n++) {
// decode the RS codewords
int result = decode_rs_ccsds(&_data[n][0], &_error_positions[n][0], 0, 0);
// test for failure
_failure += result;
}
// decide what to do with the failed codeblocks
if(_failure) {
// decoding has failed!
// std::cout << "Reed Solomon decoding has failed!" << std::endl;
} else {
// decoding has worked
// std::cout << "Reed Solomon decoding has succeeded!" << std::endl;
// rearrange the codeblocks into the corrcect original message
std::vector<unsigned char> output_vector((NN-NROOTS) * _interleave);
for(int n=0; n < ((NN-NROOTS) * _interleave); n++) {
output_vector[n] = _data[n%_interleave][n/_interleave];
}
// send the vector as a PDU
pmt::pmt_t vecpmt(pmt::make_blob(&output_vector[0], (NN-NROOTS) * _interleave));
pmt::pmt_t output_pdu(pmt::cons(pmt::PMT_NIL, vecpmt));
message_port_pub(pmt::mp("pdu_out"), output_pdu);
}
}
} /* namespace ccsds */
} /* namespace gr */
|
e136a4cfc981671a27a5719eb481844a636e7479
|
8259d368485e3e627d15b871a6c3f704f9094518
|
/api/c++/persistence/HDFSStream.cpp
|
83f97e66ffe82102ccd066fd72418dc93f6638d7
|
[
"Apache-2.0"
] |
permissive
|
AudiovisualMetadataPlatform/mico
|
d8e05f10ce4a5a55d186e7a066f8a76016d31923
|
7a4faf553859119faf1abfa15d41a7c88835136f
|
refs/heads/master
| 2020-04-24T15:53:03.512597
| 2019-02-11T09:13:08
| 2019-02-11T09:13:08
| 172,086,512
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,561
|
cpp
|
HDFSStream.cpp
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstring>
#include <libgen.h>
#include "HDFSStream.hpp"
namespace mico {
namespace io {
hdfsFS createHdfsFileSystem(const char *host, uint16_t port){
//Set Hostname and port of the HDFS name node
struct hdfsBuilder *builder = hdfsNewBuilder();
if (port == 0) {
port = HDFS_DEFAULT_PORT;
}
std::string nameNodeHostName = "hdfs://" + std::string(host) + ":" + std::to_string(port);
hdfsBuilderConfSetStr(builder, "fs.defaultFS", nameNodeHostName.c_str());
hdfsBuilderSetNameNode(builder, nameNodeHostName.c_str());
//Resolve slave data nodes based on the hostname they are bound to,
//not on ther IPs (which could be part of an unreachable private network)
hdfsBuilderConfSetStr(builder, "dfs.client.use.datanode.hostname", "true");
//always read data from the websocket provided by the data node
hdfsBuilderConfSetStr(builder, "dfs.client.read.shortcircuit", "false");
hdfsBuilderSetForceNewInstance(builder);
hdfsFS fs = hdfsBuilderConnect(builder);
hdfsFreeBuilder(builder);
return fs;
}
}
}
namespace mico {
namespace io {
HDFSStreambuf::HDFSStreambuf(const char* path, FileMode mode, const char* host, uint16_t port, int bufsize)
: buffer_size(bufsize)
{
buffer = (char*)malloc(buffer_size * sizeof(char));
if (buffer == NULL) {
return;
}
fs=createHdfsFileSystem(host,port);
//Open file
switch(mode) {
case FILE_MODE_READ:
file = hdfsOpenFile(fs, path, O_RDONLY, 0, 0, 0);
break;
case FILE_MODE_WRITE:
char* path_dup = strdup(path);
char* dir = dirname(path_dup);
if(hdfsExists(fs, dir) != 0) {
if(hdfsCreateDirectory(fs, dir) != 0) {
throw std::string("Error creating directory: ") + dir;
}
}
free(path_dup);
file = hdfsOpenFile(fs, path, O_WRONLY, 0, 0, 0);
break;
}
}
HDFSStreambuf::~HDFSStreambuf() {
//HDFS: Close file and disconnect.
if (fs != NULL) {
if (file != NULL) {
hdfsCloseFile(fs, file);
}
hdfsDisconnect(fs);
}
//Free buffer.
if (buffer != NULL) {
free(buffer);
}
}
HDFSIStream::HDFSIStream(const char* path, const char* address, uint16_t port)
: HDFSStreambuf(path, FILE_MODE_READ, address, port)
{
if (buffer != NULL) {
//Set buffer pointers to mark buffer as empty. That will cause a call of underflow() on the first stream
//read request.
setg(buffer, buffer + buffer_size, buffer + buffer_size);
//Retrieve the file size, used for seek operations.
hdfsFileInfo* info = hdfsGetPathInfo(fs, path);
if (info != NULL) {
file_size = info->mSize;
hdfsFreeFileInfo(info, 1);
}
}
};
std::streambuf::int_type HDFSIStream::underflow() {
//If buffer is not empty return next byte.
if (gptr() < egptr()) {
return traits_type::to_int_type(*gptr());
}
//Fill buffer with data from HDFS file.
int length = hdfsRead(fs, file, buffer, buffer_size);
if (length == 0) {
//We are at the end of the file.
return traits_type::eof();
} else if (length == -1) {
//Read error
/* hdfsRead:
* On error, -1. Errno will be set to the error code.
* Just like the POSIX read function, hdfsRead will return -1
* and set errno to EINTR if data is temporarily unavailable,
* but we are not yet at the end of the file.
*/
return length;
}
//Set buffer pointer to indicate full (or the number of bytes that have been red actually) buffer.
setg(buffer, buffer, buffer + length);
return traits_type::to_int_type(*gptr());
}
std::streampos HDFSIStream::seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which) {
if (which != std::ios_base::in || file_size < 0)
return -1;
std::streamoff position = -1;
switch (way) {
//Offset is relative to the beginning of the file, so it is the absolute position.
case std::ios_base::beg:
position = off;
break;
//Offset is relative to the current file position.
case std::ios_base::cur:
position = hdfsTell(fs, file) + off;
break;
//Offset is relative to the end of the file and therefore should be negative.
case std::ios_base::end:
position = file_size + position;
break;
}
if (position >= 0 && position <= file_size) {
if (hdfsSeek(fs, file, position) == 0) {
//Invalidate buffer
setg(buffer, buffer + buffer_size, buffer + buffer_size);
return position;
}
}
return -1;
}
std::streampos HDFSIStream::seekpos(std::streampos pos, std::ios_base::openmode which) {
return seekoff(pos, std::ios_base::beg, which);
}
HDFSOStream::HDFSOStream(const char* path, const char* address, uint16_t port)
: HDFSStreambuf(path, FILE_MODE_WRITE, address, port)
{
if (buffer != NULL) {
//Set buffer pointers to mark buffer as empty.
setp(buffer, buffer + buffer_size);
}
};
std::streambuf::int_type HDFSOStream::overflow(std::streambuf::int_type c) {
//Write buffer content to file.
if(writeBuffer() == 0) {
if (!traits_type::eq_int_type(c, traits_type::eof())) {
//Push c as first byte on the buffer.
sputc(c);
}
return traits_type::not_eof(c);
}
return traits_type::eof();
}
int HDFSOStream::sync() {
//Write buffer content to file.
if (writeBuffer() != 0) return -1;
//Also flush HDFS buffers.
return hdfsSync(fs, file);
}
int HDFSOStream::writeBuffer() {
int write = pptr() - pbase();
if (write) {
int written = hdfsWrite(fs, file, buffer, write);
if (write != written) {
return -1;
}
}
//Set buffer pointers to mark buffer as empty.
setp(buffer, buffer + buffer_size);
return 0;
}
int removeHdfsFile(const char* path, const char* host, uint16_t port) {
//Connect to HDFS
hdfsFS fs = createHdfsFileSystem(host,port);
int status = hdfsDelete(fs, path, 0);
//HDFS: disconnect.
if (fs != NULL) {
hdfsDisconnect(fs);
}
return status;
}
int removeHdfsFile(const char* path) {
return removeHdfsFile(path, HDFS_DEFAULT_ADDRESS, HDFS_DEFAULT_PORT);
}
}
}
|
bf304345f6079a337f16be22c69db9ebfc306e47
|
fdfeb3da025ece547aed387ad9c83b34a28b4662
|
/Fundamental/CCore/test/test2020.BinarySearch.cpp
|
23e6938ef45aa25c7e9e0e547444f278c1d88e88
|
[
"FTL",
"BSL-1.0"
] |
permissive
|
SergeyStrukov/CCore-3-xx
|
815213a9536e9c0094548ad6db469e62ab2ad3f7
|
820507e78f8aa35ca05761e00e060c8f64c59af5
|
refs/heads/master
| 2021-06-04T05:29:50.384520
| 2020-07-04T20:20:29
| 2020-07-04T20:20:29
| 93,891,835
| 8
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,053
|
cpp
|
test2020.BinarySearch.cpp
|
/* test2020.BinarySearch.cpp */
//----------------------------------------------------------------------------------------
//
// Project: CCore 2.00
//
// Tag: Fundamental Mini
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2015 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <CCore/test/test.h>
#include <CCore/inc/algon/BinarySearch.h>
namespace App {
/* Testit<2020> */
template<>
const char *const Testit<2020>::Name="Test2020 BinarySearch";
template<>
bool Testit<2020>::Main()
{
const int Len = 10 ;
int buf[Len];
for(int i=0; i<Len ;i++) buf[i]=i;
for(int i=0; i<=Len ;i++)
{
PtrLen<int> r=Range(buf);
Algon::BinarySearch_greater_or_equal(r,i);
Printf(Con,"i = #; , found ",i);
if( +r ) Printf(Con,"#;\n",*r); else Printf(Con,"none\n");
}
return true;
}
} // namespace App
|
b58917841804b04fe5be64fc3efcc83f9280cb45
|
a282dccd573b9d5225017db2739c0861c5270fb2
|
/parcial.cpp
|
b193d44ec925899b40e16b7c5078be9093563d3c
|
[] |
no_license
|
atrippel/Mate3
|
064416f10bef685f79359144f40e5ade99207ba9
|
90c7d6d33c8e5498bc312be47373305bf1c5f287
|
refs/heads/master
| 2021-06-17T19:32:44.438940
| 2017-06-22T22:36:52
| 2017-06-22T22:36:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,758
|
cpp
|
parcial.cpp
|
#include <stdio.h>
#include <stdlib.h>
void cargarMatriz(int matriz[4][4])
{
int i,j,valor;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
printf("\nIngrese el valor de la posicion %d y %d\n",i,j);
scanf("%d",&valor);
matriz[i][j]=valor;
}
}
}
void sumarDiagonalPpal(int matriz[4][4])
{
int i,sum=0;
for(i=0;i<4;i++){
sum=sum+matriz[i][i];
}
printf("La suma de la diagonal Principal es: %d\n", sum);
}
void cuantosPositivosNegativos(int matriz[4][4])
{
int i,j,pos=0,neg=0;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if (matriz[i][j]>0){
pos=pos+1;
}else{
neg=neg+1;
}
}
}
printf("La cantidad de numeros positivos es: %d\n", pos);
printf("La cantidad de numeros negativos es: %d\n", neg);
}
void valorMaximo(int matriz[4][4])
{
int i,j,max=-10;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if (matriz[i][j]>max){
max=matriz[i][j];
}
}
}
printf("El valor maximo de la matriz es: %d\n", max);
printf("\nEl valor maximo se encuentra en la posicion: \n");
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if (matriz[i][j]==max){
printf("\n%d y %d\n",i,j);
}
}
}
}
int main(){
int matriz[4][4];
int i,j;
cargarMatriz(matriz);
for(i=0;i<4;i++){
for(j=0;j<4;j++){
printf("%d ",matriz[i][j]);
}
printf("\n");
}
sumarDiagonalPpal(matriz);
cuantosPositivosNegativos(matriz);
valorMaximo(matriz);
system("pause");
return 0;
}
|
b498b4068418f7aa67fda4d13a0c17ac9faf06eb
|
085e03878f982a59185cc91581d1c61b0eba7ecc
|
/BattleTank/Source/BattleTank/Public/TankBarrel.h
|
764790ed200b5e664198c85ff0920fedd14b8a10
|
[] |
no_license
|
fogeZombie/BattleTankTutorial
|
c1a0dcf1ef34cb09c2c0ebb81085f19d0a391bde
|
71b1967c86953c927adeff5329cc0b169c55b219
|
refs/heads/master
| 2020-03-23T10:42:53.596795
| 2018-08-31T19:52:54
| 2018-08-31T19:52:54
| 141,458,046
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 979
|
h
|
TankBarrel.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Engine/World.h"
#include "CoreMinimal.h"
#include "Components/StaticMeshComponent.h"
#include "TankBarrel.generated.h"
/**
* Holds barrel's properties and elevate method.
* Used exclusively as a tank component.
*/
UCLASS(ClassGroup = (Tank), meta = (BlueprintSpawnableComponent), hidecategories = ("Lighting", "Rendering"))
class BATTLETANK_API UTankBarrel : public UStaticMeshComponent
{
GENERATED_BODY()
public:
void Elevate(float RelativeSpeed);
// fields
private:
// Elevation movement speed in degrees per second.
UPROPERTY(EditAnywhere, Category = Movement)
float Elevation_MaxDegreesPerSecond = 8.0f;
// Minimum allowed elevation in degrees.
UPROPERTY(EditAnywhere, Category = Movement)
float Elevation_MinElevation = 0.0f;
// Maximum allowed elevation in degrees.
UPROPERTY(EditAnywhere, Category = Movement)
float Elevation_MaxElevation = 40.0f;
};
|
3912bf83dec9fe35f17aee7276930a90f357e0fb
|
ee33b4ab65c8840cf37c4acb3037ea66dde12d91
|
/curvefs/src/tools/curvefs_tool_main.cpp
|
9f42c095d03ba47eb178b50957ec7916336d2040
|
[
"Apache-2.0"
] |
permissive
|
opencurve/curve
|
36339c6377e7ac45ad2558d5cb67417b488094b4
|
6f5c85b1660aeb55d5c08e3d1eb354949ab7567a
|
refs/heads/master
| 2023-08-31T04:52:54.707665
| 2023-08-05T14:04:44
| 2023-08-15T11:46:46
| 276,365,255
| 2,099
| 540
|
Apache-2.0
| 2023-09-14T15:33:46
| 2020-07-01T11:57:25
|
C++
|
UTF-8
|
C++
| false
| false
| 1,940
|
cpp
|
curvefs_tool_main.cpp
|
/*
* Copyright (c) 2021 NetEase Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Project: curve
* Created Date: 2021-09-13
* Author: chengyi
*/
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <iostream>
#include <memory>
#include "curvefs/src/tools/curvefs_tool.h"
#include "curvefs/src/tools/curvefs_tool_define.h"
#include "curvefs/src/tools/curvefs_tool_factory.h"
DECLARE_string(mdsAddr);
DECLARE_bool(example);
DECLARE_string(confPath);
namespace brpc {
DECLARE_int32(health_check_interval);
}
int main(int argc, char** argv) {
google::SetUsageMessage(curvefs::tools::kHelpStr);
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
if (argc < 2) {
std::cout << curvefs::tools::kHelpStr << std::endl;
return -1;
}
std::string command = argv[1];
// Turn off the health check,
// otherwise it does not make sense to try again when Not Connect to
brpc::FLAGS_health_check_interval = -1;
curvefs::tools::CurvefsToolFactory curveToolFactory;
std::shared_ptr<curvefs::tools::CurvefsTool> curveTool =
curveToolFactory.GenerateCurvefsTool(command);
if (curveTool == nullptr) {
std::cout << curvefs::tools::kHelpStr << std::endl;
return -1;
}
if (FLAGS_example) {
curveTool->PrintHelp();
return 0;
}
return curveTool->Run();
}
|
6f8e54dec614a3cabff667cf5b67eed091ef8c66
|
e281e415d56392e84d317d7d55390d8c5eb0c483
|
/ObjecrOrientedDesign/Source/Books.cpp
|
d8815920cc6eef3e3ff9583278671d4fd7afb920
|
[] |
no_license
|
soheil647/Advance_Programming_Cpp
|
9ce99203404377e40e1bc16333f0f9c2ea99fef6
|
231e5b42cfd75e04df474c931969e80b8622222b
|
refs/heads/master
| 2020-12-28T15:15:08.717047
| 2020-08-19T14:41:54
| 2020-08-19T14:41:54
| 238,384,145
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 356
|
cpp
|
Books.cpp
|
#include "../Header/Books.h"
using namespace std;
Books::Books(int book_id, const std::string &book_title, int temp_author_id, const std::string &book_genres) {
id = book_id;
title = book_title;
author_id = temp_author_id;
genres = book_genres;
}
Books::Books(int book_id, float book_rate) {
id = book_id;
rate = book_rate;
}
|
3e5933d0b0f4e29f8bdab47b9100d82af4b5913a
|
28fa21455f49efffe9dc4302ef82d878428e9c5f
|
/src/test_thread_class.cpp
|
c3dcf321032a8442e36385f13126933241f13b31
|
[
"Apache-2.0"
] |
permissive
|
zhangkeplus/revolver
|
1051a9460a88b8bf75ce7304ad18be1b893c9d01
|
75e4fb32cd8b7f603cef61985f483a77e6a529b8
|
refs/heads/master
| 2020-12-11T07:54:27.552091
| 2015-10-07T07:15:06
| 2015-10-07T07:15:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,029
|
cpp
|
test_thread_class.cpp
|
#include "inc.h"
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "thread_class.h"
using cootek::revolver::thread_class;
class testc1 : public thread_class
{
public:
testc1() :
m_init(0),
m_cleanup(0)
{
}
void check1()
{
assert(m_init == 0);
assert(m_cleanup == 0);
}
void check2()
{
assert(m_init == 1);
assert(m_cleanup == 0);
}
void check3()
{
assert(m_init == 1);
assert(m_cleanup == 1);
}
protected:
virtual void thread_init()
{
m_init++;
}
virtual void thread_cleanup()
{
m_cleanup++;
}
private:
int m_init;
int m_cleanup;
};
BOOST_AUTO_TEST_CASE(thread_class_test1)
{
auto t1 = boost::make_shared<testc1>();
t1->check1();
t1->start();
t1->check2();
t1->stop();
t1->check3();
}
class testc2ex : public std::exception
{
};
class testc2 : public thread_class
{
public:
testc2() :
m_init(0),
m_cleanup(0)
{
}
void check1()
{
assert(m_init == 0);
assert(m_cleanup == 0);
}
void check2()
{
assert(m_init == 0);
assert(m_cleanup == 1);
}
void check3()
{
assert(m_init == 0);
assert(m_cleanup == 1);
}
protected:
virtual void thread_init()
{
throw testc2ex();
}
virtual void thread_cleanup()
{
m_cleanup++;
}
private:
int m_init;
int m_cleanup;
};
BOOST_AUTO_TEST_CASE(thread_class_test2)
{
auto t2 = boost::make_shared<testc2>();
t2->check1();
bool ex = false;
try
{
t2->start();
}
catch (std::exception &e)
{
ex = true;
}
BOOST_CHECK(ex);
t2->check2();
t2->stop();
t2->check3();
}
class testc3 : public thread_class
{
public:
testc3() :
m_init(0),
m_cleanup(0)
{
}
void check1()
{
assert(m_init == 0);
assert(m_cleanup == 0);
}
void check2()
{
assert(m_init == 1);
assert(m_cleanup == 0);
}
void check3()
{
assert(m_init == 1);
assert(m_cleanup == 1);
}
void do_ex()
{
m_async.send();
}
protected:
virtual void thread_init()
{
m_init++;
m_async.set(ev_loop());
m_async.set<testc3, &testc3::on_ev_exception>(this);
m_async.start();
}
virtual void thread_cleanup()
{
m_cleanup++;
m_async.stop();
}
private:
void on_ev_exception(ev::async &w, int revents)
{
std::cout << "throw exception" << std::endl;
throw testc2ex();
}
private:
int m_init;
int m_cleanup;
ev::async m_async;
};
BOOST_AUTO_TEST_CASE(thread_class_test3)
{
auto t2 = boost::make_shared<testc3>();
bool has_ex = false;
t2->check1();
t2->start([&has_ex](std::exception_ptr p)->void {has_ex = true;});
t2->check2();
t2->do_ex();
boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
assert(has_ex);
t2->check3();
}
class testc4 : public thread_class
{
};
BOOST_AUTO_TEST_CASE(thread_class_test4)
{
auto t2 = boost::make_shared<testc4>();
t2->start();
int c = 0;
for (int i = 0; i < 100; ++i)
{
c += 1;
t2->thread_execute([&c]() -> void {c += 1;});
}
t2->stop();
BOOST_CHECK_EQUAL(c, 200);
}
BOOST_AUTO_TEST_CASE(thread_class_test5)
{
auto t2 = boost::make_shared<testc4>();
t2->start();
int c = 0;
for (int i = 0; i < 100; ++i)
{
c += 1;
t2->thread_sync_execute<bool>([&c]() -> bool {c += 1; return true;});
}
BOOST_CHECK_EQUAL(c, 200);
}
BOOST_AUTO_TEST_CASE(thread_class_test6)
{
auto t2 = boost::make_shared<testc4>();
t2->start();
int c = 0;
for (int i = 0; i < 100; ++i)
{
c += 1;
t2->thread_sync_execute([&c]() -> void {c += 1;});
}
BOOST_CHECK_EQUAL(c, 200);
}
|
23127e777798667cb34554d9a24ff65fdbb73998
|
058dd18b93de675e53598012923f2148047a87b8
|
/GenericCombine/Main.cpp
|
c3d79cfc8f38c54254080ecfa7b270ac3fc99406
|
[
"MIT"
] |
permissive
|
invader35/SEN2UE9
|
92b43965c59d6a01315bb0154c0e52abc1a110ef
|
165b88d0b6e0f196cbdda0cd761d92054e2d51cc
|
refs/heads/master
| 2020-05-30T10:49:28.516457
| 2015-03-16T11:02:37
| 2015-03-16T11:02:37
| 10,665,486
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,307
|
cpp
|
Main.cpp
|
///////////////////////////////////////
// Workfile : Main.cpp
// Author : Matthias Schett
// Date : 27-05-2013
// Description : Combine if template
// Remarks : -
// Revision : 0
///////////////////////////////////////
#include <iostream>
#include "GenericCombine.h"
#include <vector>
#include <random>
#include <algorithm>
#include <iterator>
#include "RandomGen.h"
#include <ostream>
#include <list>
#include <set>
using namespace std;
int RandNum () {
return rgen::GetRandVal(1, 5);
}
int RandNumDobule () {
return rgen::GetRandVal(1000, 5000) / 500;
}
template <typename T>
T ProductSquare(T const &a, T const &b){
return static_cast<T>( (pow(a, 2) * pow(b,2)) );
}
template <typename T>
bool isPos(T const &a){
return a > 0;
}
void testInt(ostream &os = cout){
vector<int> myVec(5);
vector<int> myVec2(5);
vector<int> newVec(5);
//vector<int> newVec;
ostream_iterator<int> out_it (os, ", ");
generate(myVec.begin(), myVec.end(), RandNum);
generate(myVec2.begin(), myVec2.end(), RandNum);
combine_if(myVec.begin(), myVec.end(), myVec2.begin(), newVec.begin(), ProductSquare<int>, isPos<int>);
Print(myVec, "1. Original vector<int>");
os << endl;
Print(myVec2, "2. Original vector<int>");
os << endl;
Print(newVec, "Result vector<int>");
os << endl << endl;
}
void testIntList(ostream &os = cout){
list<int> myVec(5);
list<int> myVec2(5);
list<int> newVec(5);
ostream_iterator<int> out_it (os, ", ");
generate(myVec.begin(), myVec.end(), RandNum);
generate(myVec2.begin(), myVec2.end(), RandNum);
combine_if(myVec.begin(), myVec.end(), myVec2.begin(), newVec.begin(), ProductSquare<int>, isPos<int>);
Print(myVec, "1. Original list<float>");
os << endl;
Print(myVec2, "2. Original list<float>");
os << endl;
Print(newVec, "Result list<float>");
os << endl << endl;
}
void testFloat(ostream &os = cout){
vector<float> myVec(5);
vector<float> myVec2(5);
vector<float> newVec(5);
ostream_iterator<float> out_it (os, ", ");
generate(myVec.begin(), myVec.end(), RandNumDobule);
generate(myVec2.begin(), myVec2.end(), RandNumDobule);
combine_if(myVec.begin(), myVec.end(), myVec2.begin(), newVec.begin(), ProductSquare<float>, isPos<float>);
Print(myVec, "1. Original vector<float>");
os << endl;
Print(myVec2, "2. Original vector<float>");
os << endl;
Print(newVec, "Result vector<float>");
os << endl << endl;
}
void testFloatList(ostream &os = cout){
list<float> myVec(5);
list<float> myVec2(5);
list<float> newVec(5);
ostream_iterator<float> out_it (os, ", ");
generate(myVec.begin(), myVec.end(), RandNumDobule);
generate(myVec2.begin(), myVec2.end(), RandNumDobule);
combine_if(myVec.begin(), myVec.end(), myVec2.begin(), newVec.begin(), ProductSquare<float>, isPos<float>);
Print(myVec, "1, Original list<float>");
os << endl;
Print(myVec2, "2. Original list<float>");
os << endl;
Print(newVec, "Result list<float>");
os << endl << endl;
}
int main(){
rgen::Init();
ostream &os = cout;
testInt(os);
testIntList(os);
testFloat(os);
testFloatList(os);
cin.get();
return 0;
}
|
df1fc70bebc538c4c2148b0b4b8d0f721624488a
|
42a5316d14e8a3a01dd58eee2e63b3376a3fead9
|
/002 Even Fibonacci numbers.cpp
|
a071de155acb25feccbbca4d2434002aab898ff1
|
[
"MIT"
] |
permissive
|
satvik007/ProjectEuler
|
f76b9936002eca7d59e5f63de29c6bf7ae7628c4
|
6044cebe03672412d385a62bef827b28f0943cb6
|
refs/heads/master
| 2021-05-12T08:05:28.121197
| 2018-01-12T18:27:18
| 2018-01-12T18:27:18
| 117,266,819
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 804
|
cpp
|
002 Even Fibonacci numbers.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
//ifstream cin("in.txt");
int t;
cin >> t;
vector <long long int> a;
a.push_back(1); a.push_back(2);
long long current;
for(int i=2; a[i-1]<4e16; i++){
current = a[i-1] + a[i-2];
//cout << current << endl;
a.push_back(current);
}
vector <long long > b(a);
b[0] = 0;
for(int i=1; i<b.size(); i++){
if(b[i]%2 == 0) b[i]+=b[i-1];
else b[i] = b[i-1];
//cout << b[i] << endl;
}
while(t--){
long long n;
cin >> n;
int index = lower_bound(a.begin(), a.end(), n) - a.begin();
index--;
cout << b[index] << endl;
}
return 0;
}
|
6256bc17d9fa8337dabafb966228b60f30d18fcf
|
39921d049a882220193fb45f4023a6831fb79908
|
/Pods/gRPC-Core/src/core/lib/profiling/basic_timers.cc
|
3afcad8e44b21d3bb33bc21fb8bd17f724ef9741
|
[] |
no_license
|
furydeveloper/SearchCoinKaraoke
|
a48bb7f0a4032735a2fc8895bd6bb02626b392b3
|
98043d3e280814f75c4f6c7957e6c0eee320a9b9
|
refs/heads/master
| 2023-08-10T23:24:28.780365
| 2021-10-03T02:51:57
| 2021-10-03T02:51:57
| 409,012,702
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 129
|
cc
|
basic_timers.cc
|
version https://git-lfs.github.com/spec/v1
oid sha256:ef078c099ab36e2bd6326b34d1caabcbe1aa32a74048f1df1b3c87e4274a5473
size 7881
|
ff803a8f82e0b3e7a4d862af36c8033dc67d44fd
|
b73a46dcf05ab7ba0f079779dcae7b428b76c546
|
/C++/1044火星购物.cpp
|
fb789e6573dc2c9f435c07c56d9a9d8c7005ed6b
|
[] |
no_license
|
vei123/PATTestAdvanced
|
1a665f278e8cc88c4342ed8e8bd489530ca9ba69
|
222f6e8efa45fadd3a432ba88475d9476591aba8
|
refs/heads/main
| 2023-07-28T12:47:55.908453
| 2021-09-09T10:21:06
| 2021-09-09T10:21:06
| 392,303,394
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,143
|
cpp
|
1044火星购物.cpp
|
#include<iostream>
#include<vector>
using namespace std;
//看到N<=10^5,就知道一定得用O(n)复杂度的算法,自然想到"滑动窗口"法
struct segm
{
int i, j, val;
segm(int i, int j, int val) :i(i), j(j), val(val) { }
};
signed main()
{
ios::sync_with_stdio(0);
int n, m, d, a[100005];
vector<segm> ans;
int minlost = 0x7fffffff;
vector<segm> minlosts;
cin >> n >> m;
for (int k = 1; k <= n; k++) cin >> a[k];
int l = 1, r = 1, tsum = a[1];
while (r <= n)
{
if (tsum == m)
{
ans.push_back(segm(l, r, m));
tsum -= a[l];
l++;
}
else if (tsum < m)
{
r++;
tsum += a[r];
}
else
{
if (tsum < minlost)
{
minlost = tsum;
minlosts.clear();
minlosts.push_back(segm(l, r, tsum));
}
else if (tsum == minlost)
minlosts.push_back(segm(l, r, tsum));
tsum -= a[l];
l++;
}
}
if (ans.size())
{
for (int k = 0; k < ans.size(); k++)
{
if (k) cout << '\n';
cout << ans[k].i << '-' << ans[k].j;
}
}
else
{
for (int k = 0; k < minlosts.size(); k++)
{
if (k) cout << '\n';
cout << minlosts[k].i << '-' << minlosts[k].j;
}
}
return 0;
}
|
2f7ce87d10b0f69dfcf76c334a597d84dd8791af
|
2fdba81ab16f228d209afcb09cd683475b239f8b
|
/ConsoleApplication1/ConsoleApplication1/job_priority_compare.h
|
2ca1ee7bafaabad31460ce64936cfefef65a37b9
|
[] |
no_license
|
thatgirlprogrammer/OS_project
|
97a71e1ce63bc9b87d5431ac1fc1903060dd87e6
|
e56a6074f41438d75369e2223481676007373ceb
|
refs/heads/main
| 2023-01-20T02:49:39.571530
| 2020-12-07T15:41:43
| 2020-12-07T15:41:43
| 302,135,355
| 1
| 0
| null | 2020-10-28T00:03:35
| 2020-10-07T19:08:12
|
C++
|
UTF-8
|
C++
| false
| false
| 520
|
h
|
job_priority_compare.h
|
#pragma once
#include <vector>
#include "pcb.h"
namespace OSSim {
class priorities {
public:
priorities(PCB_info pcb_info) {
info = pcb_info;
}
bool operator< (const priorities other) const {
return info.pc.job_priority < other.info.pc.job_priority;
}
PCB_info get_pcb_info() {
return info;
}
void set_PCB_info(pcb pc, data d, buffer b, process_details pd) {
info.pc = pc;
info.d = d;
info.b = b;
info.pd = pd;
}
private:
PCB_info info;
};
}
|
9778f48193d0ccce730c5df291eca05b6ab9fa19
|
e6793e7eb54d2105c373a8af7ebc653b7ad94575
|
/bindings/pydrake/solvers/osqp_py.cc
|
1b27e795d58a1d629c9a18317cb0e736a57ca64a
|
[
"BSD-3-Clause"
] |
permissive
|
nikaven/drake
|
5c59e88f79b530ddf62496452959abeaf8fff1e3
|
34bab4ecaa34ac09ade6dcb11cf7bc0d13c5bd4e
|
refs/heads/master
| 2020-03-31T01:37:25.441270
| 2018-10-05T19:42:22
| 2018-10-05T19:42:22
| 151,788,663
| 7
| 0
| null | 2018-10-05T23:37:07
| 2018-10-05T23:37:07
| null |
UTF-8
|
C++
| false
| false
| 716
|
cc
|
osqp_py.cc
|
#include "pybind11/pybind11.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/solvers/osqp_solver.h"
namespace drake {
namespace pydrake {
PYBIND11_MODULE(osqp, m) {
using drake::solvers::OsqpSolver;
auto& doc = pydrake_doc.drake.solvers;
m.doc() = "OSQP solver bindings for MathematicalProgram";
py::object solverinterface =
py::module::import("pydrake.solvers.mathematicalprogram")
.attr("MathematicalProgramSolverInterface");
py::class_<OsqpSolver>(m, "OsqpSolver", solverinterface,
doc.OsqpSolver.doc).def(py::init<>(),
doc.OsqpSolver.ctor.doc);
}
} // namespace pydrake
} // namespace drake
|
1c5c193af946894ce68dc7900b120994b3afc837
|
2ba94892764a44d9c07f0f549f79f9f9dc272151
|
/Engine/Source/Runtime/SlateCore/Public/Fonts/SlateFontInfo.h
|
37dbd45ba9aa78e34142fb13dba8444116171513
|
[
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
PopCap/GameIdea
|
934769eeb91f9637f5bf205d88b13ff1fc9ae8fd
|
201e1df50b2bc99afc079ce326aa0a44b178a391
|
refs/heads/master
| 2021-01-25T00:11:38.709772
| 2018-09-11T03:38:56
| 2018-09-11T03:38:56
| 37,818,708
| 0
| 0
|
BSD-2-Clause
| 2018-09-11T03:39:05
| 2015-06-21T17:36:44
| null |
UTF-8
|
C++
| false
| false
| 6,014
|
h
|
SlateFontInfo.h
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Templates/TypeHash.h"
#include "CompositeFont.h"
#include "SlateFontInfo.generated.h"
/**
* A representation of a font in Slate.
*/
USTRUCT(BlueprintType)
struct SLATECORE_API FSlateFontInfo
{
GENERATED_USTRUCT_BODY()
/** The font object (valid when used from UMG or a Slate widget style asset) */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=SlateStyleRules, meta=(AllowedClasses="Font", DisplayName="Font Family"))
const UObject* FontObject;
/** The material to use when rendering this font */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=SlateStyleRules, meta=(AllowedClasses="MaterialInterface"))
const UObject* FontMaterial;
/** The composite font data to use (valid when used with a Slate style set in C++) */
TSharedPtr<const FCompositeFont> CompositeFont;
/** The name of the font to use from the default typeface (None will use the first entry) */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=SlateStyleRules, meta=(DisplayName="Font"))
FName TypefaceFontName;
/** The size of the font */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=SlateStyleRules)
int32 Size;
private:
/** The name of the font */
UPROPERTY()
FName FontName_DEPRECATED;
/** The hinting algorithm to use with the font */
UPROPERTY()
EFontHinting Hinting_DEPRECATED;
public:
/** Default constructor. */
FSlateFontInfo();
/**
* Creates and initializes a new instance with the specified font, size, and emphasis.
*
* @param InCompositeFont The font instance to use.
* @param InSize The size of the font.
* @param InTypefaceFontName The name of the font to use from the default typeface (None will use the first entry)
*/
FSlateFontInfo( TSharedPtr<const FCompositeFont> InCompositeFont, const int32 InSize, const FName& InTypefaceFontName = NAME_None );
/**
* Creates and initializes a new instance with the specified font, size, and emphasis.
*
* @param InFontObject The font instance to use.
* @param InSize The size of the font.
* @param InFamilyFontName The name of the font to use from the default typeface (None will use the first entry)
*/
FSlateFontInfo( const UObject* InFontObject, const int32 InSize, const FName& InTypefaceFontName = NAME_None );
/**
* DEPRECATED - Creates and initializes a new instance with the specified font name and size.
*
* @param InFontName The name of the font.
* @param InSize The size of the font.
* @param InHinting The type of hinting to use for the font.
*/
FSlateFontInfo( const FString& InFontName, uint16 InSize, EFontHinting InHinting = EFontHinting::Default );
/**
* DEPRECATED - Creates and initializes a new instance with the specified font name and size.
*
* @param InFontName The name of the font.
* @param InSize The size of the font.
* @param InHinting The type of hinting to use for the font.
*/
FSlateFontInfo( const FName& InFontName, uint16 InSize, EFontHinting InHinting = EFontHinting::Default );
/**
* DEPRECATED - Creates and initializes a new instance with the specified font name and size.
*
* @param InFontName The name of the font.
* @param InSize The size of the font.
* @param InHinting The type of hinting to use for the font.
*/
FSlateFontInfo( const ANSICHAR* InFontName, uint16 InSize, EFontHinting InHinting = EFontHinting::Default );
/**
* DEPRECATED - Creates and initializes a new instance with the specified font name and size.
*
* @param InFontName The name of the font.
* @param InSize The size of the font.
* @param InHinting The type of hinting to use for the font.
*/
FSlateFontInfo( const WIDECHAR* InFontName, uint16 InSize, EFontHinting InHinting = EFontHinting::Default );
public:
/**
* Compares this font info with another for equality.
*
* @param Other The other font info.
* @return true if the two font infos are equal, false otherwise.
*/
bool operator==( const FSlateFontInfo& Other ) const
{
return FontObject == Other.FontObject
&& FontMaterial == Other.FontMaterial
&& CompositeFont == Other.CompositeFont
&& TypefaceFontName == Other.TypefaceFontName
&& Size == Other.Size;
}
/**
* Compares this font info with another for inequality.
*
* @param Other The other font info.
*
* @return false if the two font infos are equal, true otherwise.
*/
bool operator!=( const FSlateFontInfo& Other ) const
{
return !(*this == Other);
}
/**
* Check to see whether this font info has a valid composite font pointer set (either directly or via a UFont)
*/
bool HasValidFont() const;
/**
* Get the composite font pointer associated with this font info (either directly or via a UFont)
* @note This function will return the fallback font if this font info itself does not contain a valid font. If you want to test whether this font info is empty, use HasValidFont
*/
const FCompositeFont* GetCompositeFont() const;
/**
* Calculates a type hash value for a font info.
*
* Type hashes are used in certain collection types, such as TMap.
*
* @param FontInfo The font info to calculate the hash for.
* @return The hash value.
*/
friend inline uint32 GetTypeHash( const FSlateFontInfo& FontInfo )
{
uint32 Hash = 0;
Hash = HashCombine(Hash, GetTypeHash(FontInfo.FontObject));
Hash = HashCombine(Hash, GetTypeHash(FontInfo.FontMaterial));
Hash = HashCombine(Hash, GetTypeHash(FontInfo.CompositeFont));
Hash = HashCombine(Hash, GetTypeHash(FontInfo.TypefaceFontName));
Hash = HashCombine(Hash, GetTypeHash(FontInfo.Size));
return Hash;
}
/**
* Used to upgrade legacy font into so that it uses composite fonts
*/
void PostSerialize(const FArchive& Ar);
private:
/**
* Used to upgrade legacy font into so that it uses composite fonts
*/
void UpgradeLegacyFontInfo();
};
template<>
struct TStructOpsTypeTraits<FSlateFontInfo>
: public TStructOpsTypeTraitsBase
{
enum
{
WithPostSerialize = true,
};
};
|
88a791c78943e63dd3d8061b5de8d3ca62670085
|
825baf7b3ecbcbdcd2f8b86179a802739ba3636c
|
/src/systems/sources/depth.cpp
|
ea2e668ef603c61c2689b85f11bacf26b229706d
|
[
"MIT"
] |
permissive
|
brucelevis/zenith
|
1c8fcdb273c7497a73046f1d1a9112f7c8f9ebfb
|
eeef065ed62f35723da87c8e73a6716e50d34060
|
refs/heads/master
| 2023-08-28T21:28:05.552328
| 2021-10-15T19:14:13
| 2021-10-15T19:14:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 710
|
cpp
|
depth.cpp
|
/**
* @file
* @author __AUTHOR_NAME__ <mail@host.com>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#include "../depth.hpp"
#include "../../utils/assert.hpp"
#include "../../components/depth.hpp"
namespace Zen {
extern entt::registry g_registry;
int GetDepth (Entity entity)
{
auto depth = g_registry.try_get<Components::Depth>(entity);
ZEN_ASSERT(depth, "The entity has no 'Depth' component.");
return depth->value;
}
void SetDepth (Entity entity, int value)
{
auto depth = g_registry.try_get<Components::Depth>(entity);
ZEN_ASSERT(depth, "The entity has no 'Depth' component.");
depth->value = value;
}
} // namespace Zen
|
c73dca1207d1ee15b1fa616fba28cb7fd0951555
|
c054ffed0df3565ce5a52321db273219275c6ca5
|
/src/yart_core/sphere.h
|
9e6770f83cafc688feda525be5976b7d1295c0d9
|
[] |
no_license
|
stevegocoding/yart
|
8ba0d059485f08e3a8eec31bdbec223512d2b71b
|
01505cc0e989cee41ba0e7617c9e6acb511447fe
|
refs/heads/master
| 2016-09-03T07:08:28.078837
| 2012-06-16T02:15:03
| 2012-06-16T02:15:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 421
|
h
|
sphere.h
|
#pragma once
#include "prerequisites.h"
#include "shape.h"
class c_sphere : public c_shape
{
typedef c_shape super;
public:
c_sphere(float radius, float z_min, float z_max, float phi_max_deg);
// virtual bool intersects(const c_ray& ray, float *t_hit, float *ray_epsilon) const;
private:
float m_radius;
float m_phi_max;
float m_z_min, m_z_max;
float m_theta_min, m_theta_max;
};
|
fc90e56534d4437011773538b7969c7a91f7d43b
|
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
|
/codeforce/581-620/600/f2.cpp
|
04a491e2a4d7fd80668836f70e61b02ec041d16b
|
[] |
no_license
|
kmjp/procon
|
27270f605f3ae5d80fbdb28708318a6557273a57
|
8083028ece4be1460150aa3f0e69bdb57e510b53
|
refs/heads/master
| 2023-09-04T11:01:09.452170
| 2023-09-03T15:25:21
| 2023-09-03T15:25:21
| 30,825,508
| 23
| 2
| null | 2023-08-18T14:02:07
| 2015-02-15T11:25:23
|
C++
|
UTF-8
|
C++
| false
| false
| 2,995
|
cpp
|
f2.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int N,M,K,Q;
vector<pair<int,int>> E[101010];
vector<pair<int,ll>> E2[101010];
int from[101010];
ll dist[101010];
int P[21][200005],D[200005];
ll ma[21][200005];
template<int um> class UF {
public:
vector<int> par,rank;
UF() {rank=vector<int>(um,0); for(int i=0;i<um;i++) par.push_back(i);}
int operator[](int x) {return (par[x]==x)?(x):(par[x] = operator[](par[x]));}
int operator()(int x,int y) {
if((x=operator[](x))==(y=operator[](y))) return x;
if(rank[x]>rank[y]) return par[x]=y;
rank[x]+=rank[x]==rank[y]; return par[y]=x;
}
};
UF<500000> uf;
void dfs(int cur) {
FORR(e,E2[cur]) if(e.first!=P[0][cur]) {
D[e.first]=D[cur]+1;
P[0][e.first]=cur;
ma[0][e.first]=e.second;
dfs(e.first);
}
}
int lca(int a,int b) {
int ret=0,i,aa=a,bb=b;
if(D[aa]>D[bb]) swap(aa,bb);
for(i=19;i>=0;i--) if(D[bb]-D[aa]>=1<<i) bb=P[i][bb];
for(i=19;i>=0;i--) if(P[i][aa]!=P[i][bb]) aa=P[i][aa], bb=P[i][bb];
return (aa==bb)?aa:P[0][aa]; // vertex
}
void solve() {
int i,j,k,l,r,x,y; string s;
scanf("%d%d%d%d",&N,&M,&K,&Q);
FOR(i,M) {
scanf("%d%d%d",&x,&y,&r);
E[x-1].push_back({y-1,r});
E[y-1].push_back({x-1,r});
}
priority_queue<pair<ll,int>> PQ;
FOR(i,N) {
if(i<K) from[i]=i, PQ.push({0,i});
else dist[i]=1LL<<60;
}
while(PQ.size()) {
ll co=-PQ.top().first;
int cur=PQ.top().second;
PQ.pop();
if(dist[cur]!=co) continue;
FORR(e,E[cur]) if(dist[e.first]>co+e.second) {
dist[e.first]=co+e.second;
from[e.first]=from[cur];
PQ.push({-dist[e.first],e.first});
}
}
vector<vector<ll>> Es;
FOR(i,N) FORR(e,E[i]) if(from[e.first]>from[i]) {
Es.push_back({dist[i]+dist[e.first]+e.second,from[i],from[e.first]});
}
sort(ALL(Es));
FORR(e,Es) {
if(uf[e[1]]!=uf[e[2]]) {
uf(e[1],e[2]);
E2[e[1]].push_back({e[2],e[0]});
E2[e[2]].push_back({e[1],e[0]});
}
}
dfs(0);
FOR(i,19) FOR(x,K) {
P[i+1][x]=P[i][P[i][x]];
ma[i+1][x]=max(ma[i][x],ma[i][P[i][x]]);
}
while(Q--) {
scanf("%d%d",&x,&y);
x--;
y--;
int lc=lca(x,y);
ll ret=0;
for(i=18;i>=0;i--) {
if(D[x]-D[lc]>=1<<i) ret=max(ret,ma[i][x]), x=P[i][x];
if(D[y]-D[lc]>=1<<i) ret=max(ret,ma[i][y]), y=P[i][y];
}
cout<<ret<<endl;
}
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
cout.tie(0); solve(); return 0;
}
|
27b331a9b6c6470cb348b39bcf157b74e8dbb5cb
|
afb71a8e6d26990b044debda5367188a898723d6
|
/cpp/methods/greedy_linear_oblivious_trees_v2.h
|
aaef23130e334869dcfcf31c2c99b51350f3ef6f
|
[
"Apache-2.0"
] |
permissive
|
equivalence1/ml_lib
|
cf4d1c45167958051d4a4422e10c382f2e6d19af
|
92d75ab73bc2d77ba8fa66022c803c06cad66f21
|
refs/heads/master
| 2021-08-22T08:09:39.593877
| 2020-02-10T07:44:34
| 2020-02-10T07:44:34
| 150,852,557
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,062
|
h
|
greedy_linear_oblivious_trees_v2.h
|
#pragma once
#include <unordered_set>
#include <vector>
#include <memory>
#include "optimizer.h"
#include <models/model.h>
#include <data/grid.h>
#include <models/bin_optimized_model.h>
class GreedyLinearObliviousTreeLearnerV2;
class BinStat {
public:
explicit BinStat(int size, int filledSize)
: size_(size)
, filledSize_(filledSize) {
for (int i = 0; i < size; ++i) {
XTX_.emplace_back(i + 1, 0.0);
}
XTy_ = std::vector<double>(size, 0.0);
cnt_ = 0;
trace_ = 0.0;
maxUpdatedPos_ = filledSize_;
}
void reset() {
cnt_ = 0;
trace_ = 0;
for (int i = 0; i <= filledSize_; ++i) {
for (int j = 0; j < i + 1; ++j) {
XTX_[i][j] = 0;
}
XTy_[i] = 0;
}
filledSize_ = 0;
}
void setFilledSize(int filledSize) {
filledSize_ = filledSize;
}
int filledSize() {
return filledSize_;
}
void addNewCorrelation(const std::vector<double>& xtx, double xty) {
assert(xtx.size() >= filledSize_ + 1);
for (int i = 0; i <= filledSize_; ++i) {
XTX_[filledSize_][i] += xtx[i];
}
XTy_[filledSize_] += xty;
trace_ += xtx[filledSize_];
maxUpdatedPos_ = filledSize_ + 1;
}
void addFullCorrelation(Vec x, double y) {
assert(x.size() >= filledSize_);
auto xRef = x.arrayRef();
for (int i = 0; i < filledSize_; ++i) {
XTy_[i] += xRef[i] * y;
}
for (int i = 0; i < filledSize_; ++i) {
for (int j = i; j < filledSize_; ++j) {
XTX_[j][i] += xRef[i] * xRef[j]; // TODO change order, this one is bad for caches
}
}
cnt_ += 1;
}
Mx getXTX() const {
Mx res(maxUpdatedPos_, maxUpdatedPos_);
auto resRef = res.arrayRef();
for (int i = 0; i < maxUpdatedPos_; ++i) {
for (int j = 0; j < i + 1; ++j) {
int pos = i * maxUpdatedPos_ + j;
resRef[pos] = XTX_[i][j];
pos = j * maxUpdatedPos_ + i;
resRef[pos] = XTX_[i][j];
}
}
return res;
}
Mx getXTy() const {
Mx res(maxUpdatedPos_, 1);
auto resRef = res.arrayRef();
for (int i = 0; i < maxUpdatedPos_; ++i) {
resRef[i] = XTy_[i];
}
return res;
}
uint32_t getCnt() {
return cnt_;
}
double getTrace() {
return trace_;
}
// This one DOES NOT add up new correlations
BinStat& operator+=(const BinStat& s) {
assert(filledSize_ == s.filledSize_);
cnt_ += s.cnt_;
trace_ += s.trace_;
for (int i = 0; i < filledSize_; ++i) {
for (int j = 0; j < i + 1; ++j) {
XTX_[i][j] += s.XTX_[i][j];
}
XTy_[i] += s.XTy_[i];
}
}
// This one DOES NOT subtract new correlations
BinStat& operator-=(const BinStat& s) {
cnt_ -= s.cnt_;
trace_ -= s.trace_;
for (int i = 0; i < filledSize_; ++i) {
for (int j = 0; j < i + 1; ++j) {
XTX_[i][j] -= s.XTX_[i][j];
}
XTy_[i] -= s.XTy_[i];
}
}
private:
friend BinStat operator+(const BinStat& lhs, const BinStat& rhs);
friend BinStat operator-(const BinStat& lhs, const BinStat& rhs);
private:
int size_;
int filledSize_;
int maxUpdatedPos_;
std::vector<std::vector<double>> XTX_;
std::vector<double> XTy_;
uint32_t cnt_;
double trace_;
};
inline BinStat operator+(const BinStat& lhs, const BinStat& rhs) {
BinStat res(lhs);
res += rhs;
return res;
}
inline BinStat operator-(const BinStat& lhs, const BinStat& rhs) {
BinStat res(lhs);
res -= rhs;
return res;
}
class HistogramV2 {
public:
HistogramV2(BinarizedDataSet& bds, GridPtr grid, unsigned int nUsedFeatures, int lastUsedFeatureId);
void addFullCorrelation(int bin, Vec x, double y);
void addNewCorrelation(int bin, const std::vector<double>& xtx, double xty);
void prefixSumBins();
void addBinStat(int bin, const BinStat& stats);
std::pair<double, double> splitScore(int fId, int condId, double l2reg, double traceReg);
std::shared_ptr<Mx> getW(double l2reg);
void printEig(double l2reg);
void printCnt();
void print();
HistogramV2& operator+=(const HistogramV2& h);
HistogramV2& operator-=(const HistogramV2& h);
private:
static double computeScore(Mx& XTX, Mx& XTy, double XTX_trace, uint32_t cnt, double l2reg,
double traceReg);
static void printEig(Mx& M);
friend HistogramV2 operator-(const HistogramV2& lhs, const HistogramV2& rhs);
friend HistogramV2 operator+(const HistogramV2& lhs, const HistogramV2& rhs);
private:
BinarizedDataSet& bds_;
GridPtr grid_;
std::vector<BinStat> hist_;
int lastUsedFeatureId_ = -1;
unsigned int nUsedFeatures_;
friend class GreedyLinearObliviousTreeLearnerV2;
};
class LinearObliviousTreeLeafV2;
class GreedyLinearObliviousTreeLearnerV2 final
: public Optimizer {
public:
explicit GreedyLinearObliviousTreeLearnerV2(GridPtr grid, int32_t maxDepth = 6, int biasCol = -1,
double l2reg = 0.0, double traceReg = 0.0)
: grid_(std::move(grid))
, biasCol_(biasCol)
, maxDepth_(maxDepth)
, l2reg_(l2reg)
, traceReg_(traceReg) {
}
GreedyLinearObliviousTreeLearnerV2(const GreedyLinearObliviousTreeLearnerV2& other) = default;
ModelPtr fit(const DataSet& dataSet, const Target& target) override;
private:
void cacheDs(const DataSet& ds);
private:
GridPtr grid_;
int32_t maxDepth_ = 6;
int biasCol_ = -1;
double l2reg_ = 0.0;
double traceReg_ = 0.0;
bool isDsCached_ = false;
std::vector<Vec> fColumns_;
std::vector<ConstVecRef<float>> fColumnsRefs_;
// thread leaf bin coordinate
std::vector<std::vector<std::vector<std::vector<double>>>> h_XTX_;
std::vector<std::vector<std::vector<double>>> h_XTy_;
std::vector<std::vector<std::vector<BinStat>>> stats_;
ConstVecRef<int32_t> binOffsets_;
int nThreads_;
int totalBins_;
};
class LinearObliviousTreeV2 final
: public Stub<Model, LinearObliviousTreeV2>
, std::enable_shared_from_this<LinearObliviousTreeV2> {
public:
LinearObliviousTreeV2(const LinearObliviousTreeV2& other, double scale)
: Stub<Model, LinearObliviousTreeV2>(other.gridPtr()->origFeaturesCount(), 1) {
grid_ = other.grid_;
scale_ = scale;
leaves_ = other.leaves_;
}
LinearObliviousTreeV2(GridPtr grid, std::vector<std::shared_ptr<LinearObliviousTreeLeafV2>> leaves)
: Stub<Model, LinearObliviousTreeV2>(grid->origFeaturesCount(), 1)
, grid_(std::move(grid))
, leaves_(std::move(leaves)) {
scale_ = 1;
}
explicit LinearObliviousTreeV2(GridPtr grid)
: Stub<Model, LinearObliviousTreeV2>(grid->origFeaturesCount(), 1)
, grid_(std::move(grid)) {
}
Grid grid() const {
return *grid_.get();
}
GridPtr gridPtr() const {
return grid_;
}
// I have now idea what this function should do...
// For now just adding value(x) to @param to.
void appendTo(const Vec& x, Vec to) const override;
// void applyToBds(const BinarizedDataSet& ds, Mx to, ApplyType type) const override;
// void applyBinarizedRow(const Buffer<uint8_t>& x, Vec to) const;
double value(const Vec& x) override;
void grad(const Vec& x, Vec to) override;
private:
friend class GreedyLinearObliviousTreeLearnerV2;
double value(const Vec& x) const;
private:
GridPtr grid_;
double scale_ = 1;
std::vector<std::shared_ptr<LinearObliviousTreeLeafV2>> leaves_;
};
|
6e3873c6938b1e4ad22d68966e25fafefafa5dfe
|
aacc7ecfb6a23aa5a13e7cd872d2c2ea3053858d
|
/Binary Search/Matrix Median.cpp
|
c1d4355c639f33f2c993f2a3fb98aaf779013742
|
[] |
no_license
|
pranayagr/InterviewBit
|
4dd7a300ced59920904dc2dedb9f1035a7201705
|
4031abac73dc56ee5f4b53ed797353d34d9362bd
|
refs/heads/main
| 2023-05-13T01:11:14.979359
| 2021-06-04T18:26:23
| 2021-06-04T18:26:23
| 326,433,528
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 575
|
cpp
|
Matrix Median.cpp
|
int Solution::findMedian(vector<vector<int> > &A) {
int m = A.size(), n = A[0].size();
int a = INT_MAX, b = INT_MIN, k = (m*n+1)/2, mid;
for(int i = 0 ; i < m ; i++){
a = min(a,A[i][0]);
b = max(b,A[i][n-1]);
}
while(a < b){
mid = a + (b-a)/2;
int count = 0;
for(int i = 0 ; i < m ; i++){
count += upper_bound(A[i].begin(),A[i].end(),mid)-A[i].begin();
}
if(count < k){
a = mid + 1;
}
else{
b = mid;
}
}
return a;
}
|
e24e7106c10e02fb38cae78ed9497de17c7ce1f1
|
37d5c87b8dbdd8d430870de3e5a3714ed47e126d
|
/hihocoder21.cpp
|
ad21c8787161f701c1318a0790a1b444f78c3d31
|
[] |
no_license
|
cczhong11/hihocoder
|
981c17c52be8cb7ee75e4b68f8a8612a06d4cde8
|
e7fd66bebaef69ed8d99f9664a88dd7252925aa3
|
refs/heads/master
| 2021-01-22T23:43:17.023952
| 2017-03-22T04:27:32
| 2017-03-22T04:27:32
| 85,664,804
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,489
|
cpp
|
hihocoder21.cpp
|
#include <algorithm>
#include <vector>
#include <set>
#include <cstdio>
#define RM 1000000010
#define MAX 100020
#define LL long long
using namespace std;
LL index_R[MAX], index_L[MAX];
int c[2*MAX],lazy[2*MAX];
vector<LL> v;
set<int> ss;
int getid(int x)
{
return lower_bound(v.begin(),v.end(),x)-v.begin()+1;
}
void push_up(int rt)
{
if((c[rt<<1]!=c[rt<<1|1])||(c[rt<<1|1]!=c[rt]))
{c[rt]=-1;lazy[rt] = 0;}
}
void push_down(int rt)
{
if(lazy[rt])
{
lazy[rt<<1] = lazy[rt<<1|1] = lazy[rt];
c[rt<<1] = c[rt<<1|1] = c[rt];
lazy[rt] = 0;
c[rt]=-1;
}
}
void build(int l, int r)
{
for(int i = l;i<r+1; i++)
{
c[i] = -1;
lazy[i] = 0;
}
}
void update(int L, int R, int c0, int l, int r, int rt)
{
if(l==r) {
lazy[rt] = c0;
c[rt] = c0;
return;
}
//printf("%d %d %d %d %d %d \n",rt,c[rt],l,r,L,R);
if(L<=l && r<=R)
{
lazy[rt] = c0;
c[rt] = c0;
return;
}
push_down(rt);
int m = (l+r) >> 1;
if(L<m) update(L,R,c0,l,m,rt<<1);
if(m<R) update(L,R,c0,m,r,rt<<1|1);
push_up(rt);
}
void query(int l,int r,int rt)
{
if(l+1>=r) {
if(c[rt]!=-1&&c[rt]!=0)
ss.insert(c[rt]);
//printf("%d %d \n",rt,c[rt]);
return;
}
//printf("%d %d %d %d \n",rt,c[rt],l,r);
if(lazy[rt]&&c[rt]!=-1&&c[rt]!=0)
{
//printf("%d %d \n",rt,c[rt]);
ss.insert(c[rt]);
return;
}
push_down(rt);
int m = (l+r) >> 1;
query(l,m,rt<<1);
query(m,r,rt<<1|1);
return;
}
int query(int siz)
{
ss.clear();
for(int i = 1; i < siz+1;i++)
{
//printf("%d %d\n",i,c[i]);
if(c[i]!=-1||c[i]!=0)
ss.insert(c[i]);
}
return ss.size();
}
int main()
{
int N,M;
//freopen("in21.txt", "r", stdin);
//memset(tree,0,sizeof(tree));
v.clear();
scanf("%d %d",&N,&M);
for(int i=0;i<N;i++)
{
scanf("%d %d",&index_L[i],&index_R[i]);
v.push_back(index_L[i]);
v.push_back(index_R[i]);
}
sort(v.begin(),v.end());
v.erase(unique(v.begin(),v.end()),v.end());
int N2=v.size();
build(0,2*N2);
for(int i=0;i<N;i++)
{
update(getid(index_L[i]),getid(index_R[i]),i+1,0,N2,1);
}
//printf("---------------------------");
query(0,N2,1);
int result = ss.size();//query(2*N2);
printf("%d\n", result);
}
|
9da149c3f6a159609f3e1f51c84a5ea1b2e27fc7
|
6114187e8f0a727a9128483a20556e824b16b907
|
/src/main.cpp
|
ad1bf8999606b80ebc3242b975f8079183129dcb
|
[
"MIT"
] |
permissive
|
jipp/theBadge
|
5f4bde300e356410e3fb90d8641053541acad80b
|
954b3b95124bc6adb61a6a49a86daf51e4139049
|
refs/heads/master
| 2020-12-19T02:04:39.633904
| 2020-01-26T17:51:57
| 2020-01-26T17:51:57
| 235,588,138
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,278
|
cpp
|
main.cpp
|
#include <Arduino.h>
// TODO (jipp): upload info via web services, list files, delete files, upload files
#define ARDUINOJSON_ENABLE_STD_STRING 1
#define ENABLE_GxEPD2_GFX 0
#include <iostream>
#include <ArduinoJson.h>
#include <Bounce2.h>
#include <DNSServer.h>
#include <GxEPD2_BW.h>
#include <SPI.h>
#include <SPIFFS.h>
#include <Ticker.h>
#include <WebServer.h>
#include <WiFi.h>
#include <Fonts/FreeMono9pt7b.h>
#include <Fonts/FreeMonoBold12pt7b.h>
#include <Fonts/FreeMonoBold18pt7b.h>
const uint8_t BUTTON_1 = 39;
const uint8_t BUTTON_2 = 37;
const uint8_t BUTTON_3 = 38;
const int SLEEP_TIME = 120; // seconds
const int GRACE_TIME = 10; // seconds
DNSServer dnsServer;
WebServer webServer(80);
GxEPD2_BW<GxEPD2_290, GxEPD2_290::HEIGHT> display(GxEPD2_290(/*CS=5*/ 5, /*DC=*/17, /*RST=*/16, /*BUSY=*/4));
DynamicJsonDocument jsonDocConfig(2048);
Bounce button1 = Bounce();
Bounce button2 = Bounce();
Bounce button3 = Bounce();
Ticker goToSleep = Ticker();
const char *filename = "/config.json";
const char Header[] PROGMEM = "HTTP/1.1 303 OK\r\nLocation:spiffs.html\r\nCache-Control: no-cache\r\n";
const char Helper[] PROGMEM = R"(<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="upload"><input type="submit" value="Upload"></form>Lade die spiffs.html hoch.)";
static const uint16_t input_buffer_pixels = 800; // may affect performance
static const uint16_t max_row_width = 800; // for up to 7.5" display 800x480
static const uint16_t max_palette_pixels = 256; // for depth <= 8
uint8_t input_buffer[3 * input_buffer_pixels]; // up to depth 24
uint8_t output_row_mono_buffer[max_row_width / 8]; // buffer for at least one row of b/w bits
uint8_t output_row_color_buffer[max_row_width / 8]; // buffer for at least one row of color bits
uint8_t mono_palette_buffer[max_palette_pixels / 8]; // palette buffer for depth <= 8 b/w
uint8_t color_palette_buffer[max_palette_pixels / 8]; // palette buffer for depth <= 8 c/w
// bmp handling
uint16_t read16(fs::File &f)
{
// BMP data is stored little-endian, same as Arduino.
uint16_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read(); // MSB
return result;
}
uint32_t read32(fs::File &f)
{
// BMP data is stored little-endian, same as Arduino.
uint32_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read();
((uint8_t *)&result)[2] = f.read();
((uint8_t *)&result)[3] = f.read(); // MSB
return result;
}
int drawBitmap(const char *filename, int16_t x, int16_t y, bool with_color)
{
fs::File file;
bool valid = false; // valid format to be handled
bool flip = true; // bitmap is stored bottom-to-top
uint32_t startTime = millis();
uint32_t value;
if ((x >= display.width()) || (y >= display.height()))
return 0;
if (!SPIFFS.exists(filename))
{
std::cout << "File not found" << std::endl;
return 0;
}
std::cout << "Loading image '" << filename << '\'' << std::endl;
file = SPIFFS.open(filename, FILE_READ);
// Parse BMP header
if (read16(file) == 0x4D42)
{ // BMP signature
uint32_t fileSize = read32(file);
uint32_t creatorBytes = read32(file);
uint32_t imageOffset = read32(file); // Start of image data
uint32_t headerSize = read32(file);
uint32_t width = read32(file);
uint32_t height = read32(file);
uint16_t planes = read16(file);
uint16_t depth = read16(file); // bits per pixel
uint32_t format = read32(file);
if ((planes == 1) && ((format == 0) || (format == 3)))
{ // uncompressed is handled, 565 also
std::cout << "File size: " << fileSize << std::endl;
std::cout << "Image Offset: " << imageOffset << std::endl;
std::cout << "Header size: " << headerSize << std::endl;
std::cout << "Bit Depth: " << depth << std::endl;
std::cout << "Image size: " << width << 'x' << height << std::endl;
// BMP rows are padded (if needed) to 4-byte boundary
value = width;
uint32_t rowSize = (width * depth / 8 + 3) & ~3;
if (depth < 8)
{
rowSize = ((width * depth + 8 - depth) / 8 + 3) & ~3;
}
if (height < 0)
{
height = -height;
flip = false;
}
uint16_t w = width;
uint16_t h = height;
if ((x + w - 1) >= display.width())
{
w = display.width() - x;
}
if ((y + h - 1) >= display.height())
{
h = display.height() - y;
}
valid = true;
uint8_t bitmask = 0xFF;
uint8_t bitshift = 8 - depth;
uint16_t red, green, blue;
bool whitish, colored;
if (depth == 1)
{
with_color = false;
}
if (depth <= 8)
{
if (depth < 8)
{
bitmask >>= depth;
}
file.seek(54); //palette is always @ 54
for (uint16_t pn = 0; pn < (1 << depth); pn++)
{
blue = file.read();
green = file.read();
red = file.read();
file.read();
whitish = with_color ? ((red > 0x80) && (green > 0x80) && (blue > 0x80)) : ((red + green + blue) > 3 * 0x80); // whitish
colored = (red > 0xF0) || ((green > 0xF0) && (blue > 0xF0));
// reddish or yellowish?
if (0 == pn % 8)
{
mono_palette_buffer[pn / 8] = 0;
}
mono_palette_buffer[pn / 8] |= whitish << pn % 8;
if (0 == pn % 8)
{
color_palette_buffer[pn / 8] = 0;
}
color_palette_buffer[pn / 8] |= colored << pn % 8;
}
}
display.fillScreen(GxEPD_WHITE);
uint32_t rowPosition = flip ? imageOffset + (height - h) * rowSize : imageOffset;
for (uint16_t row = 0; row < h; row++, rowPosition += rowSize)
{ // for each line
uint32_t in_remain = rowSize;
uint32_t in_idx = 0;
uint32_t in_bytes = 0;
uint8_t in_byte = 0; // for depth <= 8
uint8_t in_bits = 0; // for depth <= 8
uint16_t color = GxEPD_WHITE;
file.seek(rowPosition);
for (uint16_t col = 0; col < w; col++)
{ // for each pixel
// Time to read more pixel data?
if (in_idx >= in_bytes)
{ // ok, exact match for 24bit also (size IS multiple of 3)
in_bytes = file.read(input_buffer, in_remain > sizeof(input_buffer) ? sizeof(input_buffer) : in_remain);
in_remain -= in_bytes;
in_idx = 0;
}
switch (depth)
{
case 24:
blue = input_buffer[in_idx++];
green = input_buffer[in_idx++];
red = input_buffer[in_idx++];
whitish = with_color ? ((red > 0x80) && (green > 0x80) && (blue > 0x80)) : ((red + green + blue) > 3 * 0x80); // whitish
colored = (red > 0xF0) || ((green > 0xF0) && (blue > 0xF0)); // reddish or yellowish?
break;
case 16:
{
uint8_t lsb = input_buffer[in_idx++];
uint8_t msb = input_buffer[in_idx++];
if (format == 0)
{ // 555
blue = (lsb & 0x1F) << 3;
green = ((msb & 0x03) << 6) | ((lsb & 0xE0) >> 2);
red = (msb & 0x7C) << 1;
}
else
{ // 565
blue = (lsb & 0x1F) << 3;
green = ((msb & 0x07) << 5) | ((lsb & 0xE0) >> 3);
red = (msb & 0xF8);
}
whitish = with_color ? ((red > 0x80) && (green > 0x80) && (blue > 0x80)) : ((red + green + blue) > 3 * 0x80); // whitish
colored = (red > 0xF0) || ((green > 0xF0) && (blue > 0xF0)); // reddish or yellowish?
}
break;
case 1:
case 4:
case 8:
{
if (0 == in_bits)
{
in_byte = input_buffer[in_idx++];
in_bits = 8;
}
uint16_t pn = (in_byte >> bitshift) & bitmask;
whitish = mono_palette_buffer[pn / 8] & (0x1 << pn % 8);
colored = color_palette_buffer[pn / 8] & (0x1 << pn % 8);
in_byte <<= depth;
in_bits -= depth;
}
break;
}
if (whitish)
{
color = GxEPD_WHITE;
}
else if (colored && with_color)
{
color = GxEPD_RED;
}
else
{
color = GxEPD_BLACK;
}
uint16_t yrow = y + (flip ? h - row - 1 : row);
display.drawPixel(x + col, yrow, color);
} // end pixel
} // end line
std::cout << "loaded in " << millis() - startTime << " ms" << std::endl;
}
}
file.close();
if (!valid)
{
std::cout << "bitmap format not handled." << std::endl;
return 0;
}
return value;
}
void deepSleep()
{
std::cout << "going to sleep!" << std::endl;
esp_sleep_enable_ext0_wakeup(GPIO_NUM_39, 0);
esp_sleep_enable_timer_wakeup(SLEEP_TIME * 1000000);
esp_deep_sleep_start();
}
bool loadConfiguration(const char *filename, DynamicJsonDocument &jsonDoc)
{
fs::File file;
std::cout << "load configuration" << std::endl;
if (SPIFFS.exists(filename))
{
std::cout << "open file" << std::endl;
file = SPIFFS.open(filename, FILE_READ);
}
else
{
std::cout << "file does not exist" << std::endl;
}
if (deserializeJson(jsonDoc, file))
{
std::cout << "Failed to read file, using default configuration" << std::endl;
jsonDoc["active"] = 0;
jsonDoc["screens"][0]["bmp"] = "";
jsonDoc["screens"][0]["title"] = "title0";
jsonDoc["screens"][0]["text"][0] = "text0";
jsonDoc["screens"][0]["text"][1] = "text1";
return false;
}
file.close();
return true;
}
void saveConfiguration(const char *filename, DynamicJsonDocument &jsonDoc)
{
fs::File file;
std::cout << "save configuration" << std::endl;
SPIFFS.remove(filename);
file = SPIFFS.open(filename, FILE_WRITE);
if (!file)
{
std::cout << "Failed to create file" << std::endl;
}
if (serializeJsonPretty(jsonDoc, file) == 0)
{
std::cout << "Failed to write to file" << std::endl;
}
file.close();
}
void printFile(const char *filename)
{
fs::File file = SPIFFS.open(filename, FILE_READ);
if (!file)
{
std::cout << "Failed to read file" << std::endl;
return;
}
while (file.available())
{
std::cout << (char)file.read();
}
std::cout << std::endl;
file.close();
}
void displayScreen(DynamicJsonDocument &jsonDoc, int active, int total)
{
JsonArray array;
int line = 1;
int offsetFont = 20;
int offsetPicture = 8;
display.setRotation(1);
display.setTextColor(GxEPD_BLACK);
display.setFullWindow();
display.fillScreen(GxEPD_WHITE);
offsetPicture += drawBitmap(jsonDoc["screens"][jsonDoc["active"].as<signed int>()]["bmp"].as<char *>(), 0, 0, true);
display.setFont(&FreeMonoBold18pt7b);
display.setCursor(offsetPicture, 18 + offsetFont);
display.println(jsonDoc["screens"][jsonDoc["active"].as<signed int>()]["title"].as<char *>());
display.setFont(&FreeMonoBold12pt7b);
array = jsonDoc["screens"][jsonDoc["active"].as<signed int>()]["text"];
for (JsonVariant v : array)
{
line++;
display.setCursor(offsetPicture, 30 + line * offsetFont);
display.println(v.as<char *>());
}
display.setFont(&FreeMono9pt7b);
display.setCursor(display.width() - 40, display.height() - 10);
display.print(active);
display.print("/");
display.println(total);
display.display(false);
display.hibernate();
}
void switchScreen(DynamicJsonDocument &jsonDoc, int increment)
{
int total = jsonDoc["screens"].size();
int active = jsonDoc["active"].as<signed int>();
active = (active + increment) % total;
if (active < 0)
{
active = total - 1;
}
jsonDoc["active"] = active;
std::cout << "screen: " << active + 1 << "/" << total << std::endl;
displayScreen(jsonDoc, active + 1, total);
}
const String formatBytes(size_t const &bytes)
{ // lesbare Anzeige der Speichergrößen
return (bytes < 1024) ? String(bytes) + " Byte" : (bytes < (1024 * 1024)) ? String(bytes / 1024.0) + " KB" : String(bytes / 1024.0 / 1024.0) + " MB";
}
const String &contentType(String &filename)
{ // ermittelt den Content-Typ
if (filename.endsWith(".htm") || filename.endsWith(".html"))
filename = "text/html";
else if (filename.endsWith(".css"))
filename = "text/css";
else if (filename.endsWith(".js"))
filename = "application/javascript";
else if (filename.endsWith(".json"))
filename = "application/json";
else if (filename.endsWith(".png"))
filename = "image/png";
else if (filename.endsWith(".gif"))
filename = "image/gif";
else if (filename.endsWith(".jpg"))
filename = "image/jpeg";
else if (filename.endsWith(".ico"))
filename = "image/x-icon";
else if (filename.endsWith(".xml"))
filename = "text/xml";
else if (filename.endsWith(".pdf"))
filename = "application/x-pdf";
else if (filename.endsWith(".zip"))
filename = "application/x-zip";
else if (filename.endsWith(".gz"))
filename = "application/x-gzip";
else
filename = "text/plain";
return filename;
}
void handleList()
{ // Senden aller Daten an den Client
File root = SPIFFS.open("/");
String temp = "[";
File file = root.openNextFile();
while (file)
{
if (temp != "[")
temp += ",";
temp += R"({"name":")" + String(file.name() + 1) + R"(","size":")" + formatBytes(file.size()) + R"("})";
file = root.openNextFile();
}
temp += R"(,{"usedBytes":")" + formatBytes(SPIFFS.usedBytes() * 1.05) + R"(",)" + // Berechnet den verwendeten Speicherplatz + 5% Sicherheitsaufschlag
R"("totalBytes":")" + formatBytes(SPIFFS.totalBytes()) + R"(","freeBytes":")" + // Zeigt die Größe des Speichers
(SPIFFS.totalBytes() - (SPIFFS.usedBytes() * 1.05)) + R"("}])"; // Berechnet den freien Speicherplatz + 5% Sicherheitsaufschlag
webServer.send(200, "application/json", temp);
}
bool handleFile(String &&path)
{
if (webServer.hasArg("delete"))
{
SPIFFS.remove(webServer.arg("delete")); // Datei löschen
webServer.sendContent(Header);
return true;
}
if (!SPIFFS.exists("/spiffs.html"))
webServer.send(200, "text/html", Helper); //Upload the spiffs.html
if (path.endsWith("/"))
path += "index.html";
return SPIFFS.exists(path) ? ({File f = SPIFFS.open(path, "r"); webServer.streamFile(f, contentType(path)); f.close(); true; }) : false;
}
void handleFileUpload()
{ // Dateien vom Rechnenknecht oder Klingelkasten ins SPIFFS schreiben
static File fsUploadFile;
HTTPUpload &upload = webServer.upload();
if (upload.status == UPLOAD_FILE_START)
{
if (upload.filename.length() > 30)
{
upload.filename = upload.filename.substring(upload.filename.length() - 30, upload.filename.length()); // Dateinamen auf 30 Zeichen kürzen
}
std::cout << "FileUpload Name: " << upload.filename << std::endl;
fsUploadFile = SPIFFS.open("/" + webServer.urlDecode(upload.filename), "w");
}
else if (upload.status == UPLOAD_FILE_WRITE)
{
std::cout << "FileUpload Data: " << (String)upload.currentSize << std::endl;
if (fsUploadFile)
fsUploadFile.write(upload.buf, upload.currentSize);
}
else if (upload.status == UPLOAD_FILE_END)
{
if (fsUploadFile)
fsUploadFile.close();
std::cout << "FileUpload Size: " << (String)upload.totalSize << std::endl;
webServer.sendContent(Header);
}
}
void formatSpiffs()
{ //Formatiert den Speicher
SPIFFS.format();
webServer.sendContent(Header);
}
bool freeSpace(uint16_t const &printsize)
{ // Funktion um beim speichern in Logdateien zu prüfen ob noch genügend freier Platz verfügbar ist.
std::cout << formatBytes(SPIFFS.totalBytes() - (SPIFFS.usedBytes() * 1.05)) << " im Spiffs frei" << std::endl;
return (SPIFFS.totalBytes() - (SPIFFS.usedBytes() * 1.05) > printsize) ? true : false;
}
void startNetwork()
{
std::cout << "start Network" << std::endl;
WiFi.softAP("theBadge");
dnsServer.start(53, "*", WiFi.softAPIP());
webServer.on("/json", handleList);
webServer.on("/format", formatSpiffs);
webServer.on("/upload", HTTP_POST, []() {}, handleFileUpload);
webServer.onNotFound([]() {
if (!handleFile(webServer.urlDecode(webServer.uri())))
webServer.send(404, "text/plain", "FileNotFound");
});
webServer.begin();
}
void setup()
{
Serial.begin(SPEED);
pinMode(BUTTON_1, INPUT_PULLUP);
pinMode(BUTTON_2, INPUT_PULLUP);
pinMode(BUTTON_3, INPUT_PULLUP);
btStop();
WiFi.mode(WIFI_OFF);
display.init(SPEED);
if (!SPIFFS.begin())
std::cout << "SPIFFS problem!" << std::endl;
button1.attach(BUTTON_1);
button1.interval(5);
button2.attach(BUTTON_2);
button2.interval(5);
button3.attach(BUTTON_3);
button3.interval(5);
if (!loadConfiguration(filename, jsonDocConfig))
{
saveConfiguration(filename, jsonDocConfig);
}
switch (esp_sleep_get_wakeup_cause())
{
case ESP_SLEEP_WAKEUP_TIMER:
std::cout << "timer wakepup" << std::endl;
switchScreen(jsonDocConfig, 1);
saveConfiguration(filename, jsonDocConfig);
deepSleep();
break;
case ESP_SLEEP_WAKEUP_EXT0:
std::cout << "ext0 wakepup" << std::endl;
switchScreen(jsonDocConfig, 1);
saveConfiguration(filename, jsonDocConfig);
deepSleep();
break;
case ESP_SLEEP_WAKEUP_EXT1:
std::cout << "ext1 wakepup" << std::endl;
break;
default:
std::cout << "normal wakepup" << std::endl;
}
printFile(filename);
switchScreen(jsonDocConfig, 0);
goToSleep.once(GRACE_TIME, deepSleep);
}
void loop()
{
if (WiFi.getMode() == WIFI_AP)
{
dnsServer.processNextRequest();
webServer.handleClient();
}
button1.update();
if (button1.fell())
{
switchScreen(jsonDocConfig, 1);
saveConfiguration(filename, jsonDocConfig);
}
button2.update();
if (button2.fell())
{
}
button3.update();
if (button3.fell())
{
std::cout << "timer off" << std::endl;
goToSleep.detach();
startNetwork();
}
}
|
fe3ab9b7497dc4d3fcb5a8e224f37bbaebf05315
|
a0c4ed3070ddff4503acf0593e4722140ea68026
|
/source/MAILPLUS/BULLET2/SRC/PABNSP/HIERBCX.CXX
|
8d3bb89c11f5a8728d23fd19422085fa3eba97a6
|
[] |
no_license
|
cjacker/windows.xp.whistler
|
a88e464c820fbfafa64fbc66c7f359bbc43038d7
|
9f43e5fef59b44e47ba1da8c2b4197f8be4d4bc8
|
refs/heads/master
| 2022-12-10T06:47:33.086704
| 2020-09-19T15:06:48
| 2020-09-19T15:06:48
| 299,932,617
| 0
| 1
| null | 2020-09-30T13:43:42
| 2020-09-30T13:43:41
| null |
UTF-8
|
C++
| false
| false
| 1,807
|
cxx
|
HIERBCX.CXX
|
#include <pabinc.cxx>
#include "session.hxx"
#include "pabbcx.hxx"
#include "macbcx.hxx"
#include "hierbcx.hxx"
ASSERTDATA;
_public
HIERBCX::HIERBCX ( void )
{
this->lpschemaCur = (LPSCHEMA) pvNull;
}
_public
HIERBCX::~HIERBCX ( void )
{
FreePvNull( lpschemaCur );
}
_public NSEC
HIERBCX::NsecInstall ( PABSESSION *ppabsession,
LPSCHEMA *lplpSchemaRet )
{
SZ szNSPTitle = SzFromIdsK( idsPABDisplayName );
DWORD dwHierLevel = 0;
DWORD fIsPAB = (DWORD) fTrue;
DWORD fHasNames = (DWORD) fTrue;
DWORD fHasDirectories = (DWORD) fFalse;
PABNSID pabnsid;
LPIBF lpibf;
NSEC nsec;
if ( nsec = MACBCX::NsecInstall( ppabsession ))
return nsec;
if ( BuildSchema( &lpschemaCur, 6,
fidDisplayName,
fidHierLevel,
fidNSEntryId,
fidIsPAB,
fidHasNames,
fidHasDirectories ) != nsecNone )
{
TraceTagString( tagNull, "HIERBCX::NsecInstall - OOM [BuildSchema]" );
return ppabsession->NsecSetError( nsecMemory, idsErrOOM );
}
*lplpSchemaRet = lpschemaCur;
SetPPabnsid( &pabnsid, pidtypeHierarchy, ppabsession->PidHierarchy() );
if ( BuildIbf( fNoErrorJump, &lpibf, 6,
fidDisplayName, CchSzLen(szNSPTitle)+1, szNSPTitle,
fidHierLevel, sizeof(DWORD), &dwHierLevel,
fidNSEntryId, sizeof(PABNSID), &pabnsid,
fidIsPAB, sizeof(DWORD), &fIsPAB,
fidHasNames, sizeof(DWORD), &fHasNames,
fidHasDirectories, sizeof(DWORD), &fHasDirectories ) != nsecNone )
{
TraceTagString( tagNull, "HIERBCX::NsecInstall - OOM [BuildIbf]" );
return ppabsession->NsecSetError( nsecMemory, idsErrOOM );
}
if ( nsec = NsecInsertEntry( lpibf ))
{
FreePv((PV) lpibf );
return nsec;
}
return nsecNone;
}
|
e138ea7e7c4e6b61d9a6241e2fa40533f1962110
|
2dd0253e5f7331e2346cb44aebabc925c5003519
|
/src/api/declare_operator.h
|
52b482d364f911a4705799c6bfaaa4d782d0f83a
|
[] |
no_license
|
KangLin/TenniS
|
06e22b734c08781abf3bcb24abeceda777584e6c
|
d2c44ab369685450beb18fc83685f9e589bb3f35
|
refs/heads/master
| 2023-07-30T14:11:25.828834
| 2021-10-03T08:49:52
| 2021-10-03T08:49:52
| 412,299,971
| 0
| 0
| null | 2021-10-01T02:35:24
| 2021-10-01T02:35:23
| null |
UTF-8
|
C++
| false
| false
| 1,426
|
h
|
declare_operator.h
|
//
// Created by kier on 19-5-18.
//
#ifndef TENSORSTACK_DECLARE_OPERATOR_H
#define TENSORSTACK_DECLARE_OPERATOR_H
#include <core/tensor_builder.h>
#include "declaration.h"
#include "api/operator.h"
#include "global/operator_factory.h"
#include "declare_tensor.h"
#include "runtime/stack.h"
#include "core/device_context.h"
#include "runtime/runtime.h"
struct ts_OperatorParams {
public:
ts_OperatorParams(ts::Operator *op) : op(op) {}
ts::Operator *op;
};
class APIPluginStack {
public:
APIPluginStack(ts::Stack &stack) {
auto argc = stack.size();
try {
for (size_t i = 0; i < argc; ++i) {
auto &tensor = stack[i];
args.emplace_back(new ts_Tensor(tensor));
}
} catch (const ts::Exception &e) {
for (auto &arg : args) delete arg;
throw e;
} catch (const std::exception &e) {
for (auto &arg : args) delete arg;
throw e;
}
}
~APIPluginStack() {
for (auto &arg : args) {
delete arg;
}
}
std::vector<ts_Tensor *> args;
};
struct ts_OperatorContext {
public:
ts_OperatorContext() {
device = &ts::ctx::of<ts::DeviceContext>::ref();
runtime = &ts::ctx::of<ts::RuntimeContext>::ref();
}
ts::DeviceContext *device;
ts::RuntimeContext *runtime;
};
#endif //TENSORSTACK_DECLEARE_OPERATOR_H
|
75f39a05ce1ef80ca518afefd6b851f939de1e5d
|
ec250c250ac18e555a0629d0716182ffe3cb9729
|
/Samples/Marmalade_SpaceWarFare/client/SpaceWarFare/source/GameListener.h
|
e7824945d27b6e758a90aaf6cc316fac61c3d150
|
[] |
no_license
|
shephertz/AppWarpS2Public
|
99cb82f30a0b2a5171f0be0c605ad8d686c14b83
|
7495645c561b131d6323b5f337a63b72c8e3e9f4
|
refs/heads/master
| 2020-12-29T01:41:54.094084
| 2017-12-28T07:17:37
| 2017-12-28T07:17:37
| 14,166,804
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,456
|
h
|
GameListener.h
|
#ifndef __GAME_LISTENER_H__
#define __GAME_LISTENER_H__
#include "appwarp.h"
class GameListener : public AppWarp::ConnectionRequestListener, public AppWarp::LobbyRequestListener, public AppWarp::NotificationListener, public AppWarp::RoomRequestListener, public AppWarp::ZoneRequestListener,public AppWarp::ChatRequestListener, public AppWarp::UpdateRequestListener, public AppWarp::TurnBasedRoomRequestListener
{
public:
//AppWarp::ConnectionRequestListener
void onConnectDone(int res);
void onDisconnectDone(int res);
//AppWarp::LobbyRequestListener
void onJoinLobbyDone(AppWarp::lobby levent) ;
void onSubscribeLobbyDone(AppWarp::lobby levent) ;
void onUnsubscribeLobbyDone(AppWarp::lobby levent) ;
void onLeaveLobbyDone(AppWarp::lobby levent) ;
void onGetLiveLobbyInfoDone(AppWarp::livelobby levent) ;
//AppWarp::NotificationListener
void onRoomCreated(AppWarp::room rData) ;
void onRoomDestroyed(AppWarp::room rData) ;
void onUserLeftRoom(AppWarp::room rData, std::string user) ;
void onUserJoinedRoom(AppWarp::room rData, std::string user);
void onUserLeftLobby(AppWarp::lobby ldata, std::string user);
void onUserJoinedLobby(AppWarp::lobby ldata, std::string user) ;
void onChatReceived(AppWarp::chat chatevent);
void onUpdatePeersReceived(AppWarp::byte update[], int len);
//AppWarp::RoomRequestListener
void onSubscribeRoomDone(AppWarp::room revent);
void onUnsubscribeRoomDone(AppWarp::room revent);
void onJoinRoomDone(AppWarp::room revent);
void onLeaveRoomDone (AppWarp::room revent);
void onGetLiveRoomInfoDone(AppWarp::liveroom revent);
void onSetCustomRoomDataDone (AppWarp::liveroom revent);
void onUpdatePropertyDone(AppWarp::liveroom revent);
//AppWarp::ZoneRequestListener
void onCreateRoomDone (AppWarp::room revent);
void onDeleteRoomDone (AppWarp::room revent);
void onGetAllRoomsDone (AppWarp::liveresult res);
void onGetOnlineUsersDone (AppWarp::liveresult res);
void onGetLiveUserInfoDone (AppWarp::liveuser uevent);
void onSetCustomUserInfoDone (AppWarp::liveuser uevent);
void onGetMatchedRoomsDone(AppWarp::matchedroom mevent);
//AppWarp::ChatRequestListener
void onSendChatDone(int res);
//AppWarp::UpdateRequestListener
void onSendUpdateDone(int res);
//AppWarp::TurnBasedRoomRequestListener
void onStartGameDone(int res);
void onStopGameDone(int res);
void onSendMoveDone(int res);
void onGetMoveHistoryDone(int res, std::vector<AppWarp::move> history);
};
#endif
|
db833ffe851719228d73334311e0a4a2574ed9fd
|
9f5227a0df5362dcefe9cdc29e032e1aae478a53
|
/Eigen.cc
|
c1b02643d9b583478627afc5c760e5f1904ab19a
|
[] |
no_license
|
hapfang/AnisoAdapt
|
684b419e17fa3fac7a447802d1909a5065460fc0
|
051335fdb6e32028573d34153041458c22751639
|
refs/heads/master
| 2021-05-08T19:19:35.938308
| 2018-01-30T19:57:49
| 2018-01-30T19:57:49
| 119,564,267
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,973
|
cc
|
Eigen.cc
|
#include "Eigen.h"
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <math.h>
#include "MeshSimInternal.h"
using namespace std;
#define ABS(x) ((x) < 0 ? -(x) : (x))
// int normVt (double [],double [])
// {
// return 1;
// }
#ifdef SIM
int normVt(double *v1,double *nv)
{
double norm ;
norm = v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2] ;
norm = 1./sqrt(norm) ;
nv[0] = v1[0]*norm ;
nv[1] = v1[1]*norm ;
nv[2] = v1[2]*norm ;
return(1) ;
}
void diffVt(double *a,double *b,double *v)
{
v[0] = a[0] - b[0] ;
v[1] = a[1] - b[1] ;
v[2] = a[2] - b[2] ;
}
void crossProd(double *v1, double *v2, double *cp)
{
cp[0] = v1[1]*v2[2] - v1[2]*v2[1] ;
cp[1] = v1[2]*v2[0] - v1[0]*v2[2] ;
cp[2] = v1[0]*v2[1] - v1[1]*v2[0] ;
}
double dotProd(double *v1, double *v2)
{
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] ;
}
#endif
struct greater_abs
{
bool operator () (const double &a, const double &b)
{
return fabs(a) > fabs(b);
}
};
long eigen (double pos[3][3], double e[3][3], double v[3], int checkOrthogonality)
{
#ifdef DEBUG
// cout<<"\nin eigen(), eigen computation of matrix\n";
// for(int j=0; j< 3; j++){
// cout<<pos[j][0]<<" "<<pos[j][1]<<" "<<pos[j][2]<<"\n";
// }
#endif
// characteristic polynomial of T :
// solve x^3 + (I[2]/I[3])*x^2 + (I[1]/I[3])*x + (I[0]/I[3])*a3 = 0
// I1 : first invariant , trace(T)
// I2 : second invariant , 1/2 (I1^2 -trace(T^2))
// I3 : third invariant , det T
double I[4];
I[3] = 1.0;
I[2] = - trace(pos);
I[1] = 0.5 * (I[2]*I[2] - trace2(pos));
I[0] = - det(pos);
// printf (" %lf x^3 + %lf x^2 + %lf x + %lf = 0\n",
// I[3],I[2],I[1],I[0]);
// solve x^3 + (I[2]/I[3])*x^2 + (I[1]/I[3])*x + (I[0]/I[3])*a3 = 0
// solve x^3 + a1 x^2 + a2 x + a3 = 0
long nbEigen = FindCubicRoots (I,v);
std::sort(v,v+3, greater_abs() );
// printf ("nbEigen = %d %12.5E %12.5E %12.5E\n",nbEigen,v[0],v[1],v[2]);
double result[12];
int nb_vec=0;
while(1)
{
double a[9] = {pos[0][0]-v[nb_vec],pos[0][1],pos[0][2],
pos[1][0],pos[1][1]-v[nb_vec],pos[1][2],
pos[2][0],pos[2][1],pos[2][2]-v[nb_vec]};
// eps smaller gives better eigenvals (orig 1.0e-3)
double eps = 1.0e-5;
int nb = 0;
while (1)
{
nb = NullSpace (a,result,eps,3);
if (nb != 0)break;
eps *= 2.0;
}
int kk=0;
for (int i=nb_vec;i<nb+nb_vec;i++)
{
e[i][0] = result[0+kk*3];
e[i][1] = result[1+kk*3];
e[i][2] = result[2+kk*3];
normVt (e[i], e[i]);
// printf("%d: %f (%f, %f, %f)\n",i,v[nb_vec],e[i][0],e[i][1],e[i][2]);
kk++;
if (i == 2 && checkOrthogonality) {
int factor;
if( !checkUnitaryOthoganal(e,factor) )
{
printf (" %lf x^3 + %lf x^2 + %lf x + %lf = 0\n",I[3],I[2],I[1],I[0]);
printf ("nbEigen = %d %12.5E %12.5E %12.5E\n",nbEigen,v[0],v[1],v[2]);
for(int jj=0; jj<3; jj++ )
printf("%d: %f (%f, %f, %f)\n",jj,v[jj],e[jj][0],e[jj][1],e[jj][2]);
printf("nb=%d nb_vec=%d nbEigen=%d\n",nb,nb_vec,nbEigen);
printf("WARNING: not orthoganal (eigen)\n\n");
}
// // changing the orientation of thrid vector
// // such that it follows right hand rule
// if(factor==-1) {
// for(int icomp=0;icomp<3;icomp++) {
// e[3][icomp]=factor*e[3][icomp];
// }
// // cout<<"Changing orientation for third eigen-vector"<<endl;
// }
return nbEigen;
}// if (i == 2 && checkOrthog
}//for (int i=nb_v
nb_vec += nb;
if (nb_vec == 3)
return nbEigen;
if( nb_vec > 3 )
return nbEigen;
// throw;
if (nb > 3)
throw;
}//while(1)
}
int checkUnitaryOthoganal(double e[3][3], int &factor)
{
int i;
double dot, n[3];
double tol=1e-14;
double cosalpha, alpha;
for( i=0; i<3; i++ ) {
dot=dotProd(e[i],e[i]);
if( dot < tol )
{ printf("the %d vector in zero length\n",i); return 0; }
if( ABS(dot - 1.) > tol )
{ printf("the %d vector not unitary. lenthSq=%f\n",i,dot); return 0; }
}
dot=dotProd(e[0],e[1]);
cosalpha=dot/sqrt(dotProd(e[0],e[0])*dotProd(e[1],e[1]));
alpha = 57.295718*acos(cosalpha);
if( alpha > 95 && alpha<85 ) {
printf("first two base vectors not orthognal. %f\n",alpha);
return 0;
}
crossProd(e[0],e[1],n);
dot=dotProd(e[2],n);
if(dot<0.)
factor=-1;
cosalpha=dot/sqrt(dotProd(e[2],e[2])*dotProd(n,n));
alpha = 57.295718*acos(cosalpha);
if( alpha < 175 && alpha>5 ) {
printf("third base vector not orthognal to first two. %f\n", alpha);
return 0;
}
return 1;
}
double trace (double pos[3][3])
{
return pos[0][0] + pos[1][1] + pos[2][2];
}
double trace2 (double pos[3][3])
{
double a00 = pos[0][0] * pos[0][0] +
pos[1][0] * pos[0][1] +
pos[2][0] * pos[0][2];
double a11 = pos[1][0] * pos[0][1] +
pos[1][1] * pos[1][1] +
pos[1][2] * pos[2][1];
double a22 = pos[2][0] * pos[0][2] +
pos[2][1] * pos[1][2] +
pos[2][2] * pos[2][2];
return a00 + a11 + a22;
}
double det (double pos[3][3])
{
return pos[0][0] * (pos[1][1] * pos[2][2] - pos[1][2] * pos[2][1]) -
pos[0][1] * (pos[1][0] * pos[2][2] - pos[1][2] * pos[2][0]) +
pos[0][2] * (pos[1][0] * pos[2][1] - pos[1][1] * pos[2][0]);
}
// solve x^2 + b x + c = 0
// x[2] is always set to be zero
long FindQuadraticRoots(const double b, const double c, double x[3])
{
// printf("Quadratic roots\n");
x[2]=0.0;
double delt=b*b-4.*c;
if( delt >=0 ) {
delt=sqrt(delt);
x[0]=(-b+delt)/2.0;
x[1]=(-b-delt)/2.0;
return 3;
}
printf("Imaginary roots, impossible, delt=%f\n",delt);
return 1;
}
// solve x^3 + a1 x^2 + a2 x + a3 = 0
long FindCubicRoots(const double coeff[4], double x[3])
{
double a1 = coeff[2] / coeff[3];
double a2 = coeff[1] / coeff[3];
double a3 = coeff[0] / coeff[3];
if( ABS(a3)<1.0e-8 )
return FindQuadraticRoots(a1,a2,x);
double Q = (a1 * a1 - 3 * a2) / 9.;
double R = (2. * a1 * a1 * a1 - 9. * a1 * a2 + 27. * a3) / 54.;
double Qcubed = Q * Q * Q;
double d = Qcubed - R * R;
// printf ("d = %22.15e Q = %12.5E R = %12.5E Qcubed %12.5E\n",d,Q,R,Qcubed);
/// three roots, 2 equal
if(Qcubed == 0.0 || fabs ( Qcubed - R * R ) < 1.e-8 * (fabs ( Qcubed) + fabs( R * R)) )
{
double theta;
if (Qcubed <= 0.0)theta = acos(1.0);
else if (R / sqrt(Qcubed) > 1.0)theta = acos(1.0);
else if (R / sqrt(Qcubed) < -1.0)theta = acos(-1.0);
else theta = acos(R / sqrt(Qcubed));
double sqrtQ = sqrt(Q);
// printf("sqrtQ = %12.5E teta=%12.5E a1=%12.5E\n",sqrt(Q),theta,a1);
x[0] = -2 * sqrtQ * cos( theta / 3) - a1 / 3;
x[1] = -2 * sqrtQ * cos((theta + 2 * M_PI) / 3) - a1 / 3;
x[2] = -2 * sqrtQ * cos((theta + 4 * M_PI) / 3) - a1 / 3;
return (3);
}
/* Three real roots */
if (d >= 0.0) {
double theta = acos(R / sqrt(Qcubed));
double sqrtQ = sqrt(Q);
x[0] = -2 * sqrtQ * cos( theta / 3) - a1 / 3;
x[1] = -2 * sqrtQ * cos((theta + 2 * M_PI) / 3) - a1 / 3;
x[2] = -2 * sqrtQ * cos((theta + 4 * M_PI) / 3) - a1 / 3;
return (3);
}
/* One real root */
else {
printf("IMPOSSIBLE !!!\n");
double e = pow(sqrt(-d) + fabs(R), 1. / 3.);
if (R > 0)
e = -e;
x[0] = (e + Q / e) - a1 / 3.;
return (1);
}
}
#define MAXN 32
#define R(i,j) result[n*(i)+(j)]
long NullSpace(const double *a, double *result, double eps, long n)
{
int r[MAXN], c[MAXN];
register long i, j, k;
int jj, kk, t;
double max, temp;
int ec;
for (i = 0; i < n; i++)
r[i] = c[i] = -1; /* Reset row and column pivot indices */
// copy the input matrix if not in place
if (result != a)
for (i = 0; i < n*n; i++)
result[i] = a[i];
// rest of algorithm is in place wrt result[]
for (i = 0; i < n; i++) {
/* Find the biggest element in the remaining submatrix
* for the next full pivot.
*/
max = 0.0;
for (k = 0; k < n; k++) {
if (r[k] < 0) {
for (j = 0; j < n; j++) {
if ((c[j] < 0) && ((temp = fabs(R(k, j))) > max)) {
kk = k;
jj = j;
max = temp;
}
}
}
}
if (max < eps)
break; /* Consider this and all subsequent pivots to be zero */
c[jj] = kk; /* The row */
r[kk] = jj; /* and column of the next pivot */
temp = 1.0 / R(kk, jj);
R(kk, jj) = 1.0;
for (j = 0; j < n; j++) /* Should this be for j != jj ? */
R(kk, j) *= temp; /* Row equilibration */
for (k = 0; k < n; k++) { /* Row elimination */
if (k == kk)
continue; /* Don't do a thing to the pivot row */
temp = R(k, jj);
R(k, jj) = 0.0;
for (j = 0; j < n; j++) {
R(k, j) -= temp * R(kk, j); /* Subtract row kk from row k */
if (fabs(R(k, j)) < eps)
R(k, j) = 0.0; /* Flush to zero if too small */
}
}
}
/* Sort into a truncated triangular matrix */
for (j = 0; j < n; j++) { /* For all columns... */
while ((c[j] >= 0) && (j != c[j])) {
for (k = 0; k < n; k++) {
if (r[k] < 0) {
/* Aha! a null column vector */
temp = R(k, j); /* Get it on top */
R(k, j) = R(k, c[j]);
R(k, c[j]) = temp;
}
}
t = c[j]; /* Twiddle until pivots are on the diagonal */
c[j] = c[t];
c[t] = t;
}
}
/* Copy the null space vectors into the top of the A matrix */
ec = 0;
for (k = 0; k < n; k++) {
if (r[k] < 0) {
R(k, k) = 1.0; /* Set the pivot equal to 1 */
if (ec != k) {
for (j = 0; j < n; j++) {
R(ec, j) = R(k, j);
}
}
ec++;
}
}
/* The first ec rows of the matrix a are the vectors which are
* orthogonal to the columns of the matrix a.
*/
return (ec);
}
|
98a59ac27ddb9f3d1d32db25910db88a59b0abf2
|
8892e53be0319219214f9f6b8ff75b7c4d41ce9b
|
/src/vpktool.h
|
6455f556aee5d696ece7edd9beb0947485400a7a
|
[
"MIT"
] |
permissive
|
motz61/vpktool
|
6621dae3e9075736aa496f99ace5e91082e59600
|
99093c6d8992cac64a8129def874ba8f26d48cbf
|
refs/heads/master
| 2023-01-08T14:50:07.455977
| 2020-10-06T23:10:57
| 2020-10-06T23:10:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 141
|
h
|
vpktool.h
|
/**
*
* vpktool.h
*
* Common definitions for the VPK tool
*
*/
#pragma once
#include <filesystem>
#include <string>
#include <vector>
|
21e87e695dd020464b2b42f14a7cd54f57bba976
|
412386012ca2b54426b59eccf2019b00dbc3b32c
|
/mymol/src/configfile.cpp
|
569eae7ac07db61d793b4923429ae7d802249964
|
[] |
no_license
|
Santiso-Group/GeneralOPs
|
353b522cbce51663e327b7bd8214336c53ced6bd
|
e34135f79fca31cea8b3f6aaf946352b35912a8b
|
refs/heads/master
| 2023-03-25T07:48:49.786397
| 2021-03-24T21:22:48
| 2021-03-24T21:22:48
| 271,597,046
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 22,395
|
cpp
|
configfile.cpp
|
/*
** Copyright 2007-2011 Erik Santiso.
** This file is part of mymol.
** mymol is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License
** version 2.1 as published by the Free Software Foundation.
**
**
** mymol is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with mymol. If not, see <http://www.gnu.org/licenses/>.
*/
/*
** CONFIG (DL-POLY) file format
*/
#include <iomanip>
#include <sstream>
#include "common/include/assert.h"
#include "mymol/include/file_formats/fileformats.h"
// Constructors
CONFIGFile::CONFIGFile()
:
IOFile()
{}
CONFIGFile::CONFIGFile(std::string const &fileName, IOMode const &mode)
:
IOFile(fileName, mode)
{}
// Operators
CONFIGFile &operator<<(CONFIGFile &configFile, Geometry const &geometry)
{
assert(configFile.is_open() && configFile.mode() == OUT);
// Set precision
std::streamsize precision = configFile.precision();
configFile.precision(WRITE_PRECISION);
// Title line
configFile.setf(std::ios::left, std::ios::adjustfield);
configFile << std::setw(80) << geometry.name() << std::endl;
// File key, supercell key, number of atoms
configFile.setf(std::ios::right, std::ios::adjustfield);
configFile << std::setw(10) << 0 // Only write positions
<< std::setw(10) << 0 // No PBCs
<< std::setw(10) << geometry.numAtoms()
<< std::endl;
// Atom records
for(size_t i = 0; i < geometry.numAtoms(); ++i)
{
Atom const ¤tAtom = geometry.atom(i);
configFile.setf(std::ios::left, std::ios::adjustfield);
configFile << std::setw(8) << currentAtom.symbol;
configFile.setf(std::ios::right, std::ios::adjustfield);
configFile << std::setw(10) << i + 1
<< std::endl;
configFile << std::setiosflags(std::ios::fixed)
<< std::setw(20) << currentAtom.position.x
<< std::setw(20) << currentAtom.position.y
<< std::setw(20) << currentAtom.position.z
<< std::endl;
}
configFile.precision(precision); // Return to original value
return configFile;
}
CONFIGFile &operator>>(CONFIGFile &configFile, Geometry &geometry)
{
assert(configFile.is_open() && configFile.mode() == IN);
bool newGeometry = (geometry.numAtoms() == 0);
// Read the title line
std::string title;
std::getline(configFile, title);
geometry.setName(title);
// Read the file key, supercell key, and number of atoms
std::string line; // Line read from file
// These variables follow notation from the DL_POLY manual
size_t levcfg; // File key
size_t imcon; // Periodic boundary key
size_t natms; // Number of atoms
std::getline(configFile, line);
std::istringstream keyStream(line);
keyStream >> levcfg;
if(keyStream.fail() || levcfg > 2)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": invalid levcfg record" << std::endl;
return configFile;
}
keyStream >> imcon;
if(keyStream.fail() || imcon > 7)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": invalid imcon record" << std::endl;
return configFile;
}
keyStream >> natms;
bool know_numAtoms = (!keyStream.fail());
if(know_numAtoms && !newGeometry && geometry.numAtoms() != natms)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": inconsistent number of atoms" << std::endl;
return configFile;
}
// If present, skip unit cell records
if(imcon > 0)
for(size_t i = 0; i < 3; ++i) configFile.ignore(LINE_LENGTH, '\n');
// Read atom records
size_t iAtom = 0; // Index of current atom
while(!configFile.eof())
{
std::string r_symbol; // Atom symbol read from file
size_t r_index; // Atom index read from file
Real r_x, r_y, r_z; // Coordinates read from file
// Read symbol and index
configFile >> r_symbol >> r_index;
if(configFile.eof()) break; // Done reading
if(configFile.fail())
{
std::cerr << "Error reading atom record from file " << configFile.fileName() << std::endl
<< "Atoms read: " << iAtom << std::endl;
return configFile;
}
if(r_index != iAtom + 1)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": atom indices not correlated" << std::endl;
return configFile;
}
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
// Read position
configFile >> r_x >> r_y >> r_z;
if(configFile.fail())
{
std::cerr << "Error reading atom position from file " << configFile.fileName() << std::endl
<< "Atoms read: " << iAtom << std::endl;
return configFile;
}
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
// If present, skip velocity and/or force records
for(size_t i = 0; i < levcfg; ++i)
configFile.ignore(LINE_LENGTH, '\n');
if(newGeometry)
geometry.addAtom(Atom(r_symbol, Vector3D(r_x, r_y, r_z)));
else
{
if(iAtom > geometry.numAtoms() - 1 ||
r_symbol.find(geometry.atom(iAtom).symbol) == r_symbol.npos)
{
std::cerr << "Inconsistent data in CONFIG file " << configFile.fileName() << std::endl;
return configFile;
}
geometry.setPosition(iAtom, Vector3D(r_x, r_y, r_z));
}
++iAtom;
} // End of loop to read atom records
if(!newGeometry && iAtom != geometry.numAtoms())
{
std::cerr << "Inconsistent number of atoms in CONFIG file " << configFile.fileName() << std::endl;
return configFile;
}
// Find bonds automatically if this is a new geometry
if(newGeometry) geometry.calculateBonds();
return configFile;
}
CONFIGFile &operator<<(CONFIGFile &configFile, System<Geometry> const &system)
{
assert(configFile.is_open() && configFile.mode() == OUT);
// Sanity check
if(system.size() == 0 || system[0].numAtoms() == 0)
{
std::cerr << "Error while writing CONFIG file " << configFile.fileName()
<< ": empty system" << std::endl;
return configFile;
}
// Get number of atoms
size_t nAtoms = 0;
for(size_t i = 0; i < system.size(); ++i)
nAtoms += system[i].numAtoms();
// Get periodic boundary key (imcon)
size_t imcon = 0; // Following notation in DL_POLY manual
if(system.lattice().numDimensions() == 2) imcon = 6;
if(system.lattice().numDimensions() == 3) imcon = 3;
// Set precision
std::streamsize precision = configFile.precision();
configFile.precision(WRITE_PRECISION);
// Title line
configFile.setf(std::ios::left, std::ios::adjustfield);
configFile << std::setw(80) << system.name() << std::endl;
// File key, supercell key, number of atoms
configFile.setf(std::ios::right, std::ios::adjustfield);
configFile << std::setw(10) << 0 // Only write positions
<< std::setw(10) << imcon
<< std::setw(10) << nAtoms
<< std::endl;
// Supercell
if(imcon != 0)
{
Vector3D const a = system.lattice().latticeVector(0);
Vector3D const b = system.lattice().latticeVector(1);
Vector3D const c = (imcon = 3)?system.lattice().latticeVector(2):0.0;
configFile << std::setiosflags(std::ios::fixed)
<< std::setw(20) << a.x
<< std::setw(20) << a.y
<< std::setw(20) << a.z
<< std::endl
<< std::setw(20) << b.x
<< std::setw(20) << b.y
<< std::setw(20) << b.z
<< std::endl
<< std::setw(20) << c.x
<< std::setw(20) << c.y
<< std::setw(20) << c.z
<< std::endl;
}
// Atom records
size_t iAtom = 0;
for(size_t i = 0; i < system.size(); ++i)
for(size_t j = 0; j < system[i].numAtoms(); ++j)
{
Atom const ¤tAtom = system[i].atom(j);
configFile.setf(std::ios::left, std::ios::adjustfield);
configFile << std::setw(8) << currentAtom.symbol;
configFile.setf(std::ios::right, std::ios::adjustfield);
configFile << std::setw(10) << iAtom + 1
<< std::endl;
configFile << std::setiosflags(std::ios::fixed)
<< std::setw(20) << currentAtom.position.x
<< std::setw(20) << currentAtom.position.y
<< std::setw(20) << currentAtom.position.z
<< std::endl;
++iAtom;
}
configFile.precision(precision); // Return to original value
return configFile;
}
CONFIGFile &operator>>(CONFIGFile &configFile, System<Geometry> &system)
{
assert(configFile.is_open() && configFile.mode() == IN);
bool newSystem = (system.size() == 0);
// Read the title line
std::string title;
std::getline(configFile, title);
system.setName(title);
// Read the file key, supercell key, and number of atoms
std::string line; // Line read from file
// These variables follow notation from the DL_POLY manual
size_t levcfg; // File key
size_t imcon; // Periodic boundary key
size_t natms; // Number of atoms
std::getline(configFile, line);
std::istringstream keyStream(line);
keyStream >> levcfg;
if(keyStream.fail() || levcfg > 2)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": invalid levcfg record" << std::endl;
return configFile;
}
keyStream >> imcon;
if(keyStream.fail() || imcon > 7)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": invalid imcon record" << std::endl;
return configFile;
}
keyStream >> natms;
bool know_numAtoms = (!keyStream.fail());
bool know_lattice = (system.lattice().numDimensions() > 0);
// Consistency checks
if(know_lattice && !newSystem) // In case lattice has been read before
{
if( (imcon == 0 && system.lattice().numDimensions() > 0) ||
(imcon == 6 && system.lattice().numDimensions() != 2) ||
(imcon != 0 && imcon != 6 && system.lattice().numDimensions() < 3) )
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": inconsistent unit cell" << std::endl;
return configFile;
}
}
if(know_numAtoms && !newSystem)
{
size_t nAtoms = 0;
for(size_t i = 0; i < system.size(); ++i)
nAtoms += system[i].numAtoms();
if(nAtoms != natms)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": inconsistent number of atoms" << std::endl;
return configFile;
}
}
// If present, read unit cell records
if(imcon > 0)
{
Vector3D r_a1, r_a2, r_a3; // Lattice vectors read from file
configFile >> r_a1.x >> r_a1.y >> r_a1.z;
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
configFile >> r_a2.x >> r_a2.y >> r_a2.z;
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
configFile >> r_a3.x >> r_a3.y >> r_a3.z;
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
if(configFile.fail())
{
std::cerr << "Error reading unit cell records from file " << configFile.fileName() << std::endl;
return configFile;
}
if(imcon == 6)
system.setLattice(Lattice(r_a1, r_a2, system.lattice().type()));
else
system.setLattice(Lattice(r_a1, r_a2, r_a3, system.lattice().type()));
}
// Read atom records
size_t iAtom = 0; // Index of current atom
size_t iMol = 0; // Index of current molecule
size_t iAtomInMol = 0; // Index of current atom in current molecule
if(newSystem)
system.add(Geometry()); // No connectivity, will read to a single geometry
while(!configFile.eof())
{
std::string r_symbol; // Atom symbol read from file
size_t r_index; // Atom index read from file
Real r_x, r_y, r_z; // Coordinates read from file
// Read symbol and index
configFile >> r_symbol >> r_index;
if(configFile.eof()) break; // Done reading
if(configFile.fail())
{
std::cerr << "Error reading atom record from file " << configFile.fileName() << std::endl
<< "Atoms read: " << iAtom << std::endl;
return configFile;
}
if(r_index != iAtom + 1)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": atom indices not correlated" << std::endl;
return configFile;
}
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
// Read position
configFile >> r_x >> r_y >> r_z;
if(configFile.fail())
{
std::cerr << "Error reading atom position from file " << configFile.fileName() << std::endl
<< "Atoms read: " << iAtom << std::endl;
return configFile;
}
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
// If present, skip velocity and/or force records
for(size_t i = 0; i < levcfg; ++i)
configFile.ignore(LINE_LENGTH, '\n');
if(newSystem)
system[0].addAtom(Atom(r_symbol, Vector3D(r_x, r_y, r_z)));
else
{
if(iMol > system.size() - 1 ||
r_symbol.find(system[iMol].atom(iAtomInMol).symbol) == r_symbol.npos)
{
std::cerr << "Inconsistent data in CONFIG file " << configFile.fileName() << std::endl;
return configFile;
}
system[iMol].setPosition(iAtomInMol, Vector3D(r_x, r_y, r_z));
// Local index bookkeeping
++iAtomInMol;
if(iAtomInMol > system[iMol].numAtoms() - 1)
{
++iMol;
iAtomInMol = 0;
}
}
++iAtom;
} // End of loop to read atom positions
// Consistency check
if(!newSystem && iMol != system.size())
{
std::cerr << "Inconsistent number of atoms in CONFIG file " << configFile.fileName() << std::endl;
return configFile;
}
// Find bonds automatically if this is a new system (this does not separate molecules)
if(newSystem) system[0].calculateBonds();
return configFile;
}
CONFIGFile &operator<<(CONFIGFile &configFile, System<Molecule> const &system)
{
assert(configFile.is_open() && configFile.mode() == OUT);
// Sanity check
if(system.size() == 0 || system[0].numAtoms() == 0)
{
std::cerr << "Error while writing CONFIG file " << configFile.fileName()
<< ": empty system" << std::endl;
return configFile;
}
// Get number of atoms
size_t nAtoms = 0;
for(size_t i = 0; i < system.size(); ++i)
nAtoms += system[i].numAtoms();
// Get periodic boundary key (imcon)
size_t imcon = 0; // Following notation in DL_POLY manual
if(system.lattice().numDimensions() == 2) imcon = 6;
if(system.lattice().numDimensions() == 3) imcon = 3;
// Set precision
std::streamsize precision = configFile.precision();
configFile.precision(WRITE_PRECISION);
// Title line
configFile.setf(std::ios::left, std::ios::adjustfield);
configFile << std::setw(80) << system.name() << std::endl;
// File key, supercell key, number of atoms
configFile.setf(std::ios::right, std::ios::adjustfield);
configFile << std::setw(10) << 0 // Only write positions
<< std::setw(10) << imcon
<< std::setw(10) << nAtoms
<< std::endl;
// Supercell
if(imcon != 0)
{
Vector3D const a = system.lattice().latticeVector(0);
Vector3D const b = system.lattice().latticeVector(1);
Vector3D const c = (imcon = 3)?system.lattice().latticeVector(2):0.0;
configFile << std::setiosflags(std::ios::fixed)
<< std::setw(20) << a.x
<< std::setw(20) << a.y
<< std::setw(20) << a.z
<< std::endl
<< std::setw(20) << b.x
<< std::setw(20) << b.y
<< std::setw(20) << b.z
<< std::endl
<< std::setw(20) << c.x
<< std::setw(20) << c.y
<< std::setw(20) << c.z
<< std::endl;
}
// Atom records
size_t iAtom = 0;
for(size_t i = 0; i < system.size(); ++i)
for(size_t j = 0; j < system[i].numAtoms(); ++j)
{
Atom const ¤tAtom = system[i].atom(j);
configFile.setf(std::ios::left, std::ios::adjustfield);
configFile << std::setw(8) << currentAtom.symbol;
configFile.setf(std::ios::right, std::ios::adjustfield);
configFile << std::setw(10) << iAtom + 1
<< std::endl;
configFile << std::setiosflags(std::ios::fixed)
<< std::setw(20) << currentAtom.position.x
<< std::setw(20) << currentAtom.position.y
<< std::setw(20) << currentAtom.position.z
<< std::endl;
++iAtom;
}
configFile.precision(precision); // Return to original value
return configFile;
}
CONFIGFile &operator>>(CONFIGFile &configFile, System<Molecule> &system)
{
assert(configFile.is_open() && configFile.mode() == IN);
bool newSystem = (system.size() == 0);
// Read the title line
std::string title;
std::getline(configFile, title);
system.setName(title);
// Read the file key, supercell key, and number of atoms
std::string line; // Line read from file
// These variables follow notation from the DL_POLY manual
size_t levcfg; // File key
size_t imcon; // Periodic boundary key
size_t natms; // Number of atoms
std::getline(configFile, line);
std::istringstream keyStream(line);
keyStream >> levcfg;
if(keyStream.fail() || levcfg > 2)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": invalid levcfg record" << std::endl;
return configFile;
}
keyStream >> imcon;
if(keyStream.fail() || imcon > 7)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": invalid imcon record" << std::endl;
return configFile;
}
keyStream >> natms;
bool know_numAtoms = (!keyStream.fail());
bool know_lattice = (system.lattice().numDimensions() > 0);
// Consistency checks
if(know_lattice && !newSystem) // In case lattice has been read before
{
if( (imcon == 0 && system.lattice().numDimensions() > 0) ||
(imcon == 6 && system.lattice().numDimensions() != 2) ||
(imcon != 0 && imcon != 6 && system.lattice().numDimensions() < 3) )
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": inconsistent unit cell" << std::endl;
return configFile;
}
}
if(know_numAtoms && !newSystem)
{
size_t nAtoms = 0;
for(size_t i = 0; i < system.size(); ++i)
nAtoms += system[i].numAtoms();
if(nAtoms != natms)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": inconsistent number of atoms" << std::endl;
return configFile;
}
}
// If present, read unit cell records
if(imcon > 0)
{
Vector3D r_a1, r_a2, r_a3; // Lattice vectors read from file
configFile >> r_a1.x >> r_a1.y >> r_a1.z;
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
configFile >> r_a2.x >> r_a2.y >> r_a2.z;
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
configFile >> r_a3.x >> r_a3.y >> r_a3.z;
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
if(configFile.fail())
{
std::cerr << "Error reading unit cell records from file " << configFile.fileName() << std::endl;
return configFile;
}
if(imcon == 6)
system.setLattice(Lattice(r_a1, r_a2, system.lattice().type()));
else
system.setLattice(Lattice(r_a1, r_a2, r_a3, system.lattice().type()));
}
// Read atom records
size_t iAtom = 0; // Index of current atom
size_t iMol = 0; // Index of current molecule
size_t iAtomInMol = 0; // Index of current atom in current molecule
if(newSystem)
system.add(Molecule()); // No connectivity, will read to a single molecule
while(!configFile.eof())
{
std::string r_symbol; // Atom symbol read from file
size_t r_index; // Atom index read from file
Real r_x, r_y, r_z; // Coordinates read from file
// Read symbol and index
configFile >> r_symbol >> r_index;
if(configFile.eof()) break; // Done reading
if(configFile.fail())
{
std::cerr << "Error reading atom record from file " << configFile.fileName() << std::endl
<< "Atoms read: " << iAtom << std::endl;
return configFile;
}
if(r_index != iAtom + 1)
{
std::cerr << "Error reading CONFIG file " << configFile.fileName()
<< ": atom indices not correlated" << std::endl;
return configFile;
}
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
// Read position
configFile >> r_x >> r_y >> r_z;
if(configFile.fail())
{
std::cerr << "Error reading atom position from file " << configFile.fileName() << std::endl
<< "Atoms read: " << iAtom << std::endl;
return configFile;
}
configFile.ignore(LINE_LENGTH, '\n'); // Skip to next line
// If present, skip velocity and/or force records
for(size_t i = 0; i < levcfg; ++i)
configFile.ignore(LINE_LENGTH, '\n');
if(newSystem)
system[0].addAtom(Atom(r_symbol, Vector3D(r_x, r_y, r_z)));
else
{
if(iMol > system.size() - 1 ||
r_symbol.find(system[iMol].atom(iAtomInMol).symbol) == r_symbol.npos)
{
std::cerr << "Inconsistent data in CONFIG file " << configFile.fileName() << std::endl;
return configFile;
}
system[iMol].setPosition(iAtomInMol, Vector3D(r_x, r_y, r_z));
// Local index bookkeeping
++iAtomInMol;
if(iAtomInMol > system[iMol].numAtoms() - 1)
{
++iMol;
iAtomInMol = 0;
}
}
++iAtom;
} // End of loop to read atom positions
// Consistency check
if(!newSystem && iMol != system.size())
{
std::cerr << "Inconsistent number of atoms in CONFIG file " << configFile.fileName() << std::endl;
return configFile;
}
// Find bonds automatically if this is a new system (this does not separate molecules)
if(newSystem) system[0].calculateBonds();
return configFile;
}
|
b9bebc051955955a2efbda024daf60a514311565
|
c107f05542d22c310733604878fcd8f3745ab35f
|
/leetcode/_000716_maxStack.cpp
|
1dd1e434168a04dfc6930609d7e9de7a2d448582
|
[
"MIT"
] |
permissive
|
cbrghostrider/Hacking
|
b9f867e9f5bab476a109098ab768254225d86a06
|
bec6ede4682595e39c985ee55e5db1c0bc3ddff9
|
refs/heads/master
| 2022-03-10T19:06:14.155969
| 2022-02-15T06:19:13
| 2022-02-15T06:19:13
| 33,151,888
| 6
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,271
|
cpp
|
_000716_maxStack.cpp
|
class MaxStack {
vector<int> stack;
void repopulateAt(int index) {
for (int i=index; i<stack.size()-1; i++) {
std::swap(stack[i], stack[i+1]);
}
stack.pop_back();
}
public:
// O(1) time.
MaxStack() {}
// O(1) time.
void push(int x) {
stack.push_back(x);
}
// O(1) time.
int pop() {
int ret = stack.back();
stack.pop_back();
return ret;
}
// O(1) time.
int top() {
return stack.back();
}
// O(n) time.
int peekMax() {
int max = std::numeric_limits<int>::min();
for (int i=0; i<stack.size(); i++) {
if (stack[i] > max) {max = stack[i];}
}
return max;
}
// O(n) time.
int popMax() {
int max = peekMax();
for (int i=stack.size()-1; i>=0; i--) {
if (stack[i] == max) {
repopulateAt(i);
break;
}
}
return max;
}
};
/**
* Your MaxStack object will be instantiated and called as such:
* MaxStack* obj = new MaxStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->peekMax();
* int param_5 = obj->popMax();
*/
|
7c0d4fca3a6f8f6d6e70c7aaa8305654bb0bdcfa
|
5b9c89d96ce3e2a239427a4a8f2d55278ccb187c
|
/Week13/Mitrele's Exam/mitrele1Tegava.cpp
|
31d4b27bf4be75d63c40d7dd5efa370cdf8c6dc7
|
[
"MIT"
] |
permissive
|
Stoefff/Introduction-to-Programming-17-18
|
eeb1e1dfa2c2dc82de5a1daa6beba9fa67053396
|
0f58bddddd9bbf3141181961ac2f41f866b93966
|
refs/heads/master
| 2022-09-18T06:17:49.169808
| 2022-09-03T15:30:00
| 2022-09-03T15:30:00
| 106,529,959
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 589
|
cpp
|
mitrele1Tegava.cpp
|
#include <iostream>
#include <cmath>
using namespace std;
int main(){
float v;
float EPS = 0.0001; //Approximation of the float value needed
cout << "Enter value of V: " << endl;
cin >> v;
cout << "Value of U: ";
if ((v - 4.0) <= EPS){
if ((v - 2) > EPS){
cout << v + 4 << endl;
} else if ((v - 1) <= EPS) {
cout << pow(v, 2) << endl; // 2-kata e stepenta ako tr da smenqsh
} else {
cout << "Function undefined in this region" << endl;
}
} else {
cout << v - 1 << endl;
}
}
|
ebfc6734530ebf54e0f41733263e4605c9999756
|
7202c6911d505b6b1e54da2e4220f731d098d54f
|
/PiZeroROI/classes.h
|
df52e5c274e01f54c9bd9eabb2d75b56f7d6013d
|
[] |
no_license
|
jzennamo/PiZeroROI
|
45fad268f119bff54f1448f2b39012e8263c2521
|
e40a9a6c79d13f518d7263f3c684fd5b3ea9e5c7
|
refs/heads/master
| 2021-01-21T13:53:19.425907
| 2016-04-17T04:10:30
| 2016-04-17T04:10:30
| 52,900,465
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 269
|
h
|
classes.h
|
#include "art/Persistency/Common/Wrapper.h"
#include "PiZeroROI/PiZeroROI.hh"
template class art::Wrapper<std::vector<ana::PiZeroROI> >;
template class std::vector<ana::PiZeroROI>;
template class std::vector<std::pair<int,int> >;
template class std::pair<int,int>;
|
c8d8c3f4bd4f70b0d3c7eaa19bbccc5159220a81
|
a94b9cc0bdc87c6d94708f815b7848fe332989f8
|
/src/Test.cpp
|
b3bd26baf357318b7169b9b810a1ba3254943b4a
|
[] |
no_license
|
mightyvoice/Face-and-Skin-Detection
|
d0c1aa127a76a1c4ee5a038ff6c86205e03f842f
|
7dcaadfb98e578dc42df322c8959cb47de3d7b28
|
refs/heads/master
| 2021-01-10T06:36:36.480638
| 2015-12-18T23:29:45
| 2015-12-18T23:29:45
| 47,209,584
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,703
|
cpp
|
Test.cpp
|
#include "Test.hpp"
void Test::procAllPicInDir(string imgDir){
vector<string> fileNames = GetAllBodySkinRatios::getAllFilesFromDir(imgDir);
int n = fileNames.size();
for(int i = 0; i < n; i++){
string imgName = MyLib::getNameFromFileName(fileNames[i]);
// cout<<imgName<<endl;
Mat peopleImg = imread(imgDir+"/"+fileNames[i]);
Mat mask = peopleImg.clone();
AdaptiveSkinDetector detector;
detector.run(peopleImg, mask);
MyLib::writeMatToJpgFile(mask, "./npeople-res/"+imgName+"-res.jpg");
}
}
void Test::getAllSkinToBodyRatioFromFiles(
const string picDir,
const string jsonDir,
const string resFileName)
{
int nakePicNum = 0;
int nonNakePicNum = 0;
if(picDir == "" || jsonDir == "" || resFileName == ""){
cout<<"Please input three file names"<<endl;
return;
}
ofstream resFile(resFileName.c_str(), std::ios::out|std::ios::ate);
if(!resFile){
cout<<"Cannot open the result file: "+resFileName<<endl;
return;
}
vector<string> picFileNames = MyLib::getAllFileNamesFromDir(picDir);
// vector<string> jsonFileNames = MyLib::getAllFileNamesFromDir(jsonDir);
int n = picFileNames.size();
for(int ii = 0; ii < picFileNames.size(); ii++){
string picFileName = picFileNames[ii];
cout<<picFileName<<endl;
string picFilePath = picDir;
if(picFilePath[picDir.length()-1] != '/'){
picFilePath += '/';
}
picFilePath += picFileName;
// cout<<picFilePath<<' '<<jsonFilePath<<endl;
Mat srcImg = imread(picFilePath, 1);
if(srcImg.rows == 0 || srcImg.cols == 0){
cout<<"The picture: " + picFilePath + " does not exist"<<endl;
resFile<<0.0<<endl;
break;
}
string jsonFilePath = jsonDir;
if(jsonFilePath[jsonDir.length()-1] != '/'){
jsonFilePath += '/';
}
jsonFilePath += MyLib::getNameFromFileName(picFileName) + ".json";
vector<vector<int> > bodyPos = ParseJson::getBodyPosFromJsonFile(jsonFilePath);
double res;
if(bodyPos.size() > 0){
vector<double> ratios;
for(int i = 0; i < bodyPos.size(); i++){
Rect bodyRect;
// cout<<bodyPos[j][0]<<' '<<bodyPos[j][1]<<' '<<bodyPos[j][2]<<' '<<bodyPos[j][3]<<endl;
bodyRect.x = bodyPos[i][0];
bodyRect.y = bodyPos[i][1];
bodyRect.width = bodyPos[i][2] - bodyRect.x;
bodyRect.height = bodyPos[i][3] - bodyRect.y;
// cout<<srcImg.cols<<' '<<srcImg.rows<<endl;
// cout<<bodyRect.x<<' '<<bodyRect.y<<' '<<bodyRect.width<<' '<<bodyRect.height<<endl;
GetAllBodySkinRatios::fixRectWithinBoundary(bodyRect, srcImg);
// cout<<bodyRect.x<<' '<<bodyRect.y<<' '<<bodyRect.width<<' '<<bodyRect.height<<endl;
Mat bodyImg = srcImg(bodyRect);
// Mat bodyImgCopy = srcImg(bodyRect);
// Mat mask = bodyImg.clone();
AdaptiveSkinDetector detector;
string bodyImgName = "./pic/bad-pic/"
+ MyLib::getNameFromFileName(picFileName)
+ "-"+MyLib::int2String(i);
ratios.push_back(detector.skinDetectFromImgShrink(bodyImg, bodyImgName));
// MyLib::writeMatToJpgFile(bodyImg, bodyImgName + "-frame-0.jpg");
}
res = *max_element(ratios.begin(), ratios.end());
if(res >= AdaptiveSkinDetector::NAKE_SKIN_RATIO){
nakePicNum++;
resFile<<picFileName+": "<<res<<endl;
}
else{
nonNakePicNum++;
// resFile<<picFileName+": "<<res<<endl;
}
}
else{
cout<<"There are no bodies in the picture: " + picFilePath<<endl;
res = 0.0;
}
// cout<<res<<endl;
// resFile<<picFileName+": "<<res<<endl;
}
resFile.close();
const int NAKE_PIC_NUM = 67;
const int NON_NAKE_PIC_NUM = 71;
// cout<<"Naked recognition ratio: "<<nakePicNum*100.0/NAKE_PIC_NUM<<"%"<<endl;
cout<<"None naked recognition ratio: "<<nakePicNum*100.0/NON_NAKE_PIC_NUM<<"%"<<endl;
}
void Test::getAllSkinRatiosFromPicDir(string picDir){
cout<<picDir<<endl;
vector<string> picFileNames = MyLib::getAllFileNamesFromDir(picDir);
for(int ii = 0; ii < picFileNames.size(); ii++){
string picName = picFileNames[ii];
string picPath = picDir+"/"+picName;
// cout<<picPath<<endl;
if(picPath[picPath.length()-1] == 'g'){
cout<<picName<<": ";
Mat srcImg = imread(picPath, 1);
AdaptiveSkinDetector detector;
detector.skinDetectFromImgShrink(srcImg);
}
}
}
|
15ab209b8a3d6dd5bf030eb42c0f35ed52d5f4e5
|
e0bd5c3aae3885d2efc09c54693554f9d2b2a1b5
|
/RayTrace/Pinhole.h
|
59e75bb9a881108d4a3b6ab7c2197e031dbf3bd6
|
[] |
no_license
|
Mrwanghao/RayTrace
|
0548c10b2fb75d7187ffdba6a5d5ff5fe2efae2b
|
aaf0a6974a6db91409952a566b4cda4de4785dd8
|
refs/heads/master
| 2020-03-24T08:01:07.436434
| 2018-08-28T10:05:47
| 2018-08-28T10:05:47
| 142,582,842
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 526
|
h
|
Pinhole.h
|
#pragma once
#include "Camera.h"
#include "Vect2.h"
#include "World.h"
class Pinhole : public Camera
{
public:
Pinhole();
Pinhole(const Pinhole& right);
virtual Camera* Clone() const;
Pinhole& operator=(const Pinhole& right);
virtual ~Pinhole();
public:
inline void SetViewDistance(float _distance) { distance = _distance; }
inline void SetZoom(float _zoom) { zoom = _zoom; }
Vect3 GetDirection(const Vect2& point) const;
virtual void RenderScene(const World& _world);
private:
float distance;
float zoom;
};
|
4175e4ddb2079806306ff90cbf4135e0f9163782
|
475e62ba79012bc8e507ae3a8788856388b56ace
|
/Gondola.h
|
4f6d8243509401a0f402474fc1dc25bd6e9c85b6
|
[] |
no_license
|
Martinsosa95/Chango
|
7409d9ce641a833b236268318b1b25c75313e7a2
|
9bda24bbf3cf857fbfacdc50f1b91894d1ca8ecc
|
refs/heads/master
| 2020-05-17T05:34:10.179468
| 2019-04-28T22:57:14
| 2019-04-28T22:57:14
| 183,538,080
| 1
| 2
| null | 2019-04-28T21:15:17
| 2019-04-26T01:55:12
|
C++
|
UTF-8
|
C++
| false
| false
| 1,999
|
h
|
Gondola.h
|
#ifndef GONDOLA_H
#define GONDOLA_H
#include "Producto.h"
using namespace std;
class Gondola{
private:
int cant_productos;
Producto* productos;
int producto_seleccionado;
public:
//Descripcion: constructor por parametros
//Pre: ---
//Pos: se creo la gondola con los valores indicados en los parametros.
Gondola(int nueva_cant_productos);
void asignar_seleccion(int seleccion);
Producto obtener_producto() const;
int obtener_producto_seleccionado();
//Pre:Se debe poder leer el archivo ingresado con el formato debido,es decir debera tener un producto por linea.
//Pos:Devuelve la cantidad total de productos leidos del archivo.
void asignar_cant_productos(int cantidad);
//Pre:Se debe poder crear un producto para poder ingresarlos los nuevos productos en gondola y el valor del parametro debe mayor o igual a 0.
//Pos:Se asigna una nueva direccion de memoria apuntanto hacia nuevos_productos.
void asignar_productos(Producto* nuevos_productos);
//Pre:Tiene que estar creado el objeto gondola.
//Pos:Devuelve la cantidad de productos que tiene la gondola.
int obtener_cant_productos();
//Pre:Tiene que estar creado el objeto gondola.
//Pos:Devuelve el puntero a los productos de la gondola.
Producto* obtener_productos();
//Pre:Tiene que estar creado el objeto gondola.
//Pos:Va a devolver la informacion completa del producto si es que se encuentra en la gondola.
int buscar_nombre(string nombre);
//Pre:Tiene que estar creado el objeto gondola.
//Pos:Va a devolver la informacion completa del producto si es que se encuentra en la gondola.
int buscar_codigo(int codigo);
//Pre:Tiene que estar creado el objeto gondola.
//Pos:Va a "eliminar" los productos del producto deseado.
void quitar_producto(Producto producto);
//Descripcion:Destructor de la gndola
//Pre:La gondola debe existir
//Post:La gondola fue destruida,es decir la memoria utilizada fue liberada
~Gondola();
};
#endif // GONDOLA_H
|
cb93a955bb12b35c3dbefba91caef0d482b157c6
|
0756dea0444ada160540685dd1d28fcd3ef4aac5
|
/src/function.cpp
|
fbf3bf56612a07552e2f3c05ab5a3c6ddd3a4fa7
|
[
"MIT"
] |
permissive
|
ange-yaghi/engine-sim
|
439e38f717bf46dbe8b6825d181ed77f711f8f21
|
85f7c3b959a908ed5232ede4f1a4ac7eafe6b630
|
refs/heads/master
| 2023-02-18T03:26:25.469967
| 2023-01-22T17:44:02
| 2023-01-22T17:44:02
| 439,491,516
| 8,177
| 795
|
MIT
| 2023-01-13T00:07:50
| 2021-12-18T00:14:57
|
C++
|
UTF-8
|
C++
| false
| false
| 5,268
|
cpp
|
function.cpp
|
#include "../include/function.h"
#include <algorithm>
#include <string.h>
#include <assert.h>
#include <cmath>
GaussianFilter *Function::DefaultGaussianFilter = nullptr;
Function::Function() {
m_x = m_y = nullptr;
m_capacity = 0;
m_size = 0;
m_filterRadius = 0;
m_yMin = m_yMax = 0;
m_inputScale = 1.0;
m_outputScale = 1.0;
if (DefaultGaussianFilter == nullptr) {
DefaultGaussianFilter = new GaussianFilter;
DefaultGaussianFilter->initialize(1.0, 3.0, 1024);
}
m_gaussianFilter = nullptr;
}
Function::~Function() {
assert(m_x == nullptr);
assert(m_y == nullptr);
}
void Function::initialize(int size, double filterRadius, GaussianFilter *filter) {
resize(size);
m_size = 0;
m_filterRadius = filterRadius;
m_gaussianFilter = (filter != nullptr)
? filter
: DefaultGaussianFilter;
}
void Function::resize(int newCapacity) {
double *new_x = new double[newCapacity];
double *new_y = new double[newCapacity];
if (m_size > 0) {
memcpy(new_x, m_x, sizeof(double) * m_size);
memcpy(new_y, m_y, sizeof(double) * m_size);
}
delete[] m_x;
delete[] m_y;
m_x = new_x;
m_y = new_y;
m_capacity = newCapacity;
}
void Function::destroy() {
delete[] m_x;
delete[] m_y;
m_x = nullptr;
m_y = nullptr;
m_capacity = 0;
m_size = 0;
}
void Function::addSample(double x, double y) {
if (m_size + 1 > m_capacity) {
resize(m_capacity * 2 + 1);
}
m_yMin = std::fmin(m_yMin, y);
m_yMax = std::fmax(m_yMax, y);
const int closest = closestSample(x);
if (closest == -1) {
m_size = 1;
m_x[0] = x;
m_y[0] = y;
return;
}
const int index = x < m_x[closest]
? closest
: closest + 1;
++m_size;
const size_t sizeToCopy = (size_t)m_size - index - 1;
if (sizeToCopy > 0) {
memmove(m_x + index + 1, m_x + index, sizeof(double) * sizeToCopy);
memmove(m_y + index + 1, m_y + index, sizeof(double) * sizeToCopy);
}
m_x[index] = x;
m_y[index] = y;
}
double Function::sampleTriangle(double x) const {
x *= m_inputScale;
const int closest = closestSample(x);
if (m_size == 0) return 0;
else if (x >= m_x[m_size - 1]) return m_y[m_size - 1] * m_outputScale;
else if (x <= m_x[0]) return m_y[0] * m_outputScale;
double sum = 0;
double totalWeight = 0;
for (int i = closest; i >= 0; --i) {
if (m_x[i] > x) continue;
if (std::abs(x - m_x[i]) > m_filterRadius) break;
const double w = triangle(m_x[i] - x);
sum += w * m_y[i];
totalWeight += w;
}
for (int i = closest; i < m_size; ++i) {
if (m_x[i] <= x) continue;
if (std::abs(m_x[i] - x) > m_filterRadius) break;
const double w = triangle(m_x[i] - x);
sum += w * m_y[i];
totalWeight += w;
}
return (totalWeight != 0)
? sum * m_outputScale / totalWeight
: 0;
}
double Function::sampleGaussian(double x) const {
x *= m_inputScale;
const int closest = closestSample(x);
const double filterRadius = m_filterRadius * m_gaussianFilter->getRadius();
double sum = 0;
double totalWeight = 0;
if (m_size == 0) return 0;
else if (x > m_x[m_size - 1]) {
const double w = m_gaussianFilter->evaluate(0);
sum += w * m_y[m_size - 1];
totalWeight += w;
}
else if (x < m_x[0]) {
const double w = m_gaussianFilter->evaluate(0);
sum += w * m_y[0];
totalWeight += w;
}
for (int i = closest; i >= 0; --i) {
if (std::abs(x - m_x[i]) > filterRadius) break;
const double w = m_gaussianFilter->evaluate((m_x[i] - x) / m_filterRadius);
sum += w * m_y[i];
totalWeight += w;
}
for (int i = closest + 1; i < m_size; ++i) {
if (std::abs(m_x[i] - x) > filterRadius) break;
const double w = m_gaussianFilter->evaluate((m_x[i] - x) / m_filterRadius);
sum += w * m_y[i];
totalWeight += w;
}
return (totalWeight != 0)
? sum * m_outputScale / totalWeight
: 0;
}
bool Function::isOrdered() const {
for (int i = 0; i < m_size - 1; ++i) {
if (m_x[i] > m_x[i + 1]) return false;
}
return true;
}
void Function::getDomain(double *x0, double *x1) {
if (m_size == 0) {
*x0 = *x1 = 0;
}
else {
*x0 = m_x[0];
*x1 = m_x[m_size - 1];
}
}
void Function::getRange(double *y0, double *y1) {
*y0 = m_yMin;
*y1 = m_yMax;
}
double Function::triangle(double x) const {
return (m_filterRadius - std::abs(x)) / m_filterRadius;
}
int Function::closestSample(double x) const {
if (std::isnan(x)) {
return 0;
}
int l = 0;
int r = m_size - 1;
if (m_size == 0) return -1;
else if (x <= m_x[l]) return l;
else if (x >= m_x[r]) return r;
while (l + 1 < r) {
const int m = (l + r) / 2;
if (x > m_x[m]) {
l = m;
}
else if (x < m_x[m]) {
r = m;
}
else if (x == m_x[m]) {
return m;
}
}
return (x - m_x[l] < m_x[r] - x)
? l
: r;
}
|
f099252155467be24d55500fe784d2e3e9280aa3
|
a9c12a1da0794eaf9a1d1f37ab5c404e3b95e4ec
|
/CTPServer/CTPTDLoginSA.h
|
cb88671bae632a2405deb50fc7f886996529c998
|
[] |
no_license
|
shzdtech/FutureXPlatform
|
37d395511d603a9e92191f55b8f8a6d60e4095d6
|
734cfc3c3d2026d60361874001fc20f00e8bb038
|
refs/heads/master
| 2021-03-30T17:49:22.010954
| 2018-06-19T13:21:53
| 2018-06-19T13:21:53
| 56,828,437
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,062
|
h
|
CTPTDLoginSA.h
|
/***********************************************************************
* Module: CTPTDLoginSA.h
* Author: milk
* Modified: 2015年8月1日 21:18:52
* Purpose: Declaration of the class CTPTDLoginSA
***********************************************************************/
#if !defined(__CTP_CTPTDLoginSA_h)
#define __CTP_CTPTDLoginSA_h
#include "../message/LoginHandler.h"
#include "../dataobject/UserInfoDO.h"
#include "ctpexport.h"
class CTP_CLASS_EXPORT CTPTDLoginSA : public LoginHandler
{
public:
dataobj_ptr HandleRequest(const uint32_t serialId, const dataobj_ptr& reqDO, IRawAPI* rawAPI, const IMessageProcessor_Ptr& msgProcessor, const IMessageSession_Ptr& session);
dataobj_ptr HandleResponse(const uint32_t serialId, const param_vector& rawRespParams, IRawAPI* rawAPI, const IMessageProcessor_Ptr& msgProcessor, const IMessageSession_Ptr& session);
protected:
std::shared_ptr<UserInfoDO> Login(const dataobj_ptr reqDO, IRawAPI* rawAPI, const IMessageProcessor_Ptr& msgProcessor, const IMessageSession_Ptr& session);
private:
};
#endif
|
ee1fe967b1cf5c7a9eedfbd20834c3d394aabf84
|
fca68c5fec6df6f999408571315c2b8e7c4b8ce9
|
/service/navtrack_home/src/Navigation/Class/NavShower_condes.cc
|
306a490270cc94a34864bc8ceaa41f7f71748ef7
|
[] |
no_license
|
jpivarski-talks/1999-2006_gradschool-3
|
8b2ea0b6babef104b0281c069994fc9894a05b14
|
57e80d601c0519f9e01a07ecb53d367846e8306e
|
refs/heads/master
| 2022-11-19T12:01:42.959599
| 2020-07-25T01:19:59
| 2020-07-25T01:19:59
| 282,235,559
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,410
|
cc
|
NavShower_condes.cc
|
// -*- C++ -*-
//
// Package: Navigation
// Module: NavShower
//
// Description:
//
// Implementation:
//
// Author: Brian K. Heltsley
// Created: Tue Jun 22 10:46:38 EDT 1999
// $Id: NavShower_condes.cc,v 1.6 2003/02/03 20:16:17 bkh Exp $
//
// Revision history
//
// $Log: NavShower_condes.cc,v $
// Revision 1.6 2003/02/03 20:16:17 bkh
// Adjust to new mc tagging interface
// Get rid of friends with public access to record
// New track matching alternatives
//
// Revision 1.5 2002/11/21 16:52:40 bkh
// Add new NavShower fcn giving back track matches in same con reg
// Require NavTrack mcTag to have same charge as track
//
// Revision 1.4 2002/08/08 16:55:09 cleo3
// NavShower no longer owns any additional memory
//
// Revision 1.3 2002/03/21 01:51:43 cdj
// NavShower::noTrackMatch now just looks at Lattice
//
// Revision 1.2 2001/12/13 20:54:04 bkh
// Implement eta-->gamgam access from NavShower just as with pi0
// For track match object, get energy and momentum directly because
// shower energy can have run-time adjustments
//
// Revision 1.1 2001/11/13 16:05:36 bkh
// Separated off pi0 pieces to avoid making everyone link to PhotonDecays
//
// Revision 1.12 2001/11/09 20:26:39 bkh
// Added in shower-->pi0 functionality
//
// Revision 1.11 2001/10/30 16:55:40 bkh
// Fix bug(s) with con regs
//
// Revision 1.10 2001/10/26 21:53:53 bkh
// Add features to showers and connected region objects
//
// Revision 1.9 2001/07/09 20:49:11 bkh
// Fix nearestTracks() implementation to include all matched tracks
//
// Revision 1.8 2001/04/03 16:57:56 bkh
// Implement lists of nearby showers/tracks based on distance
//
// Revision 1.7 2000/10/04 20:00:20 bkh
// Remove pi0-vetoing from NavShower; bad idea
//
// Revision 1.6 2000/10/03 18:40:48 bkh
// Add pi0/eta access to NavShower for vetoing, etc.
//
// Revision 1.5 2000/08/11 00:20:59 bkh
// Add operator<< functionality to these classes
//
// Revision 1.4 2000/01/20 16:02:04 bkh
// Make consistent with new object for hit-shower link datum
//
// Revision 1.3 1999/12/06 18:12:42 bkh
// Change interface to use FATables where possible not vectors
//
// Revision 1.2 1999/08/09 16:25:09 bkh
// Massive renaming
//
// Revision 1.1 1999/06/29 21:10:38 bkh
// New classes associated with analysis-level shower object
//
#include "Experiment/Experiment.h"
// system include files
#include <assert.h>
#if defined(STL_TEMPLATE_DEFAULT_PARAMS_FIRST_BUG)
// You may have to uncomment some of these or other stl headers
// depending on what other header files you include (e.g. FrameAccess etc.)!
//#include <string>
#include <vector>
//#include <set>
#include <map>
#include <algorithm>
//#include <utility>
#endif /* STL_TEMPLATE_DEFAULT_PARAMS_FIRST_BUG */
// user include files
//#include "Experiment/report.h"
#include "FrameAccess/FATable.h"
#include "FrameAccess/FAConstPtrTable.h"
#include "Navigation/NavTkShMatch.h"
#include "Navigation/NavShower.h"
#include "Navigation/NavShowerServer.h"
#include "Navigation/NavConReg.h"
#include "Navigation/NavPi0ToGG.h"
#include "Navigation/NavEtaToGG.h"
//#include "PhotonDecays/PhdPi0.h"
#include "KinematicTrajectory/KTKinematicData.h"
#include "C3cc/CcAssignedEnergyHit.h"
// STL classes
// You may have to uncomment some of these or other stl headers
// depending on what other header files you include (e.g. FrameAccess etc.)!
//#include <string>
#include <vector>
//#include <set>
#include <map>
#include <algorithm>
//#include <utility>
//
// constants, enums and typedefs
//
static const char* const kReport = "Navigation.NavShower_condes" ;
// ---- cvs-based strings (Id and Tag with which file was checked out)
static const char* const kIdString = "$Id: NavShower_condes.cc,v 1.6 2003/02/03 20:16:17 bkh Exp $";
static const char* const kTagString = "$Name: $";
//
// static data member definitions
//
//
// constructors and destructor
//
NavShower::NavShower( const CcShowerAttributes& aAtts ,
const NavShowerServer& aServer ) :
m_attributes ( aAtts ) ,
m_server ( aServer ) ,
m_conRegPtr ( 0 ) ,
m_photonPtr ( 0 ) ,
m_hasTrackMatch( NavShower::kMatchUnknown),
m_trackMatches ( 0 ) ,
m_conRegTrackMatches ( 0 ) ,
m_assignedHits ( 0 ) ,
m_nearestMatchedShowers ( 0 ) ,
m_nearestUnmatchedShowers ( 0 ) ,
m_nearestTracks ( 0 ) ,
m_bremTrack ( 0 ) ,
m_hasSimpleMatch ( false ) ,
m_simpleMatch ( 0 ) ,
m_angSimpleMatch ( 999 ) ,
m_pi0s ( 0 ) ,
m_etas ( 0 ) ,
m_conReg50 ( false ) ,
m_noConReg50 ( false )
{
}
// NavShower::NavShower( const NavShower& rhs )
// {
// // do actual copying here; if you implemented
// // operator= correctly, you may be able to use just say
// *this = rhs;
// }
NavShower::~NavShower()
{
delete m_assignedHits ;
delete m_photonPtr ;
//delete m_trackMatches ;
delete m_nearestMatchedShowers ;
delete m_nearestUnmatchedShowers ;
delete m_nearestTracks ;
//delete m_pi0s ;
//delete m_etas ;
}
//
// assignment operators
//
// const NavShower& NavShower::operator=( const NavShower& rhs )
// {
// if( this != &rhs ) {
// // do actual copying here, plus:
// // "SuperClass"::operator=( rhs );
// }
//
// return *this;
// }
//
// member functions
//
//
// const member functions
//
//
|
ad20e61c584019bbc7b5ee7e8f90e8594848660a
|
ff906e1bf3405aa5b77eb90022a7ce7b30768df0
|
/viewer.cpp
|
323188be6968f84c89dbb12fe2095fd35454b55a
|
[] |
no_license
|
shadimsaleh/computer_vision_pointcloud_merger
|
28f1c5f62ba7c135ec4cd28774727906b6ac967a
|
e8c9fe13b78b79145dbf3b6e5f363072d6ba6c03
|
refs/heads/master
| 2021-01-12T11:11:51.231198
| 2014-06-27T12:27:12
| 2014-06-27T12:27:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,650
|
cpp
|
viewer.cpp
|
#include "definitions.h"
using namespace std;
pcl::PointCloud < POINT_TYPE >::Ptr
flipyz (
pcl::PointCloud < POINT_TYPE >::Ptr in
) {
pcl::PointCloud < POINT_TYPE >::Ptr ret(new pcl::PointCloud < POINT_TYPE >);
pcl::copyPointCloud(*in, *ret);
for (size_t i = 0; i < ret->points.size (); ++i) {
ret->points[i].z = - ret->points[i].z;
ret->points[i].y = - ret->points[i].y;
}
return ret;
}
void
show_cloud (
pcl::PointCloud<POINT_TYPE>::Ptr cloud,
pcl::PointCloud<POINT_TYPE>::Ptr keypoints
)
{
//... populate cloud
pcl::visualization::PCLVisualizer viewer ("3D Viewer");
viewer.setBackgroundColor(0.5, 0.5, 0.5);
pcl::visualization::PointCloudColorHandlerCustom<POINT_TYPE> keypoints_color_handler (keypoints, 0, 255, 0);
pcl::visualization::PointCloudColorHandlerRGBField<POINT_TYPE> cloud_color_handler(cloud);
viewer.addPointCloud<POINT_TYPE> (keypoints, keypoints_color_handler, "keypoints");
viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 7, "keypoints");
viewer.addPointCloud<POINT_TYPE> (cloud, cloud_color_handler, "cloud");
while (!viewer.wasStopped ())
{
viewer.spinOnce();
}
}
void
show_correspondences (
pcl::PointCloud<POINT_TYPE>::Ptr cloud1,
pcl::PointCloud<POINT_TYPE>::Ptr cloud2,
pcl::PointCloud<POINT_TYPE>::Ptr keypoints1,
pcl::PointCloud<POINT_TYPE>::Ptr keypoints2,
pcl::CorrespondencesPtr correspondences
)
{
//keypoints1 = flipyz(keypoints1);
//keypoints2 = flipyz(keypoints2);
//... populate cloud
pcl::visualization::PCLVisualizer viewer ("3D Viewer for correspondences");
viewer.setBackgroundColor(0.5, 0.5, 0.5);
pcl::visualization::PointCloudColorHandlerCustom<POINT_TYPE> keypoints1_color_handler (keypoints1, 0, 255, 0);
pcl::visualization::PointCloudColorHandlerCustom<POINT_TYPE> keypoints2_color_handler (keypoints2, 255, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<POINT_TYPE> cloud1_color_handler(cloud1);
pcl::visualization::PointCloudColorHandlerRGBField<POINT_TYPE> cloud2_color_handler(cloud2);
viewer.addPointCloud<POINT_TYPE> (keypoints1, keypoints1_color_handler, "keypoints1");
viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "keypoints1");
viewer.addPointCloud<POINT_TYPE> (keypoints2, keypoints2_color_handler, "keypoints2");
viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "keypoints2");
viewer.addPointCloud<POINT_TYPE> (cloud1, cloud1_color_handler, "cloud1");
viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "cloud1");
viewer.addPointCloud<POINT_TYPE> (cloud2, cloud2_color_handler, "cloud2");
viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "cloud2");
for (size_t i = 0; i < correspondences->size(); i++) {
const POINT_TYPE &p_src = keypoints2->points[(*correspondences)[i].index_query];
const POINT_TYPE &p_tgt = keypoints1->points[(*correspondences)[i].index_match];
std::stringstream ss("line");
ss << i;
viewer.addLine(p_src, p_tgt, 1, 1, 1, ss.str());
}
while (!viewer.wasStopped ())
{
viewer.spinOnce();
}
}
void
show_normals (
pcl::PointCloud<POINT_TYPE>::ConstPtr cloud,
pcl::PointCloud<pcl::Normal>::ConstPtr normals
)
{
// Visualization of keypoints along with the original cloud
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("Normals Viewer"));
pcl::visualization::PointCloudColorHandlerRGBField<POINT_TYPE> cloud_color_handler(cloud);
viewer->setBackgroundColor( 0.1, 0.1, 0.1 );
viewer->addPointCloud(cloud, cloud_color_handler, "cloud");
viewer->addPointCloudNormals<POINT_TYPE, pcl::Normal>(cloud, normals, 10, 0.02, "normals");
while (!viewer->wasStopped ())
{
viewer->spinOnce();
}
}
void
show_merged (
pcl::PointCloud<POINT_TYPE>::Ptr cloud1,
pcl::PointCloud<POINT_TYPE>::Ptr cloud2
)
{
//... populate cloud
pcl::visualization::PCLVisualizer viewer ("3D Viewer");
viewer.setBackgroundColor(0.5, 0.5, 0.5);
pcl::visualization::PointCloudColorHandlerRGBField<POINT_TYPE> cloud_color_handler1(cloud1);
pcl::visualization::PointCloudColorHandlerRGBField<POINT_TYPE> cloud_color_handler2(cloud2);
viewer.addPointCloud<POINT_TYPE> (cloud1, cloud_color_handler1, "cloud1");
viewer.addPointCloud<POINT_TYPE> (cloud2, cloud_color_handler2, "cloud2");
while (!viewer.wasStopped ())
{
viewer.spinOnce();
}
}
|
5174fe9979113949fa311ec549a5e673dc542f7d
|
49db059c239549a8691fda362adf0654c5749fb1
|
/2010/maltsev/task6/Pult/Pult.cpp
|
63ad2c546c0a40d61e394445f971636ce8e0bd91
|
[] |
no_license
|
bondarevts/amse-qt
|
1a063f27c45a80897bb4751ae5c10f5d9d80de1b
|
2b9b76c7a5576bc1079fc037adcf039fed4dc848
|
refs/heads/master
| 2020-05-07T21:19:48.773724
| 2010-12-07T07:53:51
| 2010-12-07T07:53:51
| 35,804,478
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,062
|
cpp
|
Pult.cpp
|
#include "Pult.h"
#include <QLabel>
#include <QErrorMessage>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QIntValidator>
Pult::Pult(QHostAddress& ip, qint16 port, QWidget *parent):QDialog(parent) {
my_ip = ip;
my_port = port;
setView();
connectButtons();
setNetworkData();
}
void Pult::setNetworkData() {
isSet = false;
my_udpSocket = new QUdpSocket(this);
my_udpSocket->bind(my_ip, my_port);
connect(my_udpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
}
void Pult::setView() {
QVBoxLayout* mainLayout = new QVBoxLayout(this);
QHBoxLayout* layout1 = new QHBoxLayout();
QLabel * ipLabel = new QLabel("IP:", this);
QLabel * portLabel = new QLabel("port:", this);
my_ipEdit = new QLineEdit("127.0.0.1", this);
my_portEdit = new QLineEdit(this);
my_portEdit->setValidator(new QIntValidator(0, 65535, this));
my_setButton = new QPushButton("Set", this);
layout1->addWidget(ipLabel);
layout1->addWidget(my_ipEdit);
layout1->addWidget(portLabel);
layout1->addWidget(my_portEdit);
layout1->addWidget(my_setButton);
mainLayout->addItem(layout1);
my_startButton = new QPushButton("Start", this);
mainLayout->addWidget(my_startButton);
layout1 = new QHBoxLayout();
my_leftButton = new QPushButton("<", this);
my_rightButton = new QPushButton(">", this);
my_leftButton->setEnabled(false);
my_rightButton->setEnabled(false);
my_startButton->setEnabled(false);
layout1->addWidget(my_leftButton);
layout1->addWidget(my_rightButton);
mainLayout->addItem(layout1);
}
void Pult::connectButtons() {
connect(my_setButton, SIGNAL(clicked()),
this, SLOT(setContact()));
connect(my_leftButton, SIGNAL(pressed()),
this, SLOT(sendLeft()));
connect(my_startButton, SIGNAL(clicked()),
this, SLOT(sendStart()));
connect(my_leftButton, SIGNAL(released()),
this, SLOT(sendStop()));
connect(my_rightButton, SIGNAL(pressed()),
this, SLOT(sendRight()));
connect(my_rightButton, SIGNAL(released()),
this, SLOT(sendStop()));
}
void Pult::setContact() {
QHostAddress temp_my_ipTo = my_ipTo;
if (!my_ipTo.setAddress(my_ipEdit->text())) {
my_ipTo = temp_my_ipTo;
if (isSet) {
my_ipEdit->setText(my_ipTo.toString());
my_portEdit->setText(QString::number(my_portTo));
}
QErrorMessage* ipError = new QErrorMessage(this);
ipError->showMessage("Invalid IP");
return;
}
my_portTo = my_portEdit->text().toInt();
isSet = true;
my_udpSocket->writeDatagram("<set/>", my_ipTo, my_portTo);
}
void Pult::sendRight() {
if (!isSet) {
QErrorMessage* ipError = new QErrorMessage(this);
ipError->showMessage("Contact is not set");
return;
}
my_udpSocket->writeDatagram("<command name = \"right\"/>", my_ipTo, my_portTo);
}
void Pult::sendLeft() {
if (!isSet) {
QErrorMessage* ipError = new QErrorMessage(this);
ipError->showMessage("Contact is not set");
return;
}
my_udpSocket->writeDatagram("<command name = \"left\"/>", my_ipTo, my_portTo);
}
void Pult::sendStart() {
if (!isSet) {
QErrorMessage* ipError = new QErrorMessage(this);
ipError->showMessage("Contact is not set");
return;
}
my_udpSocket->writeDatagram("<command name = \"start\"/>", my_ipTo, my_portTo);
}
void Pult::sendStop() {
if (!isSet) {
QErrorMessage* ipError = new QErrorMessage(this);
ipError->showMessage("Contact is not set");
return;
}
my_udpSocket->writeDatagram("<command name = \"stop\"/>", my_ipTo, my_portTo);
}
void Pult::readPendingDatagrams() {
while (my_udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(my_udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
my_udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
processTheDatagram(datagram);
}
}
bool Pult::PultXmlHandler::startElement(const QString &, const QString &, const QString & qName, const QXmlAttributes & atts) {
if (qName == "state") {
my_ts->gameOver = atts.value("gameover").toInt();
my_ts->started = atts.value("started").toInt();
my_ts->height = atts.value("height").toInt();
my_ts->width = atts.value("width").toInt();
}
if (qName == "racket") {
my_ts->tableHW = atts.value("halfwidth").toInt();
my_ts->tableX = atts.value("x").toInt();
}
if (qName == "ball") {
my_ts->ballX = atts.value("x").toInt();
my_ts->ballY = atts.value("y").toInt();
}
return true;
}
void Pult::processTheDatagram(QByteArray datagram) {
Pult::TableState* TS = Pult::TableState::createInstance(datagram);
if (TS->gameOver) {
my_startButton->setEnabled(false);
my_rightButton->setEnabled(false);
my_leftButton->setEnabled(false);
my_setButton->setEnabled(true);
} else {
my_setButton->setEnabled(false);
if (TS->started) {
my_startButton->setEnabled(false);
} else {
my_startButton->setEnabled(true);
}
if (TS->tableX > TS->tableHW) {
my_leftButton->setEnabled(true);
} else {
my_leftButton->setEnabled(false);
}
if (TS->tableX < TS->width - TS->tableHW) {
my_rightButton->setEnabled(true);
} else {
my_rightButton->setEnabled(false);
}
}
delete TS;
}
Pult::TableState* Pult::TableState::createInstance(const QByteArray& s) {
Pult::TableState* TS = new Pult::TableState();
QXmlSimpleReader reader;
Pult::PultXmlHandler* CH = new Pult::PultXmlHandler(TS);
reader.setContentHandler(CH);
QXmlInputSource buf;
buf.setData(s);
reader.parse(&buf);
delete CH;
return TS;
}
|
302f94aff7eb41722a6ea72fb89ec97b2e64444c
|
2f1cf12618d7ac91c38e38ac4a5ffe4794ff1f68
|
/game/Missile.h
|
8bc01a13ea230fbfaea68158ef27828a5e01e827
|
[] |
no_license
|
OC-MCS/p2finalproject-01-JoshKeenMurr
|
c4834922fca3dda915a2ecd569840db84ef5a9fe
|
dad2cfdfadb395db2eda3daae39a46b8ac18e3a3
|
refs/heads/master
| 2020-05-04T17:14:47.913374
| 2019-04-19T05:57:53
| 2019-04-19T05:57:53
| 179,303,632
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 950
|
h
|
Missile.h
|
#include <iostream>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
#pragma once
class Missile
{
private:
Sprite missileSprite; // sprite for the missile
public:
//===========================================================================
//Missile: default constructor for the missile class
// parameters:
// N/A
// return type: N/A
//===========================================================================
Missile()
{
}
//===========================================================================
//Missile: constructor for the missile class the passes the texture for the missile
// parameters:
// N/A
// return type: N/A
//===========================================================================
Missile(Texture &texture)
{
missileSprite.setTexture(texture);
}
Sprite getSprite();
void setPosition(float, float);
FloatRect getGlobalBounds();
Vector2f getPosition();
void missMove();
};
|
6da2610779f5e324db45b85b4333f9e26d5e5341
|
aa17f840cfaf6c660b5d284efc06025fa46da658
|
/CPP_HW_1/CPP_HW_1/Phone.h
|
2d93f6fd289870311e213027a357a226dc5b289b
|
[] |
no_license
|
iamemil/wut_projects
|
808ece42dc44d399e2ba1fe2d1ea108ccc523d0a
|
b4ec75da75e3d8d908a9aedefda43db6e02d996d
|
refs/heads/master
| 2020-05-06T20:28:38.190347
| 2019-04-08T22:55:50
| 2019-04-08T22:55:50
| 180,239,158
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 867
|
h
|
Phone.h
|
#pragma once
#include <string.h>
using namespace std;
class Phone {
private:
char Brand[30];
char Model[40];
unsigned int Number;
unsigned int Price;
static unsigned int RegisteredPhones;
int messageNum;
unsigned int messageOwner[5];
char messages[5][20];
public:
// Default Constructor
Phone();
// Parameterized Constructor
Phone(const char Brand[10],const char Model[15], unsigned int Price, unsigned int Number);
// Prints information about Phone instance
void Print() const;
// Method to send message to another phone
void SendMessage(const char * text, Phone& p1);
// Method to show messages
void ShowMessages();
// Friend function to calculate average price of 2 Phones
friend double AveragePrice(const Phone& p1, const Phone& p2);
// Shows the number of all registered phones
friend int RegisteredPhoneCount(const Phone& p1);
};
|
c09feee661ae493ff55f6a3fbb8ffd516586dde8
|
ce12cdfe1346c9babfaae48583d887fc25a56ebd
|
/HostApplication/Tracking/trackingalgo.cpp
|
8733a86116b53e91e5d555d930cec750688c32fa
|
[] |
no_license
|
noko31/GreyWind
|
ab100820643f821aefec087f29e126ff83d4d69a
|
ff3de38ba40bea47ef1da6d089e045b602ea953a
|
refs/heads/master
| 2020-04-08T23:49:09.831767
| 2015-01-20T10:31:26
| 2015-01-20T10:31:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 313
|
cpp
|
trackingalgo.cpp
|
#include "trackingalgo.h"
TrackingAlgo::TrackingAlgo(QObject *parent) :
QObject(parent)
{
}
TrackingAlgo::~TrackingAlgo(){
}
cv::Point TrackingAlgo::getCoordinate(){
return m_coordinate;
}
cv::Size TrackingAlgo::getSize(){
return m_size;
}
bool TrackingAlgo::getStatus(){
return m_status;
}
|
c2a1c770c504c04349f9ef23684869e3f1142829
|
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
|
/main/source/src/core/fragment/picking_old/vall/gen/LengthGen.cc
|
cb375a93266fd22461dfebd1eb60163a073fffec
|
[] |
no_license
|
MedicaicloudLink/Rosetta
|
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
|
01affdf77abb773ed375b83cdbbf58439edd8719
|
refs/heads/master
| 2020-12-07T17:52:01.350906
| 2020-01-10T08:24:09
| 2020-01-10T08:24:09
| 232,757,729
| 2
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,589
|
cc
|
LengthGen.cc
|
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file core/fragment/picking_old/vall/gen/LengthGen.cc
/// @brief default constant length fragment VallExtentGenerator
/// @author Yih-En Andrew Ban (yab@u.washington.edu)
// unit headers
#include <core/fragment/picking_old/vall/gen/LengthGen.hh>
#include <utility/vector1.hh>
namespace core {
namespace fragment {
namespace picking_old {
namespace vall {
namespace gen {
/// @brief default constructor
LengthGen::LengthGen() :
Super()
{}
/// @brief fragment size constructor
/// @param[in] frag_size the desired length of the fragment
LengthGen::LengthGen( Size const frag_size ) :
Super(),
frag_size_( frag_size )
{}
/// @brief copy constructor
LengthGen::LengthGen( LengthGen const & /*rval*/ ) = default;
/// @brief default destructor
LengthGen::~LengthGen() = default;
/// @brief copy assignment
LengthGen & LengthGen::operator =( LengthGen const & rval ) {
if ( this != &rval ) {
Super::operator =( rval );
frag_size_ = rval.frag_size_;
}
return *this;
}
/// @brief clone this object
VallFragmentGenOP LengthGen::clone() const {
return utility::pointer::make_shared< LengthGen >( *this );
}
/// @brief return the desired fragment extent w/requested fragment size
/// @return valid (true) extent if the end of the extent does not go past the
/// section_end, invalid (false) extent otherwise
/// @remarks we assume VallResidueIterator is a type of RandomAccessIterator, such as
/// those used in std::vector
LengthGen::Extent LengthGen::operator ()( VallResidueIterator extent_begin, VallResidueIterator section_end ) const {
Extent extent;
extent.begin = extent_begin;
// OK, we can't even REFER to this iterator if it goes beyond section_end
if ( frag_size_ > static_cast< core::Size >( section_end - extent_begin ) ) {
extent.valid = false;
extent.end = section_end;
} else {
extent.end = extent_begin + frag_size_;
extent.valid = ( extent.end <= section_end );
}
return extent;
}
} // namespace gen
} // namespace vall
} // namespace picking_old
} // namespace fragment
} // namespace core
|
86ef1169f523b5c683dc6fa0db1a12e6ba0d8d41
|
387549ab27d89668e656771a19c09637612d57ed
|
/DRGLib UE project/Source/FSDEngine/Public/SDFSingleChildBase.h
|
6871c9bdf49f443e90ce65802b2397bb69f7988d
|
[
"MIT"
] |
permissive
|
SamsDRGMods/DRGLib
|
3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a
|
76f17bc76dd376f0d0aa09400ac8cb4daad34ade
|
refs/heads/main
| 2023-07-03T10:37:47.196444
| 2023-04-07T23:18:54
| 2023-04-07T23:18:54
| 383,509,787
| 16
| 5
|
MIT
| 2023-04-07T23:18:55
| 2021-07-06T15:08:14
|
C++
|
UTF-8
|
C++
| false
| false
| 350
|
h
|
SDFSingleChildBase.h
|
#pragma once
#include "CoreMinimal.h"
#include "SDFBase.h"
#include "SDFSingleChildBase.generated.h"
UCLASS(Blueprintable)
class FSDENGINE_API USDFSingleChildBase : public USDFBase {
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
USDFBase* Child;
USDFSingleChildBase();
};
|
8fd9a0cc087da4396439650ebcf9a04accf03f17
|
aa5045647c14856d5db824be6c54f4e98b55544c
|
/Leki/Zacma.cpp
|
2b1b5b6f6659d7a6fb468238fce9efc994a3d41e
|
[] |
no_license
|
IXOFIXOF/Leki
|
164341b312a1d03107c64ecdd60f204d11b05b76
|
1d65c911730e26f036a0c2957e5f80063673588a
|
refs/heads/master
| 2020-03-18T07:53:19.638212
| 2018-05-31T14:15:44
| 2018-05-31T14:15:44
| 134,478,328
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 512
|
cpp
|
Zacma.cpp
|
#include "stdafx.h"
#include "Zacma.h"
CZacma::CZacma()
{
m_ProcentPopulacji = -1;
}
void CZacma::print(ostream& sru)
{
sru << "Jestem choroba ktora atakuje oczy. Nazywam sie: " << m_Nazwa << ". Leczy sie na mnie ok "
<< m_CzasLeczenia << " lat."<<" Atkuje ok "<<m_ProcentPopulacji<<" % ludzi.";
}
void CZacma::UstalDaneSpecyficzne()
{
cout << "Jaki procent populacji atakuje " << m_Nazwa << "\n";
cin >> m_ProcentPopulacji;
}
CZacma* CZacma::Clone()
{
return new CZacma(*this);
}
CZacma::~CZacma()
{
}
|
78695821abeca1c887ea00bab364022eb1614fa3
|
77e8abc3d2febb03132d662e000c2ed335d5c804
|
/myCode/main.cc
|
f954934887e0eb9b6e7a8460b68a461709c44ca2
|
[] |
no_license
|
yeahhhhhhhh/BPlusTree
|
b49ecddc176bbfbb4bb65dcde20a5b36293feebb
|
e4813f9eace06be620db88174e49e8005c040cb8
|
refs/heads/master
| 2020-05-01T08:40:18.824954
| 2019-04-15T06:55:41
| 2019-04-15T06:55:41
| 177,383,915
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 433
|
cc
|
main.cc
|
#include <iostream>
#include "BPlusTree.h"
using namespace std;
void aaa(Node* node){
for(int i = 0; i < node->keyNum; i++){
cout << node->arrKeys[i] << " ";
}
}
int main(int argc, char const *argv[])
{
BPlusTree* bt = new BPlusTree();
for(int i = 60; i > 0; i--){
bt->insert(i, i);
}
bt->print();
cout << "maxKey = " << bt->maxKey << endl;
bt->clear();
return 0;
}
|
dc0ca1b813813c014595977d8e9b9f4a1a7437ea
|
f8774839ebd935770609a331ee09057217bee463
|
/TVout/gameOfLife.ino
|
bbac4d9026329b554f30f515443a6ac8d602aa2f
|
[] |
no_license
|
andyfriedl/Arduino-samples
|
ff0ade4bc80afebea9e23d833da622c60ce020e4
|
0cd3a412ca30105e315f35a87b2267692bd81a24
|
refs/heads/master
| 2022-10-01T16:58:53.140397
| 2022-09-24T00:17:20
| 2022-09-24T00:17:20
| 42,628,781
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,488
|
ino
|
gameOfLife.ino
|
// Conway's Game Of Life 128x96 using TVout
// P.Beard
// March 2013
#include <TVout.h>
#define matWidth 4
#define matHeight 96
TVout TV;
unsigned long * myScreen;
void setup() {
TV.begin(NTSC, matWidth * 32, matHeight);
myScreen = (unsigned long *) TV.screen;
randomSeed(analogRead(0));
randomiseMatrix();
}
void loop() {
generateMatrix();
digitalWrite(13, !digitalRead(13));
}
unsigned long swapBytes(unsigned long x) {
return ((x & 0x000000ffUL) << 24) | ((x & 0x0000ff00UL) << 8) | ((x & 0x00ff0000UL) >> 8) | ((x & 0xff000000UL) >> 24);
}
void randomiseMatrix() {
//Set up initial cells in matrix
for (int r = 0; r < matHeight; r++) {
for (int c = 0; c < matWidth; c++) {
myScreen[r * matWidth + c] = random(0xffff) << 16 | random(0xffff);
}
}
}
void injectGlider() {
byte col = random(matWidth);
byte row = random(matHeight);
myScreen[(row+0) * matWidth + col] |= B0000111;
myScreen[(row+1) * matWidth + col] |= B0000001;
myScreen[(row+2) * matWidth + col] |= B0000010;
}
void generateMatrix() {
//Variables holding data on neighbouring cells
unsigned long NeighbourN[matWidth], NeighbourNW[matWidth], NeighbourNE[matWidth], CurrCells[matWidth], NeighbourW[matWidth];
unsigned long NeighbourE[matWidth], NeighbourS[matWidth], NeighbourSW[matWidth], NeighbourSE[matWidth], firstRow[matWidth];
unsigned long tot1, tot2, tot4, carry, NewCells;
int changes = 0; // counts the changes in the matrix
static int prevChanges = 256; // counts the changes in the matrix on prev generation
static int staleCount = 0; // counts the consecutive occurrances of the same number of changes in the matrix
//set up N, NW, NE, W & E neighbour data
//also take a copy of the first row data for use later when calculating last row
for (byte b = 0; b < matWidth; b++) {
NeighbourN[b] = swapBytes(myScreen[(matHeight-1) * matWidth + b]);
firstRow[b] = CurrCells[b] = swapBytes(myScreen[b]);
}
carry = NeighbourN[matWidth-1];
for (char b = 0; b < matWidth; b++) {
NewCells = NeighbourN[b];
NeighbourNW[b] = NewCells >> 1 | carry << 31;
carry = NewCells;
}
carry = NeighbourN[0];
for (char b = matWidth-1; b >= 0; b--) {
NewCells = NeighbourN[b];
NeighbourNE[b] = NewCells << 1 | carry >> 31;
carry = NewCells;
}
carry = CurrCells[matWidth-1];
for (char b = 0; b < matWidth; b++) {
NewCells = CurrCells[b];
NeighbourW[b] = NewCells >> 1 | carry << 31;
carry = NewCells;
}
carry = CurrCells[0];
for (char b = matWidth-1; b >= 0; b--) {
NewCells = CurrCells[b];
NeighbourE[b] = NewCells << 1 | carry >> 31;
carry = NewCells;
}
//Process each row of the matrix
for (byte row = 0; row < matHeight; row++) {
//Pick up new S, SW & SE neighbours
if (row < matHeight - 1) {
for (byte b = 0; b < matWidth; b++) {
NeighbourS[b] = swapBytes(myScreen[(row+1) * matWidth + b]);
}
}
else {
for (byte b = 0; b < matWidth; b++) {
NeighbourS[b] = firstRow[b];
}
}
carry = NeighbourS[matWidth-1];
for (char b = 0; b < matWidth; b++) {
NewCells = NeighbourS[b];
NeighbourSW[b] = NewCells >> 1 | carry << 31;
carry = NewCells;
}
carry = NeighbourS[0];
for (char b = matWidth-1; b >= 0; b--) {
NewCells = NeighbourS[b];
NeighbourSE[b] = NewCells << 1 | carry >> 31;
carry = NewCells;
}
for (char b = 0; b < matWidth; b++) {
//Count the live neighbours (in parallel) for the current row of cells
//However, if total goes over 3, we don't care (see below), so counting stops at 4
tot1 = NeighbourN[b];
tot2 = tot1 & NeighbourNW[b]; tot1 = tot1 ^ NeighbourNW[b];
carry = tot1 & NeighbourNE[b]; tot1 = tot1 ^ NeighbourNE[b]; tot4 = tot2 & carry; tot2 = tot2 ^ carry;
carry = tot1 & NeighbourW[b]; tot1 = tot1 ^ NeighbourW[b]; tot4 = tot2 & carry | tot4; tot2 = tot2 ^ carry;
carry = tot1 & NeighbourE[b]; tot1 = tot1 ^ NeighbourE[b]; tot4 = tot2 & carry | tot4; tot2 = tot2 ^ carry;
carry = tot1 & NeighbourS[b]; tot1 = tot1 ^ NeighbourS[b]; tot4 = tot2 & carry | tot4; tot2 = tot2 ^ carry;
carry = tot1 & NeighbourSW[b]; tot1 = tot1 ^ NeighbourSW[b]; tot4 = tot2 & carry | tot4; tot2 = tot2 ^ carry;
carry = tot1 & NeighbourSE[b]; tot1 = tot1 ^ NeighbourSE[b]; tot4 = tot2 & carry | tot4; tot2 = tot2 ^ carry;
//Calculate the updated cells:
// <2 or >3 neighbours, cell dies
// =2 neighbours, cell continues to live
// =3 neighbours, new cell born
NewCells = (CurrCells[b] | tot1) & tot2 & ~ tot4;
//Have any cells changed?
if (NewCells != CurrCells[b]) {
myScreen[row * matWidth + b] = swapBytes(NewCells);
//Count the change for "stale" test
changes++;
}
//Current cells (before update), E , W, SE, SW and S neighbours become
//new N, NW, NE, E, W neighbours and current cells for next loop
NeighbourN[b] = CurrCells[b];
NeighbourNW[b] = NeighbourW[b];
NeighbourNE[b] = NeighbourE[b];
NeighbourE[b] = NeighbourSE[b];
NeighbourW[b] = NeighbourSW[b];
CurrCells[b] = NeighbourS[b];
} //next col
} //next row
if (changes != prevChanges) staleCount = 0; else staleCount++; //Detect "stale" matrix
if (staleCount > 32) injectGlider(); //Inject a glider
prevChanges = changes;
}
|
e8858e8d22af13d40d7e8bb81f7b1545fc387e25
|
1e074e828ca4bd5e4ee239c81745b6b2b818a6c7
|
/apv5sdk-v15/autelan/plc-homeplug/classes/CPLChannel.hpp
|
aef9936a267fe3e340bf65aa5e050cfbf4ec9132
|
[] |
no_license
|
hades13/apv5sdk-v15
|
51698f727b17f0cc05cbfd0df6ffff3da31d5b6e
|
56b8a22a93e026580ecc8b33d18267e4ace4e02a
|
refs/heads/master
| 2020-03-18T11:34:29.809253
| 2016-05-03T10:45:27
| 2016-05-03T10:45:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,627
|
hpp
|
CPLChannel.hpp
|
/*====================================================================*
*
* CPLChannel.hpp - interface for the CPLChannel class
*
* Ethernet I/O channel managment for powerline applications;
*
* This software and documentation is the property of Intellon
* Corporation, Ocala, Florida. It is provided 'as is' without
* expressed or implied warranty of any kind to anyone for any
* reason. Intellon assumes no responsibility or liability for
* errors or omissions in the software or documentation and
* reserves the right to make changes without notification.
*
* Intellon customers may modify and distribute the software
* without obligation to Intellon. Since use of this software
* is optional, users shall bear sole responsibility and
* liability for any consequences of it's use.
*
*. Intellon HomePlug AV Application Programming Package;
*: Published 2007-2009 by Intellon Corp. ALL RIGHTS RESERVED;
*; For demonstration and evaluation only; Not for production use;
*
* Contributor(s):
* Charles Maier <charles.maier@intellon.com>
*
*--------------------------------------------------------------------*/
#ifndef CPLCHANNEL_HEADER
#define CPLCHANNEL_HEADER
/*====================================================================*
* system header files;
*--------------------------------------------------------------------*/
#if defined (WINPCAP)
# include <pcap.h>
# include <Packet32.h>
# include <ntddndis.h>
#endif
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../classes/stdafx.hpp"
#include "../classes/oflagword.hpp"
#include "../classes/ointerface.hpp"
#include "../classes/ointellon.hpp"
/*====================================================================*
* class constants;
*--------------------------------------------------------------------*/
#define CPLCHANNEL_FLAG_VERBOSE (1 << 0)
#define CPLCHANNEL_FLAG_SILENCE (1 << 1)
#define CPLCHANNEL_ETHERTYPE 0x88E1 /* in host byte order */
#define CPLCHANNEL_BPFDEVICE "/dev/bpf%d"
#define CPLCHANNEL_TIMEOUT 100
#define CPLCHANNEL_CANTREAD "Read timeout or network error"
#define CPLCHANNEL_CANTSEND "Send timeout or network error"
#define CPLCHANNEL_WONTDOIT "Device Refused Request"
#define CPLCHANNEL_CANTDOIT "(0x%02X) %s"
#define CPLCHANNEL_BRIDGES_MAX 0xFF
#define CPLCHANNEL_DEVICES_MAX 0xFF
/*====================================================================*
* class declaration;
*--------------------------------------------------------------------*/
class __declspec (dllexport) CPLChannel: public oflagword, public oethernet, public ointerface
{
public:
explicit CPLChannel (unsigned ifindex);
explicit CPLChannel (char const * ifname);
virtual ~ CPLChannel ();
signed Descriptor (void) const;
signed SendMessage (void const * memory, signed extent);
signed ReadMessage (void * memory, signed extent);
signed Bridges (void * memory, size_t extent);
signed Neighbors (void * memory, size_t extent);
private:
CPLChannel & init (void);
CPLChannel & open (void);
CPLChannel & link (void);
CPLChannel & dump (void const * memory, size_t extent);
signed mfd;
#if defined (__APPLE__) || defined (__OpenBSD__)
unsigned bpf_length;
#elif defined (WINPCAP)
pcap_t * msocket;
char merrbuf [PCAP_ERRBUF_SIZE];
#endif
unsigned mtimeout;
};
/*====================================================================*
* end definition;
*--------------------------------------------------------------------*/
#endif
|
7cbd8c269226aca62fa06089b5b59baa924ad468
|
1956af138784d983b812ef71b683a0c54c7f4a63
|
/质因数分解/分解质因数.cpp
|
418bf0f43bfb0702d9b5843f9ca9284b6bb527ba
|
[] |
no_license
|
wangzilong2019/lan-qiao
|
e46e6668ba1e7ef3a0b8ef69cb1bda41ac704642
|
d742a5cac56413ce46b0206edfb4422f35b33276
|
refs/heads/master
| 2020-09-09T15:26:39.297956
| 2020-01-13T13:30:22
| 2020-01-13T13:30:22
| 221,482,997
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 338
|
cpp
|
分解质因数.cpp
|
#include <stdio.h>
int main(){
int a,b,i,n,j;
scanf("%d%d",&a,&b);
for(i=a;i<=b;i++){
printf("%d=",i);
n=i;
j=2;
while(n!=j){
for(j=2;j<n;j++){
if(n%j==0&&n!=j){
printf("%d*",j);
n=n/j;
break;
}
}
}
printf("%d\n",n);
}
return 0;
}
|
efa5eb2ac89e7099ee6ad14586793a8a1dc0cb60
|
78d338559d773456cb830e89d692c7743b2cfc1e
|
/leetcode/algorithms/Jewels and Stones/JandS.cpp
|
ba178a26e38965c67fa84654a39f4ba8405d3280
|
[] |
no_license
|
kingback1/coding
|
ddf392acb9cbc71af8c16593a3ea2ff6f953c759
|
4839d6402b6f5b2e4dee8a24faa3c294e0b836cd
|
refs/heads/master
| 2021-06-04T19:07:47.212604
| 2018-02-22T13:00:06
| 2018-02-22T13:00:06
| 57,002,999
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 722
|
cpp
|
JandS.cpp
|
class Solution {
public:
int numJewelsInStones(string J, string S) {
if(J.length() <=0 || S.length() <=0)
return 0;
string tmp = "";
int count = 0;
for(int i =0; i<S.length(); i++)
{
if(J[0] == S[i])
{
count++;
}
else{
tmp+=S[i];
}
}
return numJewelsInStones(J.substr(1), tmp) + count;
}
};
//优化方法,用set
int numJewelsInStones(string J, string S) {
int res = 0;
set<char> setJ(J.begin(), J.end());
for (char s : S) if (setJ.count(s)) res++;
return res;
}
|
5a90690464d94035d50a7c7d9800d15beff2a14b
|
fd504941c40b9fa749f1a8c787555e70f2815bc5
|
/src/Delay.cpp
|
195ca6baf5e8fc1cea43c979a78e332805d37e3e
|
[] |
no_license
|
tmendoza/AudioDozer
|
e20febbaf3c2439874fefa0b683e4fa5cdba3712
|
98d7de1cbb4888348c9a7a6d57582d040fb6619d
|
refs/heads/master
| 2022-04-26T14:43:51.843677
| 2020-04-22T13:45:08
| 2020-04-22T13:45:08
| 166,310,210
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,836
|
cpp
|
Delay.cpp
|
/////////////////////////////////////////////////////
// delays
//
// (c) V Lazzarini, 2005
//////////////////////////////////////////////////////
#include "SndDefs.h"
float delay(float *sig, float dtime,
float *del, int *p, int vecsize, float sr){
int dt;
float out;
dt = (int) (dtime*sr);
for(int i=0; i < vecsize; i++){
out = del[*p];
del[*p] = sig[i];
sig[i] = out;
*p = (*p != dt-1 ? *p+1 : 0);
}
return *sig;
}
float comb(float *sig, float dtime, float gain,
float *delay, int *p, int vecsize, float sr){
int dt;
float out;
dt = (int) (dtime*sr);
for(int i=0; i < vecsize; i++){
out = delay[*p];
delay[*p] = sig[i] + out*gain;
sig[i] = out;
*p = (*p != dt-1 ? *p+1 : 0);
}
return *sig;
}
float allpass(float *sig, float dtime, float gain,
float *delay, int *p, int vecsize, float sr){
int dt;
float out;
dt = (int) (dtime*sr);
for(int i=0; i < vecsize; i++){
out = delay[*p];
delay[*p] = sig[i] + out*gain;
sig[i] = out - gain*sig[i];
*p = (*p != dt-1 ? *p+1 : 0);
}
return *sig;
}
float vdelay(float *sig, float vdtime, float maxdel,
float *delay, int *p, int vecsize, float sr){
int mdt,rpi;
float out, rp, vdt, frac, next;
vdt = vdtime*sr;
mdt = (int) (maxdel*sr);
if(vdt > mdt) vdt = (float) mdt;
for(int i=0; i < vecsize; i++){
rp = *p - vdt;
rp = (rp >= 0 ? (rp < mdt ? rp : rp - mdt) : rp + mdt);
rpi = (int) rp;
frac = rp - rpi;
next = (rpi != mdt-1 ? delay[rpi+1] : delay[0]);
out = delay[rpi] + frac*(next - delay[rpi]);
delay[*p] = sig[i];
sig[i] = out;
*p = (*p != mdt-1 ? *p+1 : 0);
}
return *sig;
}
float flanger(float *sig, float vdtime, float fdb, float maxdel,
float *delay, int *p, int vecsize, float sr){
int mdt, rpi;
float out, rp, vdt, frac,next;
vdt = vdtime*sr;
mdt = (int) (maxdel*sr);
if(vdt > mdt) vdt = (float) mdt;
for(int i=0; i < vecsize; i++){
rp = *p - vdt;
rp = (rp >= 0 ? (rp < mdt ? rp : rp - mdt) : rp + mdt);
rpi = (int) rp;
frac = rp - rpi;
next = (rpi != mdt-1 ? delay[rpi+1] : delay[0]);
out = delay[rpi] + frac*(next - delay[rpi]);
delay[*p] = sig[i] + out*fdb;
sig[i] = out;
*p = (*p != mdt-1 ? *p+1 : 0);
}
return *sig;
}
float fir(float *sig, float *imp, float *del,
int length, int *p, int vecsize, float sr){
float out=0.f; int rp;
for(int i=0; i < vecsize; i++){
del[*p] = sig[i];
*p = (*p != length-1 ? *p+1 : 0);
for(int j=0; j < length; j++){
rp = *p+j;
rp = (rp < length ? rp : rp - length);
out += (del[rp]*imp[length-1-j]);
}
sig[i] = out;
out = 0.f;
}
return *sig;
}
|
519db749f8acb714b79c4f062178ec6714c0acbf
|
b725a81b0946e00b0af43b3040d9a84dce9bc829
|
/objects/hLog/hLogGraphHelpers.cpp
|
2f675e879f9f59b6e7c66804574fb3802594e912
|
[] |
no_license
|
LukeThoma5/CSCW
|
5913e0cdd2e19d4c332b9b228029e949d0ecf186
|
2a4b4fa92d8bd38e48a0cf7100532f3b6bb7d989
|
refs/heads/master
| 2021-01-17T17:29:13.699600
| 2017-02-19T17:51:26
| 2017-02-19T17:51:26
| 70,406,929
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,713
|
cpp
|
hLogGraphHelpers.cpp
|
#include "../../headers/hLog.h"
#include "../../headers/logEvent.h"
#include <sstream>
using namespace std;
namespace SSG {
extern std::time_t sessionStartTime;
}
std::string hLog::coordToString(const std::vector<float>& coords)
//Convert x or y lists to comma seperated values in a string
{
//Only run if atleast 1 item
string retString; //Make a string object
stringstream retSS(retString); //Make a stringStream of that string object
int lastFloat = coords.size()-1;
for (int i=0; i<lastFloat; ++i) //For every item but the last
{
retSS << to_string(coords[i]) << ','; //Add the item and a comma
}
retSS << to_string(coords[lastFloat]); //Add the last item without a comma
return retSS.str(); //Evaluate string stream back to string
}
int hLog::findTimeStart(std::time_t comparisonTime)
{
for (int i=0, logEnd=log.size(); i<logEnd; ++i)
//For every item in the log
{
//If the current event is later than the start time return this position
if (log[i].getTime() > comparisonTime)
return i;
}
return log.size(); //If none found return the end so no loops execute
}
void hLog::getEventPointers(std::time_t startPoint, std::vector<logEvent*>& events, const std::string& eventType)
{
int startLocation = findTimeStart(startPoint); //Find the index of the first item past the start
for (int i=startLocation, logEnd=log.size(); i<logEnd; ++i)
//For every item from the entry point to the end
{
if (log[i].getType() == eventType) //If the log type that we are searching for
events.push_back(&log[i]); //Add its pointer to the events vector
}
cout << "Number of items found to plot " << events.size() << endl; //Debugging message
}
void hLog::getWeekEventPointers(std::time_t startPoint, std::vector<logEvent*>& events, const std::string& eventType)
{
time_t weekStart = startPoint - 302400; //startPoint - half a week
time_t weekEnd = startPoint + 302400; //startPoint + half a week
if (startPoint == 0) //If 0 set weekStart to 0 as it would have underflowed
weekStart = 0;
if (weekStart < 0) //If still somehow underflowed reset
weekStart = 0;
int startLocation = findTimeStart(weekStart); //Find index in vector from weekStart
for (int i=startLocation, logSize=log.size(); i<logSize; ++i)
{
if (log[i].getTime() > weekEnd) //If past the week end
break; //Stop adding the logEvent pointers
if (log[i].getType() == eventType) //If of the type that we want
events.push_back(&log[i]); //Add its pointer to the log
}
cout << "Number of items to average " << events.size() << endl; //Debug message
}
|
6e04fe774b0ee4609b83a13dccc38c7fb0b32f2b
|
d6a71446721d790ea431619666868312963afe8d
|
/CSC8503/CSC8503Common/Transform.h
|
bd5d35bb27e7e63136b805b5969edfb3ab332aa6
|
[] |
no_license
|
georgek98/CSC8508-Teamroject
|
8633eaac617c75089a506279474301031c95e04c
|
51067a6925513c6ece471ae802b3c50ad445a7fa
|
refs/heads/main
| 2023-04-14T02:23:49.462567
| 2021-04-18T16:59:41
| 2021-04-18T16:59:41
| 359,203,341
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,260
|
h
|
Transform.h
|
/* Created By Rich Davison
* Edited By Samuel Buzz Appleby
* 21/01/2021
* 170348069
* Transform Definition */
#pragma once
#include "../../Common/Matrix4.h"
#include "../../Common/Matrix3.h"
#include "../../Common/Vector3.h"
#include "../../Common/Quaternion.h"
#include "../../include/PxPhysicsAPI.h"
#include <vector>
using std::vector;
using namespace NCL::Maths;
using namespace physx;
namespace NCL
{
namespace CSC8503
{
class Transform
{
public:
Transform();
~Transform();
void SetPosition(const PxVec3& worldPos);
void SetScale(const PxVec3& worldScale);
void SetOrientation(const PxQuat& newOr);
//void
PxVec3 GetPosition() const
{
return pxPos;
}
PxVec3 GetScale() const
{
return pxScale;
}
PxQuat GetOrientation() const
{
return pxOrientation;
}
Matrix4 GetMatrix() const
{
return matrix;
}
void SetTextureScale(Vector3 scale);
Matrix4 GetTextureMatrix() const
{
return textureMatrix;
}
void UpdateMatrix();
protected:
//GameObject* go;
PxTransform* pxTransform;
Matrix4 matrix;
Matrix4 textureMatrix;
PxVec3 pxPos;
PxVec3 pxScale;
PxQuat pxOrientation;
};
}
}
|
1e35c0136bb0ea7365556f5f1522c6f7109b902a
|
c9d3176099bd20da79f28239a77b71324c6109b8
|
/day04/ex02/TacticalMarine.cpp
|
298516c47c76b1215bc1e1148beaecbeb4c9c76b
|
[] |
no_license
|
Ashypilo/Piscine-CPP
|
9db9e08e3f3853e9a198d256d42d8cca9090cb75
|
2ff24ffedae35c6bdb627f9a080513b2c2f63373
|
refs/heads/master
| 2020-08-13T15:37:28.047031
| 2019-10-14T09:12:36
| 2019-10-14T09:12:36
| 214,993,845
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,833
|
cpp
|
TacticalMarine.cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* TacticalMarine.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ashypilo <ashypilo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/04 20:12:39 by ashypilo #+# #+# */
/* Updated: 2019/10/05 13:25:40 by ashypilo ### ########.fr */
/* */
/* ************************************************************************** */
#include "TacticalMarine.hpp"
TacticalMarine::TacticalMarine()
{
std::cout << "Tactical Marine ready for battle" << std::endl;
return ;
}
TacticalMarine::TacticalMarine(TacticalMarine& over)
{
std::cout << "Tactical Marine ready for battle" << std::endl;
*this = over;
return ;
}
TacticalMarine::~TacticalMarine()
{
std::cout << "Aaargh ..." << std::endl;
return ;
}
TacticalMarine& TacticalMarine::operator=(const TacticalMarine& over)
{
(void)over;
return (*this);
}
ISpaceMarine* TacticalMarine::clone() const
{
ISpaceMarine *copy = new TacticalMarine();
return (copy);
}
void TacticalMarine::battleCry() const
{
std::cout << "For the holy PLOT !" << std::endl;
}
void TacticalMarine::meleeAttack() const
{
std::cout << "* attacks with chainsword *" << std::endl;
}
void TacticalMarine::rangedAttack() const
{
std::cout << "* attacks with bolter *" << std::endl;
}
|
2ae384f5f86cd7ed95765efbaec295be6cc886ad
|
5f071d7ed9a837c1442fbf1982e50a7180080491
|
/Source/Connection.cpp
|
adff8a0aea06dfaabaf68b90a544e8c97f9e3cd5
|
[] |
no_license
|
amweeden06/SRSem-Project-2009
|
7d877f2078c5c79cc5bc8c7b64554c43e5092efd
|
15edbfe668ff2eaf9851968fd1a86ef0257ff2f3
|
refs/heads/master
| 2021-01-19T09:31:13.883061
| 2010-04-12T00:10:51
| 2010-04-12T00:10:51
| 353,557
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 425
|
cpp
|
Connection.cpp
|
/*
*
*/
#include "Connection.hpp"
namespace Sewers
{
Connection::Connection()
{
set_width(CONNECTION_WIDTH);
set_height(CONNECTION_HEIGHT);
}
/* FUNCTION: draw()
* PRECONDITIONS: None
* POSTCONDITION: The connection has been placed in the drawing queue, to be
* drawn at the next glFlush()
* POSSIBLE RETURN VALUES: SUCCESS
*/
int Connection::draw() const
{
return SUCCESS;
}
}
|
ca7e02a99b087b3e421e851e924f648ad5807d45
|
2511f5350f86362f5eb2f536afe0b89f1360fa08
|
/src/ObjectTracker.h
|
5239489945889bea4c2827b6d909bea68eb83d7f
|
[
"MIT"
] |
permissive
|
asarasua/bloObjectesKinect
|
f5d5ac62ce94f7a5ae9409899b92c0c485cd2c1e
|
625a6ebce23d3897cdadae386f5f43761a42f9fe
|
refs/heads/master
| 2021-01-23T12:27:12.912480
| 2014-12-16T18:08:16
| 2014-12-16T18:08:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,127
|
h
|
ObjectTracker.h
|
//
// ObjectTracker.h
// bloObjectesKinect
//
// Created by Álvaro Sarasúa Berodia on 11/12/13.
//
//
#ifndef bloObjectesKinect_ObjectTracker_h
#define bloObjectesKinect_ObjectTracker_h
#include "ofxCv.h"
#include "ofMain.h"
#include "ofxKinect.h"
#include "ofxOsc.h"
class Object{
protected:
//cv::Point2f center;
float area;
unsigned int category;
bool touched;
public:
Object(){};
Object(float Area);
//cv::Point2f getCenter();
void setArea (float _area);
float getArea();
void setCategory (unsigned int _category);
unsigned int getCategory();
void setTouched (bool _touched);
bool isTouched ();
};
class ObjectTracker{
public:
ObjectTracker();
void update(ofxCv::ContourFinder& objectFinder, ofxCv::ContourFinder& handsFinder, ofxKinect& kinect);
private:
void clearBundle();
template <class T>
void addMessage(string address, T data);
void sendBundle();
void selectCategory (unsigned int _label);
map<unsigned int, Object> objects;
ofxOscSender oscSender;
ofxOscBundle bundle;
};
#endif
|
8373a8b71e0f80594ef4df89fd87b499f85eb1ab
|
350d6ea7d82208b5027e8c23a2a17bc42fef4daa
|
/include/math/ConvexHullGraham.h
|
75214d7143d48fd02b250c59bde84ce6aac6770b
|
[] |
no_license
|
bach74/Lisa
|
2436d4da3765b9fe307d5e3dc31bfe532cf37dce
|
d80af7b880c0f99b914028dcf330d00ef0540cd3
|
refs/heads/master
| 2021-01-23T11:49:37.826497
| 2010-12-09T16:31:22
| 2010-12-09T16:31:22
| 1,153,210
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,594
|
h
|
ConvexHullGraham.h
|
//
// This class uses the Graham scan algorithm to calculate the convex
// hull of a batch of points in 2D.
//
// The convex hull part of the code is based on the article from Dr. Dobb's Portal,
// September, 2007 by Mark Nelson
//
// instead of std::pair<float,float> Ogre::Vector3 is used with implicit y=0 (ground plane).
// That is .x and .z are convex hull vertices
//
#pragma once
#include <OgreVector3.h>
class ConvexHullGraham
{
public:
ConvexHullGraham(const std::vector<Ogre::Vector3>& points);
void partition_points();
std::vector<Ogre::Vector3> build_hull();
void build_half_hull(std::vector<Ogre::Vector3> input,
std::vector<Ogre::Vector3>& output, float factor);
// In this program we frequently want to look at three consecutive
// points, p0, p1, and p2, and determine whether p2 has taken a turn
// to the left or a turn to the right.
//
// We can do this by by translating the points so that p1 is at the origin,
// then taking the cross product of p0 and p2. The result will be positive,
// negative, or 0, meaning respectively that p2 has turned right, left, or
// is on a straight line.
static float direction(const Ogre::Vector3& p0, const Ogre::Vector3& p1, const Ogre::Vector3& p2)
{
return ((p0.x-p1.x)*(p2.z-p1.z))-((p2.x-p1.x)*(p0.z-p1.z));
}
float getDistanceToPointSquared(const Ogre::Vector3& A, const Ogre::Vector3& B, const Ogre::Vector3& p);
float getMinDistanceX(const Ogre::Vector3& A, const Ogre::Vector3& B, const Ogre::Vector3& p);
float getMinDistanceY(const Ogre::Vector3& A, const Ogre::Vector3& B, const Ogre::Vector3& p);
Ogre::Vector3 getCenter(const std::vector<Ogre::Vector3>& convexHull);
Ogre::Vector3 getMargins(const std::vector<Ogre::Vector3>& convexHull, const Ogre::Vector3& p);
protected:
// The raw data points generated by the constructor
std::vector<Ogre::Vector3> mRawPoints;
//
// These values are used to represent the partitioned set. A special
// leftmost and rightmost value, and the sorted set of upper and lower
// partitioned points that lie inside those two points.
//
Ogre::Vector3 left;
Ogre::Vector3 right;
std::vector<Ogre::Vector3> mUpperPartitionPoints;
std::vector<Ogre::Vector3> mLowerPartitionPoints;
//
// After the convex hull is created, the lower hull and upper hull
// are stored in these sorted sequences. There is a bit of duplication
// between the two, because both sets include the leftmost and rightmost point.
//
std::vector<Ogre::Vector3> mLowerHull;
std::vector<Ogre::Vector3> mUpperHull;
};
|
381fe712b1b223e1169202084380097ddc241f9b
|
b31d9ac2e881fec3aa9fa5f21f10da4b1db9bc17
|
/UCD/ecs40/p6/DayOfWeek.cpp
|
ac71210991fbacf161aafac2bad8692f1c268a3f
|
[
"MIT"
] |
permissive
|
darylnak/ucdavis-work
|
be7a4d5160d27fa40c2b2949c802448724a75b50
|
4bb41f5fc0e8e95197e22166e99576deefb0565a
|
refs/heads/master
| 2021-09-24T08:21:43.864710
| 2018-10-05T17:46:03
| 2018-10-05T17:46:03
| 78,607,206
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,794
|
cpp
|
DayOfWeek.cpp
|
// Author: Sean Davis
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <sstream>
#include "DayOfWeek.h"
#include <cctype>
using namespace std;
DayOfWeek::DayOfWeek(int currMonth, int currDay, int currYear) :
month(currMonth), day(currDay), year(currYear)
{
} // DayOfWeek()
bool DayOfWeek::operator==(char c)
{
if (c == 'M' && !strcmp(dayName, "Monday"))
return true;
if (c == 'T' && !strcmp(dayName, "Tuesday"))
return true;
if (c == 'W' && !strcmp(dayName, "Wednesday"))
return true;
if (c == 'R' && !strcmp(dayName, "Thursday"))
return true;
if (c == 'F' && !strcmp(dayName, "Friday"))
return true;
if (c == 'S' && !strcmp(dayName, "Saturday"))
return true;
if (c == 'U' && !strcmp(dayName, "Sunday"))
return true;
return false;
} // operator==()
std::ostream& operator<<(std::ostream &os, const DayOfWeek &dow)
{
char line[80], dayStr[3];
ostringstream convert;
string yearStr;
strcpy(line, dow.dayName);
strcat(line, ", ");
strcat(line, dow.monthName);
strcat(line, " ");
if(dow.day > 9)
{
dayStr[0] = dow.day / 10 + '0';
dayStr[1] = dow.day % 10 + '0';
dayStr[2] = '\0';
} // if day > 9
else // day < 10
{
dayStr[0] = dow.day + '0';
dayStr[1] = '\0';
} // else day < 10
convert << dow.year;
yearStr = convert.str();
strcat(line, dayStr);
strcat(line, ", ");
strcat(line, yearStr.c_str());
os << left << setw(30) << line << right;
return os;
} // operator<<()
std::istream& operator>>(std::istream &inf, DayOfWeek &dow)
{
int dateNumber = (dow.month - 1) * 31 + dow.day - 1 + (dow.year - 1990) * 372;
inf.seekg(dateNumber * sizeof(DayOfWeek));
inf.read((char*) &dow, sizeof(DayOfWeek));
return inf;
} // operator>>()
|
f0ad600dacd043b735eee7487b7b3c27f9fa78a9
|
011ceeff99beb9e1151cbba0d3db2149415a5dbb
|
/src/figure.h
|
8a456023f94043c43462a94901011dbfcdfb3765
|
[] |
no_license
|
ThomasLeMezo/ipe_generator
|
ff80f6ee26efdac8748f7e58ffd544f5a1000060
|
64e3313299c0a6398e9d6101764d13cebd86a90e
|
refs/heads/master
| 2020-09-12T01:19:14.800387
| 2020-09-04T13:58:17
| 2020-09-04T13:58:17
| 222,253,407
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,383
|
h
|
figure.h
|
#ifndef FIGURE_H
#define FIGURE_H
#include "ipelib.h"
#include "ibex_IntervalVector.h"
namespace ipegenerator {
#define MM_TO_BP 2.83467
enum FLOAT_PISTON_MVT{FLOAT_PISTON_EQUAL,FLOAT_PISTON_DOWN,FLOAT_PISTON_UP};
enum PATH_TYPE{STROKE_ONLY,STROKE_AND_FILL,FILL_ONLY};
class Figure
{
public:
/**
* @brief Figure
* @param frame_data size of the frame of data
* @param width in mm (default A4=210)
* @param height in mm (default A4=297)
*/
Figure(const ibex::IntervalVector &frame_data, const double &width=210, const double &height=297, const bool &keep_ratio=false);
/**
* @brief Figure constructor with the load of an existing Figure
* @param filename
* @param frame_data
* @param width
* @param height
* @param keep_ratio
*/
Figure(const std::string &filename, const ibex::IntervalVector &frame_data, const double &width=210, const double &height=297, const bool &keep_ratio=false);
~Figure();
void save_pdf(const std::string &file_name);
void save_ipe(const std::string &file_name);
// Ipe functions
void add_layer(const std::string &layer_name);
void set_visible(const std::string &layer_name, bool visible=true);
// Drawing functions
void draw_axis(const std::string &name_x, const std::string &name_y, const bool& enable_numbers=true);
size_t draw_arrow(const double &x0, const double &y0, const double &x1, const double &y1);
size_t draw_arrow(const ipe::Vector &v1, const ipe::Vector &v2);
size_t draw_text(const std::string &text, const double &x, const double &y, const bool& math_mode=false, const ipe::THorizontalAlignment& horizontal_align=ipe::EAlignHCenter);
size_t draw_box(const ibex::IntervalVector &box);
size_t draw_box(const ipe::Rect& box);
size_t draw_box(const ipe::Vector ¢er, const double &width, const bool& keep_ratio=false);
size_t draw_curve(const std::vector<double> &x, const std::vector<double> &y);
size_t draw_segment(const double &x0, const double &y0, const double &x1, const double &y1);
size_t draw_polygon(const std::vector<double>& x, const std::vector<double>& y, const bool& closed=true);
size_t draw_ellipse(const double& x, const double& y, const double& r1, const double& r2);
size_t draw_circle(const double &x, const double &y, const double &r);
size_t draw_circle_radius_final(const double &x, const double &y, const double &r);
size_t draw_symbol(const double& x, const double& y, const std::string &name, const double& size=1.0);
size_t draw_sector(const double &x, const double &y, const double &r1, const double &r2, const double &alpha_start, const double& alpha_end);
size_t draw_float(const double &x, const double &y, const double &piston, const double &compressibility, const FLOAT_PISTON_MVT &mvt=FLOAT_PISTON_EQUAL, const double &zoom=0.1);
// Style functions
void set_thickness_pen_factor(const double &val=1e-3);
void set_thickness_axis(const double &val=1e-3);
void set_distance_axis_text(const double &val);
void set_arrow_axis_size(const double &val);
void set_distance_number_graduation(const double &distance_number_graduation);
void set_size_axis_graduation(const double &size_axis_graduation);
void set_graduation_parameters(const double &start_x, const double &inter_x, const double &start_y, const double &inter_y);
void reset_scale(const double &width, const double &height, const bool &keep_ratio=false);
void set_scale_offset(const bool &enable);
void set_number_digits_axis_x(const size_t &val);
void set_number_digits_axis_y(const size_t &val);
void set_inverted_y();
void set_color_stroke(const std::string &color_stroke="");
void set_color_fill(const std::string &color_fill="");
void set_color_type(const PATH_TYPE &type);
void set_opacity(const int &opacity);
void set_current_layer(const std::string &layer_name);
void set_dashed(const std::string &dashed);
void set_line_width(const double &val);
void set_arrow_size(const double &val);
void reset_attribute();
void remove_object(const int &id);
private:
void load_style();
void set_layout();
void style_size();
void init_scale(const double &width, const double &height, const bool &keep_ratio);
void draw_arrow_axis(const ipe::Vector &pt1, const ipe::Vector &pt2);
enum AXIS_SENS{AXIS_VERTICAL,AXIS_HORIZONTAL};
void draw_axis_number(const double &number, const ipe::Vector &pos, const AXIS_SENS &sens);
void draw_axis_numbers();
// scale and translate in x axis
double s_t_x(const double &val);
double s_t_x_inv(const double &val);
// scale and translate in x axis
double s_t_y(const double &val);
double s_t_y_inv(const double &val);
private:
// Parameters
ibex::IntervalVector m_frame_data;
double m_output_width, m_output_height; // in bp
double m_scale_x=1.0, m_scale_y=1.0; // Scale factor
double m_offset_x=0.0, m_offset_y=0.0; // Adding offset to (0,0)
double m_offset_drawing_x=0.0, m_offset_drawing_y=0.0;
ipe::Matrix m_transform_global; // transformation offset + zoom
ipe::Matrix m_transform_global_keep_dimension; // transformation offset without zoom
ipe::Matrix m_transform_global_keep_y; // transformation offset + zoom
ipe::Matrix m_transform_global_keep_dimension_keep_y; // transformation offset without zoom
bool m_inversion_y = false;
double m_width, m_height;
bool m_keep_ratio;
// Ipe objects
ipe::Document * m_document;
ipe::Cascade * m_cascade_ref;
ipe::Page * m_page;
ipe::Layout m_layout;
ipe::StyleSheet * m_steel_sheet;
ipe::AllAttributes m_current_attr;
int m_current_layer=1;
// Ipe parameters
std::string m_ref_document = "/usr/local/etc/ipegenerator/basic.ipe";
double m_thickness_pen_factor = 1e-3; // thickness of pen
double m_arrow_axis_size = 4.294; // Corresponds to /normalsize in latex
double m_distance_axis_text = 3.0;
double m_distance_number_graduation = 2.0;
double m_size_axis_graduation = 3.0;
double m_general_offset = 0.0;
bool m_scale_offset = true;
size_t m_number_digits_axis_x = 3;
size_t m_number_digits_axis_y = 3;
double m_start_number_graduation_x = 0.0;
double m_start_number_graduation_y = 0.0;
double m_inter_graduation_x = 1.0;
double m_inter_graduation_y = 1.0;
// Latex
bool m_contain_latex = false;
};
inline void Figure::add_layer(const std::string &layer_name)
{
m_page->addLayer(layer_name.c_str());
m_page->setVisible(0, layer_name.c_str(), true);
}
inline void Figure::set_visible(const std::string &layer_name, bool visible)
{
m_page->setVisible(0, layer_name.c_str(), visible);
}
inline double Figure::s_t_x(const double &val)
{
return val*m_scale_x+m_offset_x+m_offset_drawing_x;
}
inline double Figure::s_t_y(const double &val)
{
return val*m_scale_y+m_offset_y+m_offset_drawing_y;
}
inline double Figure::s_t_x_inv(const double &val)
{
return (val-m_offset_x-m_offset_drawing_x)/m_scale_x;
}
inline double Figure::s_t_y_inv(const double &val)
{
return (val-m_offset_y-m_offset_drawing_y)/m_scale_y;
}
inline void Figure::set_distance_axis_text(const double &val)
{
m_distance_axis_text = val;
}
inline void Figure::set_arrow_axis_size(const double &val)
{
m_arrow_axis_size = val;
}
inline void Figure::set_distance_number_graduation(const double &distance_number_graduation)
{
m_distance_number_graduation = distance_number_graduation;
}
inline void Figure::set_size_axis_graduation(const double& size_axis_graduation)
{
m_size_axis_graduation = size_axis_graduation;
}
inline void Figure::set_graduation_parameters(const double &start_x, const double &inter_x, const double &start_y, const double &inter_y)
{
m_start_number_graduation_x = start_x;
m_inter_graduation_x = inter_x;
m_start_number_graduation_y = start_y;
m_inter_graduation_y = inter_y;
}
inline void Figure::set_scale_offset(const bool &enable)
{
m_scale_offset = enable;
}
inline void Figure::set_number_digits_axis_x(const size_t &val)
{
m_number_digits_axis_x = val;
}
inline void Figure::set_number_digits_axis_y(const size_t &val)
{
m_number_digits_axis_y = val;
}
}
#endif // FIGURE_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.