hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
003ce973c28b18fa87a17c8432c19b9bccb5c418 | 1,122 | cpp | C++ | 03/stu.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | null | null | null | 03/stu.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | null | null | null | 03/stu.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | null | null | null | /*
* @Descripttion:
* @version:
* @Author: HuSharp
* @Date: 2022-01-24 10:33:21
* @LastEditors: HuSharp
* @LastEditTime: 2022-01-24 21:36:21
* @@Email: 8211180515@csu.edu.cn
*/
#include <vector>
#include <iostream>
template <typename T>
void print(std::vector<T> const &a) {
std::cout << "{" ;
for (size_t i = 0; i < a.size(); i++) {
std::cout << a[i];
if (i != a.size() - 1)
std::cout << ",";
}
std::cout << "}" << std::endl;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {
os << __PRETTY_FUNCTION__ << std::endl;
os << "{";
for (size_t i = 0; i < a.size(); i++) {
std::cout << a[i];
if (i != a.size() - 1)
std::cout << ",";
}
os << "}";
return os;
}
#include <iostream>
#include <type_traits>
int main(int argc, char const *argv[]) {
std::vector<int> a = {1, 2, 3, 4, 6};
std::cout << a << std::endl;
std::vector<float> b = {3.12, 4.65, 3.29};
print(b);
std::cout << std::is_same<int const, const int>::value << std::endl;
return 0;
}
| 22.897959 | 73 | 0.509804 | [
"vector"
] |
00492039aadb33b5c49edb3d98639a842f5142d2 | 3,073 | cpp | C++ | engine/effects/source/RepelEffect.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/effects/source/RepelEffect.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/effects/source/RepelEffect.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "BresenhamLine.hpp"
#include "CoordUtils.hpp"
#include "Creature.hpp"
#include "EffectTextKeys.hpp"
#include "Game.hpp"
#include "MapUtils.hpp"
#include "MessageManager.hpp"
#include "RepelEffect.hpp"
using namespace std;
const int RepelEffect::DISTANCE_BLESSED = 5;
const int RepelEffect::DISTANCE_UNCURSED = 4;
const int RepelEffect::DISTANCE_CURSED = 3;
string RepelEffect::get_effect_identification_message(CreaturePtr creature) const
{
string message;
if (creature != nullptr)
{
message = EffectTextKeys::get_repel_effect_message(creature->get_description_sid(), creature->get_is_player());
}
return message;
}
Effect* RepelEffect::clone()
{
return new RepelEffect(*this);
}
bool RepelEffect::repel(CreaturePtr creature, const Coordinate& affected_coordinate, const int distance)
{
bool effect = false;
if (creature != nullptr)
{
// Get the creatures immediately adjacent.
MapPtr current_map = Game::instance().get_current_map();
CreatureDirectionMap cdm = MapUtils::get_adjacent_creatures(current_map, creature);
if (current_map != nullptr)
{
for (const auto& cdm_pair : cdm)
{
BresenhamLine bl;
Coordinate adj_cc = CoordUtils::get_new_coordinate(affected_coordinate, cdm_pair.first);
CreaturePtr adj_creature = cdm_pair.second;
Coordinate new_coord = CoordUtils::get_new_coordinate(adj_cc, cdm_pair.first, distance);
vector<Coordinate> line_points = bl.get_points_in_line(adj_cc.first, adj_cc.second, new_coord.first, new_coord.second);
Coordinate repel_loc = adj_cc;
TilePtr original_tile = current_map->at(adj_cc);
for (const Coordinate& c : line_points)
{
if (c == adj_cc)
{
continue;
}
TilePtr tile = current_map->at(c);
if (MapUtils::is_tile_available_for_creature(adj_creature, tile))
{
repel_loc = c;
}
else
{
// Something's blocking the way, or we can't move there for other
// reasons (solid rock and not incorporeal, etc), exit with the
// previously available location.
break;
}
}
if (repel_loc != adj_cc)
{
MapUtils::add_or_update_location(current_map, adj_creature, repel_loc, original_tile);
}
}
}
effect = true;
}
return effect;
}
bool RepelEffect::effect_blessed(CreaturePtr creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile)
{
return repel(creature, affected_coordinate, DISTANCE_BLESSED);
}
bool RepelEffect::effect_uncursed(CreaturePtr creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile)
{
return repel(creature, affected_coordinate, DISTANCE_UNCURSED);
}
bool RepelEffect::effect_cursed(CreaturePtr creature, ActionManager * am, const Coordinate& affected_coordinate, TilePtr affected_tile)
{
return repel(creature, affected_coordinate, DISTANCE_CURSED);
}
| 28.719626 | 143 | 0.692808 | [
"vector",
"solid"
] |
006b86f109933e33027a6d4c0caa378928bbf418 | 7,602 | cpp | C++ | F458/dsp/ccs_backup1/sunggu/lane_detector2.cpp | daeroro/IntegrationProject | 3b37f31e172cf4411ad0c2481e154e5facfb4d1e | [
"MIT"
] | null | null | null | F458/dsp/ccs_backup1/sunggu/lane_detector2.cpp | daeroro/IntegrationProject | 3b37f31e172cf4411ad0c2481e154e5facfb4d1e | [
"MIT"
] | null | null | null | F458/dsp/ccs_backup1/sunggu/lane_detector2.cpp | daeroro/IntegrationProject | 3b37f31e172cf4411ad0c2481e154e5facfb4d1e | [
"MIT"
] | 2 | 2019-04-29T01:05:25.000Z | 2019-04-29T02:45:44.000Z | #include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <string>
#include <vector>
class LaneDetector{
private:
double img_size;
double img_center;
bool left_flag = false;
bool right_flag = false;
cv::Point right_b;
double right_m; // y = m*x+b
cv::Point left_b;
double left_m;
putblic:
cv::Mat deNoise(cv::Mat inputImage);
cv::Mat edgeDetector(cv::Mat img_noise);
cv::Mat mask(cv::Mat img_edges);
std::vector<cv::Vec4i> houghLines(cv::Mat img_mask);
std::vector<std::vector<cv::Vec4i>> lineSeparation(std::vector<cv::Vec4i> lines, cv::Mat img_edges);
std::vector<cv::Point> regression(std::vector<std::vector<cv::Vec4i>> left_right_lines, cv::Mat inputImage);
std::string predicTurn();
int plotLane(cv::Mat inputImage, std::vector<cv::Point> lane, std::string turn)'
};
cv::Mat LaneDetector::deNoise(cv::Mat inputImage){
cv::Mat output;
cv::GaussianBlur(inputImage, output, cv::Size(3, 3), 0, 0);
return output;
}
cv::Mat LaneDetector::edgeDetector(cv::Mat img_noise){
cv::Mat output;
cv::Mat kernel;
cv::Point anchor;
cv::cvtColor(img_noise, output, cv::COLOR_RGB2GRAY);
cv::threshold(output, output, 140, 255, cv::THRESH_BINARY);
anchor = cv::Point(-1,-1);
kernel = cv::Mat(1, 3, CV_32F);
kernel.at<float>(0, 0) = -1;
kernel.at<float>(0, 1) = 0;
kernel.at<float>(0, 2) = 1;
cv::filter2D(output, output, -1, kernel, anchor, 0, cv::BORDER_DEFAULT);
return output;
}
cv::Mat LaneDetector::mask(cv::Mat img_edges){
cv::Mat output;
cv::Mat mask = cv::Mat::zeros(img_edges.size(), img_edges.type())
#if 0
cv::Point pts[4] = {
cv::Point(210, 720),
cv::Point(550, 450),
cv::Point(717, 450),
cv::Point(1280, 720)
};
#endif
// 210 / 1280 ==>> x/450, 73
// 550 / 1280 ==>> x/450, 193
// 450 / 720 ==>> x/300, 187
// 717 / 1280 ==>> x/450, 252
cv::Point pts[4] ={
cv::Point(73, 300);
cv::Point(193, 187);
cv::Point(252, 187);
cv::Point(450, 300)
};
cv::fillConvexPoloy(mask, pts, 4, cv::Scalar(255, 0, 0));
cv::bitwise_and(img_edges, mask, output);
return output;
}
std::vector<cv::Vec4i> LaneDetector::houghLines(cv::Mat img_mask){
std::vector<cv::Vec4i> line;
HoughLinesP(img_mask, line, 1, CV_PI/180, 20, 20, 30);
return line;
}
std::vector<std::vector<cv::Vec4i>>
LaneDetector::lineSeparation(
std::vector<cv::Vec4i> lines, cv::Mat img_edges){
std::vector<std::vector<cv::Vec4i>> output(2);
size_t j = 0;
cv::Point ini;
cv::Point fini;
double slope_thresh = 0.3;
std::vector<double> slopes;
std::vector<cv::Vec4i> selected_lines;
std::vector<cv::Vec4i> right_lines, left_lines;
for(auto i : lines){
ini = cv::Point(i[0], i[1]);
fini = cv::Point(i[2], i[3]);
double slope = (static_cast<double>(fini.y)-
static_cast<double>(ini.y))/
(static_cast<double>(fini.x)-
static_cast<double>(ini.x)+
0.00001);
if(std::abs(slope) > slope_thresh){
slopes.push_back(slope);
selected_lines.push_back(i);
}
}
img_center = static_cast<double>((img_edges.cols / 2));
while(j < selected_lines.size()){
ini = cv::Point(selected_lines[j][0],
selected_lines[j][1]);
fini = cv::Point(selected_lines[j][2],
selected_lines[j][3]);
if(slopes[j] > 0 &&
fini.x > img_center &&
ini.x > img_center) {
right_lines.push_back(selected_lines[j]);
right_flag = true;
} else if(slopes[j] < 0 &&
fini.x < img_center &&
ini.x < img_center){
left_lines.push_back(selected_lines[j]);
left_flag = true;
}
j++;
}
output[0] = right_lines;
output[1] = left_lines;
return output;
}
std::vector<cv:Point> LaneDetector::regression(
std::vector<std::vector<cv::Vec4i> > left_right_lines,
cv::Mat inputImage) {
std::vector<cv::Point> output(4);
cv::Point ini;
cv::Point fini;
cv::Point ini2;
cv::Point fini2;
cv::Vec4d right_line;
cv::Vec4d left_line;
std::vector<cv::Point> right_pts;
std::vector<cv::Point> left_pts;
if(right_flag == true){
for (auto i : left_right_lines[0]) {
ini = cv::Point(i[0], i[1]);
fini = cv::Point(i[2], i[3]);
right_pts.push_back(ini);
right_pts.push_back(fini);
}
if(right_pts.size() > 0){
cv::fitLine(right_pts, right_line,
CV_DIST_L2, 0, 0.01, 0.01);
right_m = right_line[1] / right_line[0];
right_b = cv::Point(right_line[2],
right_line[3]);
}
}
if(left_flag == true) {
for(auto j : left_right_lines[1]) {
ini2 = cv:Point(j[0], j[1]);
fini2 = cv::Point(j[2], j[3]);
left_pts.push_back(ini2);
left_pts.push_back(fini2);
}
if(left_pts.size() > 0){
cv::fitLine(left_pts, left_line,
CV_DIST_L2, 0, 0.01, 0.01);
left_m = left_line[1] / left_line[0];
left_b = cv::Point(left_line[2], left_line[3]);
}
}
int ini_y = inputImage.rows;
int fin_y = 165;
double right_ini_x = ((ini_y - right_b.y) / right_m) +
right_b.x;
double right_fin_x = ((fin_y - right_b.y / right_m) +
right_b.x;
double left_ini_x = ((ini_y - left_b.y)/ left_m) +left_b.x;
double left_fin_x = ((fin_y - left_b.y)/ left_m) +left_b.x;
output[0] = cv::Point(right_ini_x, ini_y);
output[1] = cv::Point(right_fin_x, fin_y);
output[2] = cv::Point(left_ini_x, ini_y);
output[3] = cv::Point(left_fin_x, fin_y);
return output;
}
std::string LaneDetector::predicTurn(){
std::string output;
double vanish x;
double thr_vp = 10;
vanish_x = static_cast<double>((right_m*right_b.x)-
(left_m*left_b.x) - right_b.y + left_b.y) / (right_m -left_m));
if(vanish_x < (img_center - thr_vp))
output = "Left Turn";
else if(vanish_x > (img_center +thr_vp))
output = "Right Turn";
else if(vanish_x >= (img_center - thr_vp)) &&
vanish_x <= (img_center +thr_vp))
output = "Straight";
return output;
}
int LaneDetector::plotLane(cv::Mat inputImage,
std::vector<cv::Point> lane, std::string turn){
std::vector<cv::Point> poly_points;
cv::Mat output;
inputImage.copyTo(output);
poly_points.push_back(lane[2]);
poly_points.push_back(lane[0]);
poly_points.push_back(lane[1]);
poly_points.push_back(lane[3]);
cv::fillConvexPoly(output, poly_points,
cv::Scalar(0, 0, 255), CV_AA, 0);
cv::addWeighted(output, 0.3, inputImage,
1.0 - 0.3, 0, inputImage);
cv::line(inputImage, lane[0], lane[1], cv::Scalar(0, 255, 255), 5, CV_AA);
cv::line(inputImage, lane[2], lane[3], cv::Scalar(0, 255, 255), 5, CV_AA);
cv::putText(inputImage, turn, cv::Point(50, 90),
cv::FONT_HERSHEY_COMPLEX_SMALL, 3,
cv::Scalar(0, 255, 0), 1, CV_AA);
cv::namedWindow("Lane", CV_WINDOW_AUTOSIZE);
cv::imshow("Lane", inputImage);
return 0;
}
int main(int argc, char *argv[]){
if(argc != 2){
std::cout << "Not enough parameters" << std::endl;
return -1;
}
std::string source = argv[1];
cv::VideoCapture cap(source);
if(!cap.isOpened())
return -1;
LaneDetector lanedetector;
cv::Mat frame;
cv::Mat img_denoise;
cv::Mat img_edges;
cv::Mat img_mask;
cv::Mat img_lines;
std::vector<cv::Vec4i> lines;
std::vector<std::vector<cv::Vec4i>> left_right_lines;
std::vector<cv::Point> lane;
std::string turn;
int flag_plot = -1;
int i = 0;
while(i < 540){
if(!cap.read(frame))
break;
img_denoise = lanedetector.deNoise(frame);
img_edges = lanedetector.edgeDetector(img_denoise);
img_mask = lanedetector.mask(img_edges);
lines = lanedetector.houghLines(img_mask);
if(!lines.empty()){
left_right_lines =
lanedetector.lineSeparation(lines, img_edges);
lane = lanedetector.regression(left_right_lines, frame);
turn = lanedetector.predicTurn();
flag_plot = lanedetector.plotLane(frame, lane, turn);
i += 1;
cv::waitKey(25);
} else{
flag_plot = -1;
}
}
return flag_plot;
}
| 24.365385 | 109 | 0.659169 | [
"vector"
] |
0072915f7c26fd96f9d8f4abbcd70890ff9a9fdd | 283,094 | cpp | C++ | src/tMSBE-v4.4/classVECSEL.cpp | sm321430/tMSBE-v4.0 | 8e4a36bb29379270deda6cc1bef7476d9018d9d1 | [
"Unlicense"
] | null | null | null | src/tMSBE-v4.4/classVECSEL.cpp | sm321430/tMSBE-v4.0 | 8e4a36bb29379270deda6cc1bef7476d9018d9d1 | [
"Unlicense"
] | null | null | null | src/tMSBE-v4.4/classVECSEL.cpp | sm321430/tMSBE-v4.0 | 8e4a36bb29379270deda6cc1bef7476d9018d9d1 | [
"Unlicense"
] | null | null | null |
/*
The VECSEL class is used to design the device
Can contain a series of devices from other classes
Solvers for MAXWELL and for each device
*/
#include "classVECSEL.h"
#include "constantsAndMiscUnits.h"
#include "fileIO.cpp"
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <sstream>
#include <unistd.h>
// For rounding
#include <string>
#include <math.h>
#include <iomanip>
#ifdef USE_THREADS
#include <vector>
#include <thread>
#include <algorithm>
#endif
#include <mpi.h>
#ifdef USE_OPENMP
#include <omp.h>
#endif
using namespace std;
/*
Construction function
*/
VECSEL::VECSEL()
{
cout << "Creating empty VECSEL" << endl;
setName("New VECSEL");
setToFileOutputKey("out_");
setLambda(0.0);
setNumberCavities(0);
setNumberTwoArmInterfaces(0);
setNumberBirefringentCrystals(0);
setNumberTwoArmCavities(0);
setNumberKerrCrystals(0);
setNumberDevices(0);
setNumberTwoArmDevices(0);
setNumberBoundaries(0);
VECSEL_transverse_points_number = -1;
VECSEL_transverse_points_device_number = -1;
VECSEL_transverse_points_R_max = 0.0;
VECSEL_transverse_points_boundary_guard_ratio = 0.78;
VECSEL_transverse_points_y = NULL;
VECSEL_transverse_points_device_y = NULL;
VECSEL_pulse_start_l = 0;
VECSEL_pulse_start_r = 0;
VECSEL_QW_FEEDBACK = 1.0;
VECSEL_initial_energy_shift = 0.0;
VECSEL_cav_snapshot_num_points = 0;
VECSEL_cav_snapshot_E = NULL;
VECSEL_cav_snapshot_E_re = NULL;
VECSEL_cav_snapshot_E_im = NULL;
VECSEL_initial_transverse_FWHM = 500.0*um;
VECSEL_initial_transverse_pulse_profile = NULL;
VECSEL_initial_temp_profile_T = NULL;
set_transverse_QW_pump_profile_SuperGaussian(13,2000.0*um); // Set initial SG pump profile
//set_transverse_QW_temp_profile_SuperGaussian(13,2000.0*um); // Set initial SG temp profile
cavity_trans_E_pl = NULL;
cavity_trans_E_mi = NULL;
cavity_trans_E_pl_k = NULL;
cavity_trans_E_mi_k = NULL;
cavity_trans_MacPol = NULL;
// MPI related arrays
MPI_MY_RANK = 0;
MPI_WORK_DIST = NULL; // size(MPI_WORK_DIST) = number_of_workers x 2. Contains start and stop index of work
MPI_WORK_DIST_E_OFFSET = NULL;
MPI_WORK_DIST_P_OFFSET = NULL;
MPI_WORK_DIST_E_SIZE = NULL;
MPI_WORK_DIST_P_SIZE = NULL;
MPI_WORK_DEVICE_SIZE = NULL;
MPI_WORK_DEVICE_OFFSET = NULL;
MPI_WORK_DIST_TOTAL = -1;
MPI_FLAG;
MPI_WORK_DIST_E_GLOBAL = NULL;
MPI_WORK_DIST_P_GLOBAL = NULL;
MPI_WORK_DIST_E_LOCAL = NULL;
MPI_WORK_DIST_P_LOCAL = NULL;
MPI_WORK_GANG = NULL;
MPI_WORK_GANG_SIZE = -1;
MPI_LoadBalancer = NULL;
MPI_LoadBalancer_index_set = NULL;
MPI_LoadBalancer_P_tmp = NULL;
MPI_LoadBalancer_E_tmp = NULL;
#ifdef MPI_BALANCE_WORKLOAD
MPI_load = NULL; // timer
#endif
test_VECSEL_iteration = 0;
init_VECSEL_iteration = 0;
filter_diagnostics_prev_E = 0.0;
}
void VECSEL::Print() const
{
cout << "Print VECSEL:" << endl;
cout << " name = " << getName() << endl;
cout << " filename = " << getToFileOutputKey() << endl;
cout << " lambda = " << getLambda() << endl;
cout << " # modules = " << getNumberModules() << endl;
cout << " # Boundaries = " << getNumberBoundaries() << endl;
cout << " # Devices = " << getNumberDevices() << endl;
cout << " # Cavities = " << getNumberCavities() << endl;
cout << " # TwoArmDevices = " << getNumberTwoArmDevices() << endl;
cout << " # TwoArmCavities = " << getNumberTwoArmCavities() << endl;
cout << " # BirefringentCrystal = " << getNumberBirefringentCrystals() << endl;
cout << " # TwoArmInterfaces = " << getNumberTwoArmInterfaces() << endl;
if (VECSEL_transverse_points_y!=NULL)
{
cout << " Transverse dimension = ";
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
cout << VECSEL_transverse_points_y[i]/um << " ";
}
cout << " [um]" << endl;
}
if (VECSEL_transverse_points_device_y != NULL)
{
cout << "Transverse device output points = ";
for(int i = 0; i < VECSEL_transverse_points_device_number; i++)
{
cout << VECSEL_transverse_points_device_y[i]/um << " ";
}
cout << " [um]" << endl;
}
cout << " Gain chip SG pump profile degree = " << VECSEL_initial_pump_profile_SG_degree << endl;
cout << " Gain chip SG pump profile FWHM = " << VECSEL_initial_pump_profile_SG_FWHM/um << " [um]" << endl;
cout << " Gain chip SG temp profile degree = " << VECSEL_initial_temp_profile_SG_degree << endl;
cout << " Gain chip SG temp profile FWHM = " << VECSEL_initial_temp_profile_SG_FWHM/um << " [um]" << endl;
for(int i = 0; i < getNumberModules(); i++)
{
if (modules[i].isDevice()||modules[i].isTwoArmDevice())
{
cout << "<------- DEVICE_PRINT() ------------" << endl;
} else {
modules[i].Print();
}
}
cout << "Cavity quick index:" << endl;
for(unsigned i = 0; i < quick_index_cavity.size(); i++)
{
cout << quick_index_cavity[i] << " ";
}
cout << endl;
cout << "Cavity quick index no BPM:" << endl;
for(unsigned i = 0; i < quick_index_cavity_noBPM.size(); i++)
{
cout << quick_index_cavity_noBPM[i] << " ";
}
cout << endl;
cout << "Cavity quick index free space:" << endl;
for(unsigned i = 0; i < quick_index_cavity_freeSpace.size(); i++)
{
cout << quick_index_cavity_freeSpace[i] << " ";
}
cout << endl;
cout << "Cavity quick index lens:" << endl;
for(unsigned i = 0; i < quick_index_cavity_lens.size(); i++)
{
cout << quick_index_cavity_lens[i] << " ";
}
cout << endl;
cout << "Cavity quick index halfCav lens:" << endl;
for(unsigned i = 0; i < quick_index_cavity_lens_halfCav.size(); i++)
{
cout << quick_index_cavity_lens_halfCav[i] << " ";
}
cout << endl;
cout << "Cavity quick index noQW:" << endl;
for(unsigned i = 0; i < quick_index_cavity_noQW.size(); i++)
{
cout << quick_index_cavity_noQW[i] << " ";
}
cout << endl;
cout << "Kerr lens crystal:" << endl;
for(unsigned i = 0; i < quick_index_kerrCrystal.size(); i++)
{
cout << quick_index_kerrCrystal[i] << " ";
}
cout << endl;
cout << "Cavity quick index w/QW:" << endl;
for(unsigned i = 0; i < quick_index_cavity_QW.size(); i++)
{
cout << quick_index_cavity_QW[i] << " ";
}
cout << endl;
cout << "Boundary quick index:" << endl;
for(unsigned i = 0; i < quick_index_boundary.size(); i++)
{
cout << quick_index_boundary[i] << " ";
}
cout << endl;
cout << "Total Device quick index:" << endl;
for(unsigned i = 0; i < quick_index_totalDevice.size(); i++)
{
cout << quick_index_totalDevice[i] << " ";
}
cout << endl;
cout << "Device quick index:" << endl;
for(unsigned i = 0; i < quick_index_device.size(); i++)
{
cout << quick_index_device[i] << " ";
}
cout << endl;
cout << "TwoArmCavity quick index:" << endl;
for(unsigned i = 0; i < quick_index_twoArmCavity.size(); i++)
{
cout << quick_index_twoArmCavity[i] << " ";
}
cout << endl;
cout << "TwoArmCavity quick index w/QW:" << endl;
for(unsigned i = 0; i < quick_index_twoArmCavity_QW.size(); i++)
{
cout << quick_index_twoArmCavity_QW[i] << " ";
}
cout << endl;
cout << "TwoArmCavity quick index noQW:" << endl;
for(unsigned i = 0; i < quick_index_twoArmCavity_noQW.size(); i++)
{
cout << quick_index_twoArmCavity_noQW[i] << " ";
}
cout << endl;
cout << "TwoArmCavity quik index birefringent crystals:" << endl;
for(unsigned i = 0; i < quick_index_birefringentCrystal.size(); i++)
{
cout << quick_index_birefringentCrystal[i] << " ";
}
cout << endl;
cout << "TwoArmDevice quick index:" << endl;
for(unsigned i = 0; i < quick_index_twoArmDevice.size(); i++)
{
cout << quick_index_twoArmDevice[i] << " ";
}
cout << endl;
cout << "TwoArmInterface quick index:" << endl;
for(unsigned i = 0; i < quick_index_twoArmInterface.size(); i++)
{
cout << quick_index_twoArmInterface[i] << " ";
}
cout << endl;
cout << "TwoArmPostCav quick index:" << endl;
for(unsigned i = 0; i < quick_index_twoArmPostCav.size(); i++)
{
cout << quick_index_twoArmPostCav[i] << " ";
}
cout << endl;
cout << "Device prev cavity quick index:" << endl;
for(unsigned i = 0; i < quick_index_totalDevice.size(); i++)
{
cout << quick_index_device_previous_cavity[i] << " ";
}
cout << endl;
}
/*
n1 / n2 -> Refractive indices in medium
nNext -> Refractive indices in the next layer AFTER the DBR (To ensure ordering)
numLayers -> Number of layers in the DBR
angle_of_incidence -> Angle in radians for TE
external_index -> Index in incoming medium
*/
void VECSEL::addDBR_LEFT(double n1, double n2, int numLayers, double nNext, double angle_of_incidence, double external_index)
{
double N_SUBSTRATE = n1;
if (n2 > n1)
{
N_SUBSTRATE = n2;
}
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
n1 = n1*sqrt(1.0-a_sin2/(n1*n1));
n2 = n2*sqrt(1.0-a_sin2/(n2*n2));
nNext = nNext*sqrt(1.0-a_sin2/(nNext*nNext));
if (n1 == n2)
{
cout << "addDBR_LEFT: Refractive indices are equal, not funny..." << endl;
exit(-1);
} else if ((n1 <= 0.0)||(n2 <= 0.0)||(nNext <= 0.0))
{
cout << "addDBR_LEFT: Refractive indices have to be strictly positive" << endl;
exit(-1);
}
if (numLayers < 0)
{
cout << "addDBR_LEFT: Have to use a positive number of layers" << endl;
exit(-1);
}
// Get starting position
int startPos = getNumberModules();
if (startPos == 0)
{
// Add boundary to first element
if (numLayers == 0)
{
cout << "addDBR_LEFT: Adding REFLECTING boundary on the left" << endl;
addBoundary(1.0,N_SUBSTRATE);
} else {
cout << "addDBR_LEFT: Adding ABSORBING boundary on the left" << endl;
addBoundary(0.0,N_SUBSTRATE);
}
} else if (startPos == 1)
{
// Starting on the left
// Check if previous was Boundary
if (!modules[0].isBoundary())
{
cout << "addDBR_LEFT: 1st module has to be a BOUNDARY..." << endl;
exit(-1);
}
}
// Ensure alternating reflectors
double n_bragg[2] = {0,0};
if (numLayers % 2 == 0)
{
// Pair number of layers
if (n2 == nNext)
{
// Reverse ordering
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
} else {
// Odd number of layers
if (n1 == nNext)
{
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
}
Module *tmp;
// Create numLayers cavities of length lambda/4/n_bragg[j]
double deviceWidth = 0;
for(int i = 0; i < numLayers; i++)
{
deviceWidth = getLambda()/(4.0*n_bragg[i%2]);
tmp = addCavity(deviceWidth, n_bragg[i%2], angle_of_incidence, external_index);
}
}
void VECSEL::addDBR_LEFT_nL(double n1, double L1, double n2, double L2, int numLayers, double angle_of_incidence, double external_index)
{
double N_SUBSTRATE = n1;
if (n2 > n1)
{
N_SUBSTRATE = n2;
}
if (n1 == n2)
{
cout << "addDBR_LEFT: Refractive indices are equal, not funny..." << endl;
exit(-1);
} else if ((n1 <= 0.0)||(n2 <= 0.0))
{
cout << "addDBR_LEFT: Refractive indices have to be strictly positive" << endl;
exit(-1);
}
if (numLayers < 0)
{
cout << "addDBR_LEFT: Have to use a positive number of layers" << endl;
exit(-1);
}
// Get starting position
int startPos = getNumberModules();
if (startPos == 0)
{
// Add boundary to first element
if (numLayers == 0)
{
cout << "addDBR_LEFT: Adding REFLECTING boundary on the left" << endl;
addBoundary(1.0,N_SUBSTRATE);
} else {
cout << "addDBR_LEFT: Adding ABSORBING boundary on the left" << endl;
addBoundary(0.0,N_SUBSTRATE);
}
} else if (startPos == 1)
{
// Starting on the left
// Check if previous was Boundary
if (!modules[0].isBoundary())
{
cout << "addDBR_LEFT: 1st module has to be a BOUNDARY..." << endl;
exit(-1);
}
}
// Ensure alternating reflectors
double n_bragg[2] = {n1,n2};
double L_bragg[2] = {L1,L2};
Module *tmp;
// Create numLayers cavities of length lambda/4/n_bragg[j]
double deviceWidth = 0;
for(int i = 0; i < numLayers; i++)
{
tmp = addCavity(L_bragg[i%2], n_bragg[i%2], angle_of_incidence, external_index);
}
}
// Based on the design idea by: Zhang. et al in Opt Quant Electron 2015 47:423-431
// Equations can be found in Calvez 2002 Photonics tech lett vol 14
// Make repetitions of ((n1n2)^D n1)^N where D and lambda0 are both solutions of an equation
void VECSEL::addDBM_LEFT(double n1, double n2, double nNext, int D, int N, double lambda0, double angle_of_incidence, double external_index)
{
double N_SUBSTRATE = n1;
if (n2 > n1)
{
N_SUBSTRATE = n2;
}
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
n1 = n1*sqrt(1.0-a_sin2/(n1*n1));
n2 = n2*sqrt(1.0-a_sin2/(n2*n2));
if (n1 == n2)
{
cout << "addDBR_LEFT: Refractive indices are equal, not funny..." << endl;
exit(-1);
} else if ((n1 <= 0.0)||(n2 <= 0.0))
{
cout << "addDBR_LEFT: Refractive indices have to be strictly positive" << endl;
exit(-1);
}
if ((N <= 0)||(D<=0))
{
cout << "addDBR_LEFT: Have to use a positive number of layers" << endl;
exit(-1);
}
// Get starting position
int startPos = getNumberModules();
if (startPos == 0)
{
// Add boundary to first element
cout << "addDBR_LEFT: Adding ABSORBING boundary on the left" << endl;
addBoundary(0.0,N_SUBSTRATE);
} else if (startPos == 1)
{
// Starting on the left
// Check if previous was Boundary
if (!modules[0].isBoundary())
{
cout << "addDBR_LEFT: 1st module has to be a BOUNDARY..." << endl;
exit(-1);
}
}
// Ensure alternating reflectors
double n_bragg[2] = {0,0};
if (n1 == nNext)
{
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
Module *tmp;
// Create numLayers cavities of length lambda/4/n_bragg[j]
double deviceWidth = 0;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < D; j++)
{
deviceWidth = lambda0/(4.0*n_bragg[0]);
tmp = addCavity(deviceWidth, n_bragg[0]);
deviceWidth = lambda0/(4.0*n_bragg[1]);
tmp = addCavity(deviceWidth, n_bragg[1]);
}
deviceWidth = lambda0/(4.0*n_bragg[0]);
tmp = addCavity(deviceWidth, n_bragg[0]);
}
}
/*
lambda -> Target lambda for DBR
n1 / n2 -> Refractive indices in medium
nNext -> Refractive indices in the next layer AFTER the DBR (To ensure ordering)
numLayers -> Number of layers in the DBR
*/
void VECSEL::addDBR_LEFT_LAMBDA(double lambda, double n1, double n2, int numLayers, double nNext)
{
double N_SUBSTRATE = n1;
if (n2 > n1)
{
N_SUBSTRATE = n2;
}
if (n1 == n2)
{
cout << "addDBR_LEFT: Refractive indices are equal, not funny..." << endl;
exit(-1);
} else if ((n1 <= 0.0)||(n2 <= 0.0)||(nNext <= 0.0))
{
cout << "addDBR_LEFT: Refractive indices have to be strictly positive" << endl;
exit(-1);
}
if (numLayers < 0)
{
cout << "addDBR_LEFT: Have to use a positive number of layers" << endl;
exit(-1);
}
// Get starting position
int startPos = getNumberModules();
if (startPos == 0)
{
// Add boundary to first element
if (numLayers == 0)
{
cout << "addDBR_LEFT: Adding REFLECTING boundary on the left" << endl;
addBoundary(1.0,N_SUBSTRATE);
} else {
cout << "addDBR_LEFT: Adding ABSORBING boundary on the left" << endl;
addBoundary(0.0,N_SUBSTRATE);
}
} else if (startPos == 1)
{
// Starting on the left
// Check if previous was Boundary
if (!modules[0].isBoundary())
{
cout << "addDBR_LEFT: 1st module has to be a BOUNDARY..." << endl;
exit(-1);
}
}
// Ensure alternating reflectors
double n_bragg[2] = {0,0};
if (numLayers % 2 == 0)
{
// Pair number of layers
if (n2 == nNext)
{
// Reverse ordering
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
} else {
// Odd number of layers
if (n1 == nNext)
{
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
}
Module *tmp;
// Create numLayers cavities of length lambda/4/n_bragg[j]
double deviceWidth = 0;
for(int i = 0; i < numLayers; i++)
{
deviceWidth = lambda/(4.0*n_bragg[i%2]);
tmp = addCavity(deviceWidth, n_bragg[i%2]);
}
}
/*
Add in a DBR design for lambda_pump, that has a total length of lambda/4.
The order of the layers is determined by nNext and n1,n2.
- default order is with: n1, n2, n1, ..., n2, n1, with numLayers
unless n1 == nNext or n2 == nNext, then the final layer is different
tune - determines the amount of extra layer on the left / right.
- tune = 0 => all on the left
- tune = 1 => all on the right
*/
void VECSEL::addDBR_LEFT_PUMP(double lambda, double lambda_pump, double n1, double n2, int numLayers, double nTune, double nNext, double tune)
{
double N_SUBSTRATE = n1;
if (n2 > n1)
{
N_SUBSTRATE = n2;
}
if ((tune < 0.0)||(tune > 1.0))
{
cout << "addDBR_LEFT_PUMP: Tune has to be in the rage [0,1]" << endl;
exit(-1);
}
if (n1 == n2)
{
cout << "addDBR_LEFT_PUMP: Refractive indices are equal, not funny..." << endl;
exit(-1);
} else if ((n1 <= 0.0)||(n2 <= 0.0)||(nNext <= 0.0))
{
cout << "addDBR_LEFT_PUMP: Refractive indices have to be strictly positive" << endl;
exit(-1);
}
if (numLayers < 0)
{
cout << "addDBR_LEFT_PUMP: Have to use a positive number of layers" << endl;
exit(-1);
}
// Get starting position
int startPos = getNumberModules();
if (startPos == 0)
{
// Add boundary to first element
if (numLayers == 0)
{
cout << "addDBR_LEFT_PUMP: Adding REFLECTING boundary on the left" << endl;
addBoundary(1.0,N_SUBSTRATE);
} else {
cout << "addDBR_LEFT_PUMP: Adding ABSORBING boundary on the left" << endl;
addBoundary(0.0,N_SUBSTRATE);
}
} else if (startPos == 1)
{
// Starting on the left
// Check if previous was Boundary
if (!modules[0].isBoundary())
{
cout << "addDBR_LEFT_PUMP: 1st module has to be a BOUNDARY..." << endl;
exit(-1);
}
}
// Ensure alternating reflectors
double n_bragg[2] = {0,0};
if (numLayers % 2 == 0)
{
// Pair number of layers
if (n2 == nNext)
{
// Reverse ordering
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
} else {
// Odd number of layers
if (n1 == nNext)
{
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
}
//======================================
// Adding in extra layer for stability
//======================================
double total_pump_length = lambda/4.0;
double MIN_LAYER_SIZE = 20*nm;
double diff_length = 0;
for(unsigned i = 0; i < numLayers; i++)
{
diff_length += lambda_pump/(4.0*n_bragg[i%2]);
}
int mult = floor(diff_length/total_pump_length);
if (mult == 0)
{
cout << "addDBR_LEFT_PUMP: Number of layers is too few for lambda/4 " << endl;
}
double res = diff_length - ((double)mult)*total_pump_length; // Residual
Module *tmp;
// Add in residual layer
if (tune < 1)
{
if (MIN_LAYER_SIZE > res*(1.0-tune))
{
cout << "addDBR_LEFT_PUMP: Extra cavity (first) is smaller than LIMIT of " << MIN_LAYER_SIZE/nm << " [nm]" << endl;
exit(-1);
}
tmp = addCavity(res*(1.0-tune), nTune);
cout << "addDBR_LEFT_PUMP: Extra cavity (first) added of length = " << res*(1-tune)/nm << " [nm]" << endl;
}
// Create numLayers cavities of length lambda/4/n_bragg[j]
double deviceWidth = 0;
for(int i = 0; i < numLayers; i++)
{
deviceWidth = lambda_pump/(4.0*n_bragg[i%2]);
tmp = addCavity(deviceWidth, n_bragg[i%2]);
}
// Add last residual layer
if (tune > 0)
{
if (MIN_LAYER_SIZE > res*tune)
{
cout << "addDBR_LEFT_PUMP: Extra cavity (last ) is smaller than LIMIT of " << MIN_LAYER_SIZE/nm << " [nm]" << endl;
exit(-1);
}
tmp = addCavity(res*tune, nTune);
cout << "addDBR_LEFT_PUMP: Extra cavity (last ) added of length = " << res*tune/nm << " [nm]" << endl;
}
}
/*
n1 / n2 -> Refractive indices in medium
nPrev -> Refractive indices in the previous layer BEFORE the DBR (To ensure ordering)
numLayers -> Number of layers in the DBR
*/
void VECSEL::addDBR_RIGHT(double n1, double n2, int numLayers, double nPrev)
{
if (n1 == n2)
{
cout << "addDBR_RIGHT: Refractive indices are equal, not funny..." << endl;
exit(-1);
} else if ((n1 <= 0.0)||(n2 <= 0.0)||(nPrev <= 0.0))
{
cout << "addDBR_RIGHT: Refractive indices have to be strictly positive" << endl;
exit(-1);
}
if (numLayers < 0)
{
cout << "addDBR_RIGHT: Have to use a positive number of layers" << endl;
exit(-1);
}
int startInd = getNumberModules();
if ((startInd == 0)||(startInd == 1))
{
// Should use addDBR_LEFT
cout << "addDBR_RIGHT: Use addDBR_RIGHT when starting on the left?" << endl;
exit(-1);
}
// Ensure alternating reflectors
double n_bragg[2] = {0,0};
if (n1 == nPrev)
{
// cout << "1: " << n1 << " == " << nPrev << endl;
// cout << "First is = " << n2 << endl;
// Reverse ordering
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
// cout << "2: " << n1 << " != " << nPrev << endl;
// cout << "First is = " << n1 << endl;
n_bragg[0] = n1;
n_bragg[1] = n2;
}
Module *tmp;
// Create numLayers cavities of length lambda/4/n_bragg[j]
double deviceWidth = 0;
for(int i = 0; i < numLayers; i++)
{
deviceWidth = getLambda()/(4.0*n_bragg[i%2]);
tmp = addCavity(deviceWidth, n_bragg[i%2]);
}
}
/*
n1 / n2 -> Refractive indices in medium
nNext -> Refractive indices in the next layer AFTER the DBR (To ensure ordering)
numLayers -> Number of layers in the DBR
angle_of_incidence -> Angle in radians for TE
external_index -> Index in incoming medium
*/
void VECSEL::addTwoArmDBR_FRONT(double n1, double n2, int numLayers, double nBack, double angle_of_incidence, double external_index)
{
double N_SUBSTRATE = n1;
if (n2 > n1)
{
N_SUBSTRATE = n2;
}
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
double intIndex = nBack;
n1 = n1*sqrt(1.0-a_sin2/(n1*n1));
n2 = n2*sqrt(1.0-a_sin2/(n2*n2));
nBack = nBack*sqrt(1.0-a_sin2/(nBack*nBack));
if (n1 == n2)
{
cout << "addTwoArmDBR_FRONT: Refractive indices are equal, not funny...but letting it slide " << endl;
//exit(-1);
} else if ((n1 <= 0.0)||(n2 <= 0.0)||(nBack <= 0.0))
{
cout << "addTwoArmDBR_FRONT: Refractive indices have to be strictly positive" << endl;
exit(-1);
}
if (numLayers < 0)
{
cout << "addTwoArmDBR_FRONT: Have to use a positive number of layers" << endl;
exit(-1);
}
// Get starting position
int startPos = getNumberModules();
Module *tmp;
if (startPos == 0)
{
// Add boundary to first element
if (numLayers == 0)
{
cout << "addTwoArmDBR_FRONT: Adding REFLECTING boundary on the left" << endl;
addBoundary(1.0,N_SUBSTRATE);
} else {
cout << "addTwoArmDBR_FRONT: Adding ABSORBING boundary on the left" << endl;
addBoundary(0.0,N_SUBSTRATE);
}
}
if (modules[startPos-1].isCavity())
{
tmp = addTwoArmInterface(1.0, angle_of_incidence, 1.0, intIndex);
}
// Ensure alternating reflectors
double n_bragg[2] = {0,0};
if (numLayers % 2 == 0)
{
// Even number of layers
if (n2 == nBack)
{
n_bragg[0] = n1;
n_bragg[1] = n2;
} else {
n_bragg[0] = n2;
n_bragg[1] = n1;
}
} else {
// Odd number of layers
if (n1 == nBack)
{
n_bragg[0] = n2;
n_bragg[1] = n1;
} else {
n_bragg[0] = n1;
n_bragg[1] = n2;
}
}
// Create numLayers cavities of length lambda/4/n_bragg[j]
double deviceWidth = 0;
for(int i = 0; i < numLayers; i++)
{
deviceWidth = getLambda()/(4.0*n_bragg[i%2]);
tmp = addTwoArmCavity(deviceWidth, n_bragg[i%2], angle_of_incidence, external_index);
}
}
/*
* Create a gain medium on the left with QW.
*
* |---o-o-o-o-o-------------|--CAP--|--AR--|
*
* . If there is nothing on the left of this, a boundary is added
*
* Where:
* numQW -> Number of QW's in the medium [0,inf)
* - If numQW = 0 => Empty medium of length cavityLength
* dx0_qw -> Distance from LEFTMOST QW's to the edge in units of WHOLE PEAKS
* dx1_qw -> Distance from RIGHTMOST QW's to right edge in units of WHOLE PEAKS
* cavityIndex -> Refractive background index in medium
* capIndex -> Refractive index of CAP layer, if capIndex = 0 then NO CAP layer
* arIndex -> Refractive index of AR coating, if arIndex = 0 then NO ar coating
* fillerLength -> Length of cavity to fill in AFTER AR and CAP layer in units of m
* angle_of_incidence -> Angle in radians for TE
* external_index -> Index in incoming medium
* */
void VECSEL::addCUSTOM_CLUSTER_QW_LEFT(int numClusters, int *clusterQW, int dx0_qw, double dx1_qw, double cavityIndex, double capIndex, double arIndex, double angle_of_incidence, double external_index)
{
// Distance between QW that are clustered
//double BARRIER_LENGTH = 16.35*nm;
//double BARRIER_LENGTH = 13.0*nm;
double BARRIER_LENGTH = 10.0*nm;
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
int numQW = 0;
for(unsigned i = 0; i < numClusters; i++)
{
numQW += clusterQW[i];
if (clusterQW[i] < 0)
{
cout << "addCUSTOM_CLUSTER_QW_LEFT(): Cannot have NEGATIVE number of QW's" << endl;
exit(-1);
}
if ((clusterQW[i]-1)*BARRIER_LENGTH + BARRIER_LENGTH > getLambda()*0.5/cavityIndex)
{
cout << "addCUSTOM_CLUSTER_QW_LEFT(): Too many QW's in a node" << endl;
cout << "Num QW's = " << clusterQW[i] << endl;
exit(-1);
}
}
if (numClusters > 0)
{
if ((clusterQW[0] == 0)||(clusterQW[numClusters-1] == 0))
{
cout << "addCUSTOM_CLUSTER_QW_LEFT(): First and/or last element of clusterQW[-] cannot be zero" << endl;
exit(-1);
}
}
// Check the input for consistencty
if (dx0_qw < 0) {
cout << "addCUSTOM_CLUSTER_QW_LEFT(): dx0_qw < 0, quitting" << endl;
exit(-1);
} else if (dx1_qw < 0) {
cout << "addCUSTOM_CLUSTER_QW_LEFT(): dx1_qw <= 0, quitting" << endl;
exit(-1);
} else if (numQW < 0) {
cout << "addCUSTOM_CLUSTER_QW_LEFT(): numQW < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addCUSTOM_CLUSTER_QW_LEFT: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if (((numQW == 0)&&(dx0_qw== 0))&&(dx1_qw == 0))
{
cout << "addCUSTOM_CLUSTER_QW_LEFT(): No QW's and NO empty nodes, refusing to make empty gain region" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
double QW_START = 0;
double EXTRA_PADDING = 0.5;
// Count number of empty peaks before first QW
for(unsigned i = 0; i < numClusters; i++)
{
if (clusterQW[i] == 0)
{
EXTRA_PADDING += 0.5;
} else {
// Find distance to first peak
QW_START = BARRIER_LENGTH*(clusterQW[i]-1)/2;
break;
}
}
tmpWidth = getLambda()*(dx0_qw*0.5 + EXTRA_PADDING)/cavityIndex - QW_START;
tmp = addCavity(tmpWidth, cavityIndex);
double QW_MID1 = QW_START; // Distance from last QW to node
double QW_MID2 = 0; // Distance from node to first QW
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
if (dx1_qw > 0)
{
tmpWidth = getLambda()*(dx1_qw)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
}
} else {
// CASE 2: numQW > 0
int QW_NUM = 1;
// Plan structure
for(int i = 0; i < numClusters; i++)
{
if (clusterQW[i] > 0)
{
EXTRA_PADDING = 0.0;
for(unsigned j = 0; j < clusterQW[i]; j++)
{
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << QW_NUM;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
// Add cavity of length
if (j < clusterQW[i]-1)
{
tmp = addCavity(BARRIER_LENGTH, cavityIndex);
}
QW_NUM += 1;
}
QW_MID1 = getLambda()*0.25/cavityIndex - BARRIER_LENGTH*(clusterQW[i]-1)/2;
if (i < numClusters-1)
{
int kk = i+1;
while (clusterQW[kk] == 0)
{
EXTRA_PADDING += 0.5;
kk++;
}
QW_MID2 = getLambda()*0.25/cavityIndex - BARRIER_LENGTH*(clusterQW[kk]-1)/2;
tmp = addCavity(getLambda()*EXTRA_PADDING/cavityIndex + QW_MID1 + QW_MID2, cavityIndex);
}
} else {
//
}
}
// Add last layer
tmpWidth = getLambda()*(dx1_qw*0.5)/cavityIndex + QW_MID1;
tmp = addCavity(tmpWidth, cavityIndex);
}
// Add CAP layer
/*
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addCavity(tmpWidth, capIndex);
tmp->getCavity()->setName("Cap");
}
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (getLambda()/4.0)/arIndex;
tmp = addCavity(tmpWidth, arIndex);
tmp->getCavity()->setName("Ar");
}
*/
tmpWidth = 0.503490*getLambda()/3.1778;
tmp = addCavity(tmpWidth, 3.1778);
tmp->getCavity()->setName("Cap");
tmpWidth = 0.190713*getLambda()/2.0781;
tmp = addCavity(tmpWidth, 2.0781);
tmp->getCavity()->setName("Ta2O5");
tmpWidth = 0.111396*getLambda()/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("SiO2");
/*
tmpWidth = 0.117717*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.351447*(getLambda())/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("AR AlGaAs");
tmpWidth = 0.183256*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.099180*(getLambda())/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("AR AlGaAs");
tmpWidth = 0.322405*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.217130*(getLambda())/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("AR AlGaAs");
tmpWidth = 0.219079*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.080894*(getLambda())/3.195400;
tmp = addCavity(tmpWidth, 3.195400);
tmp->getCavity()->setName("CAP");
tmpWidth = 0.253982*(getLambda())/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("AR - SiN");
*/
}
// Special clustering of QWs where two are centered near the peak of the antinode and two are on the wings
void VECSEL::addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(int numClusters, int *clusterQW, bool USE_BOOSTER, int dx0_qw, double dx1_qw, double cavityIndex, double capIndex, double arIndex, double angle_of_incidence, double external_index)
{
// Distance between QW that are clustered
//double BARRIER_LENGTH = 16.35*nm;
//double BARRIER_LENGTH = 13.0*nm;
double BARRIER_LENGTH_CENTER = 16.35*nm;
double BARRIER_LENGTH_WINGS = 24.0*nm;
double booster_layer_space = 16.35*nm;
// Length of region that has to be centered on the antinode
double qw_span = BARRIER_LENGTH_CENTER + 2.0*BARRIER_LENGTH_WINGS;
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
int numQW = 0;
for(unsigned i = 0; i < numClusters; i++)
{
numQW += clusterQW[i];
if (clusterQW[i] < 0)
{
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): Cannot have NEGATIVE number of QW's" << endl;
exit(-1);
}
if (BARRIER_LENGTH_CENTER + 2.0*BARRIER_LENGTH_WINGS > getLambda()*0.5/cavityIndex)
{
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): Too much space for antinode" << endl;
cout << "BARRIER_CENTER = " << BARRIER_LENGTH_CENTER/nm << " [nm]" << endl;
cout << "BARRIER_WINGS = " << BARRIER_LENGTH_WINGS/nm << " [nm]" << endl;
exit(-1);
}
if (clusterQW[i]>4)
{
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): Need 4 QWs per antinode. No more. No less." << endl;
cout << "clusterQW[i] = " << clusterQW[i] << endl;
exit(-1);
} else if (clusterQW[i]==1) {
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): Need 4 QWs per antinode. No more. No less." << endl;
cout << "clusterQW[i] = " << clusterQW[i] << endl;
exit(-1);
} else if (clusterQW[i]==2) {
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): Need 4 QWs per antinode. No more. No less." << endl;
cout << "clusterQW[i] = " << clusterQW[i] << endl;
exit(-1);
} else if (clusterQW[i]==3) {
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): Need 4 QWs per antinode. No more. No less." << endl;
cout << "clusterQW[i] = " << clusterQW[i] << endl;
exit(-1);
}
}
if (numClusters > 0)
{
if ((clusterQW[0] == 0)||(clusterQW[numClusters-1] == 0))
{
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): First and/or last element of clusterQW[-] cannot be zero" << endl;
exit(-1);
}
}
// Check the input for consistencty
if (dx0_qw < 0) {
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): dx0_qw < 0, quitting" << endl;
exit(-1);
} else if (dx1_qw < 0) {
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): dx1_qw <= 0, quitting" << endl;
exit(-1);
} else if (numQW < 0) {
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): numQW < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if (((numQW == 0)&&(dx0_qw== 0))&&(dx1_qw == 0))
{
cout << "addCUSTOM_CLUSTER_121_BOOSTER_QW_LEFT(): No QW's and NO empty nodes, refusing to make empty gain region" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
double QW_START = 0;
double EXTRA_PADDING = 0.5;
// Count number of empty peaks before first QW
for(unsigned i = 0; i < numClusters; i++)
{
if (clusterQW[i] == 0)
{
EXTRA_PADDING += 0.5;
} else {
// Find distance to first peak
QW_START = qw_span/2.0;
break;
}
}
if (USE_BOOSTER) // == true
{
tmp = addCavity(booster_layer_space, cavityIndex);
// Include BOOSTER QW near DBR
tmp = addDevice();
tmpName.str("");
tmpName << "QW1";
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
tmpWidth = getLambda()*(dx0_qw*0.5 + EXTRA_PADDING)/cavityIndex - QW_START - booster_layer_space;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
tmpWidth = getLambda()*(dx0_qw*0.5 + EXTRA_PADDING)/cavityIndex - QW_START;
tmp = addCavity(tmpWidth, cavityIndex);
}
double QW_MID1 = QW_START; // Distance from last QW to node
double QW_MID2 = 0; // Distance from node to first QW
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
if (dx1_qw > 0)
{
tmpWidth = getLambda()*(dx1_qw)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
}
} else {
// CASE 2: numQW > 0
int QW_NUM = 1;
if (USE_BOOSTER) // == true
{
QW_NUM = 2;
}
// Plan structure
for(int i = 0; i < numClusters; i++)
{
if (clusterQW[i] > 0)
{
EXTRA_PADDING = 0.0;
if (clusterQW[i]==4)
{
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << QW_NUM;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
QW_NUM += 1;
tmp = addCavity(BARRIER_LENGTH_WINGS, cavityIndex);
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << QW_NUM;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
QW_NUM += 1;
tmp = addCavity(BARRIER_LENGTH_CENTER, cavityIndex);
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << QW_NUM;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
QW_NUM += 1;
tmp = addCavity(BARRIER_LENGTH_WINGS, cavityIndex);
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << QW_NUM;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
QW_NUM += 1;
}
QW_MID1 = getLambda()*0.25/cavityIndex - qw_span/2.0;
if (i < numClusters-1)
{
int kk = i+1;
while (clusterQW[kk] == 0)
{
EXTRA_PADDING += 0.5;
kk++;
}
QW_MID2 = getLambda()*0.25/cavityIndex - qw_span/2.0;
tmp = addCavity(getLambda()*EXTRA_PADDING/cavityIndex + QW_MID1 + QW_MID2, cavityIndex);
}
} else {
//
}
}
// Add last layer
tmpWidth = getLambda()*(dx1_qw*0.5)/cavityIndex + QW_MID1;
tmp = addCavity(tmpWidth, cavityIndex);
}
/*
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addCavity(tmpWidth, capIndex);
tmp->getCavity()->setName("Cap");
}
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (getLambda()/4.0)/arIndex;
tmp = addCavity(tmpWidth, arIndex);
tmp->getCavity()->setName("Ar");
}
*/
tmpWidth = 0.486678*getLambda()/3.1778;
tmp = addCavity(tmpWidth, 3.1778);
tmp->getCavity()->setName("Cap");
tmpWidth = 0.175184*getLambda()/2.0781;
tmp = addCavity(tmpWidth, 2.0781);
tmp->getCavity()->setName("Ar Perfect");
tmpWidth = 0.143084*getLambda()/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("Ar Perfect");
/*
tmpWidth = 0.117717*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.351447*(getLambda())/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("AR AlGaAs");
tmpWidth = 0.183256*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.099180*(getLambda())/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("AR AlGaAs");
tmpWidth = 0.322405*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.217130*(getLambda())/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("AR AlGaAs");
tmpWidth = 0.219079*(getLambda())/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar AlAs");
tmpWidth = 0.080894*(getLambda())/3.195400;
tmp = addCavity(tmpWidth, 3.195400);
tmp->getCavity()->setName("CAP");
tmpWidth = 0.253982*(getLambda())/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("AR - SiN");
*/
}
/*
* Create a gain medium on the left with QW.
*
* |---o-o-o-o-o-------------|--CAP--|--AR--|
*
* . If there is nothing on the left of this, a boundary is added
*
* Where:
* numQW -> Number of QW's in the medium [0,inf)
* - If numQW = 0 => Empty medium of length cavityLength
* dx0_qw -> Distance from LEFTMOST QW to the edge in units of m
* dx_qw -> Distance between each QW in units of m
* cavityLength -> Total length of cavity (not including AR and CAP)
* - If cavityLength = 0 => Fit cavity tight on QW's (If numQW = 0 => ERROR)
* - If cavityLength < space for QW with spacing => ERROR
* cavityIndex -> Refractive background index in medium
* capIndex -> Refractive index of CAP layer, if capIndex = 0 then NO CAP layer
* arIndex -> Refractive index of AR coating, if arIndex = 0 then NO ar coating
* fillerLength -> Length of cavity to fill in AFTER AR and CAP layer in units of m
* */
void VECSEL::addCUSTOM_QW_LEFT_OPTIMAL_ANGLE(int numQW, double *width, double cavityLength, double cavityIndex, double capIndex, double arIndex, double arLength,bool PASSIVE_STRUCTURE,double BAD_GROWTH_FACTOR,double BAD_GROWTH_FACTOR_CAP, double angle_of_incidence, double external_index, double ar_temperature_index_diff)
{
double BARRIER = 5*nm;
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addCUSTOM_QW_LEFT(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (numQW < 0) {
cout << "addCUSTOM_QW_LEFT(): numQW < 0, quitting" << endl;
exit(-1);
}
for(unsigned i = 0; i < numQW; i++)
{
if (width[i] <=0.0)
{
cout << "addCUSTOM_QW_LEFT(): width[i] <= 0" << endl;
exit(-1);
} else if (width[i] < BARRIER)
{
cout << "addCUSTOM_QW_LEFT(): width[i] < min BARRIER length" << endl;
exit(-1);
}
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength == 0))
{
cout << "addCUSTOM_QW_LEFT(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addCUSTOM_QW_LEFT: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = cavityLength;
tmp = addCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else {
// CASE 2: numQW > 0
// First cavity
tmpWidth = BAD_GROWTH_FACTOR*width[0];
tmp = addCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
// Add first device
tmp = addDevice();
if (PASSIVE_STRUCTURE)
{
tmp->getDevice()->setName("QW1_PASSIVE");
} else {
tmp->getDevice()->setName("QW1");
}
tmp->setOutputToFile(1);
double totalWidth = BAD_GROWTH_FACTOR*width[0];
// Add rest in dx_qw distance
for(int i = 1; i < numQW; i++)
{
// Add Cavity
totalWidth += BAD_GROWTH_FACTOR*width[i];
tmp = addCavity(BAD_GROWTH_FACTOR*width[i], cavityIndex, angle_of_incidence, external_index);
// Add device
tmp = addDevice();
if (PASSIVE_STRUCTURE)
{
tmp->getDevice()->setName("QW1_PASSIVE");
} else {
tmpName.str("");
tmpName << "QW" << i+1;
tmp->getDevice()->setName(tmpName.str());
}
tmp->setOutputToFile(1);
}
if (cavityLength > 0)
{
// Add rest of Cavity
tmpWidth = BAD_GROWTH_FACTOR*(cavityLength - totalWidth);
tmp = addCavity( tmpWidth , cavityIndex, angle_of_incidence, external_index);
} else {
// Add final barrier
//tmpWidth = BARRIER;
tmp = addCavity( BAD_GROWTH_FACTOR*width[numQW] , cavityIndex, angle_of_incidence, external_index);
}
}
/*
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = BAD_GROWTH_FACTOR_CAP*(getLambda()/2.0)/capIndex;
//tmpWidth = BAD_GROWTH_FACTOR*(980*nm/2.0)/capIndex;
tmp = addCavity(tmpWidth, capIndex, angle_of_incidence, external_index);
tmp->getCavity()->setName("Cap");
}
// Add AR coating
if (arIndex > 0)
{
//tmpWidth = BAD_GROWTH_FACTOR_AR*(getLambda()/4.0)/arIndex;
//tmpWidth = BAD_GROWTH_FACTOR_AR*(140.0*nm); // Target length = 140*nm, Alex estimates width = 125*nm
tmp = addCavity(arLength, arIndex, angle_of_incidence, external_index);
tmp->getCavity()->setName("Ar");
}
*/
double n_AlGaAs = 3.4583 +ar_temperature_index_diff;
double n_AlAs = 2.9601 +ar_temperature_index_diff;
double n_cap = 3.1778 +ar_temperature_index_diff;
double n_si02 = 1.4708; // Lemarchand 2013
// CAP
tmpWidth = 128.96*nm; // 127.38
tmp = addCavity(tmpWidth, 3.1978, angle_of_incidence, external_index);
tmp->getCavity()->setName("CAP");
// AR 2
tmpWidth = 87.88*nm; // 87.77nm
tmp = addCavity(tmpWidth, 1.9826, angle_of_incidence, external_index);
tmp->getCavity()->setName("Ar");
// AR 2
tmpWidth = 118.98*nm; // 119.23nm
tmp = addCavity(tmpWidth, 1.477, angle_of_incidence, external_index);
tmp->getCavity()->setName("Ar");
/*
// CAP
tmpWidth = 0.273099*getLambda()/3.1978;
tmp = addCavity(tmpWidth, 3.1978, angle_of_incidence, external_index);
tmp->getCavity()->setName("CAP");
// AR 2
tmpWidth = 0.117960*getLambda()/1.9826;
tmp = addCavity(tmpWidth, 1.9826, angle_of_incidence, external_index);
tmp->getCavity()->setName("Ar");
// AR 2
tmpWidth = 0.206474*getLambda()/1.477;
tmp = addCavity(tmpWidth, 1.477, angle_of_incidence, external_index);
tmp->getCavity()->setName("Ar");
*/
//====================================================================
// Add in angle dependence for ALL previous layers (DBR/gold/...)
// First cavity
std::complex<double> n_curr = modules[quick_index_cavity[quick_index_cavity.size()-1]].getRefInd() + I*modules[quick_index_cavity[quick_index_cavity.size()-1]].getRefInd_im();
std::complex<double> n_prev = external_index;
// Convert to standard form
double n2_tilde = real(n_prev)*real(n_curr) + imag(n_prev)*imag(n_curr);
double k2_tilde = real(n_prev)*imag(n_curr) - real(n_curr)*imag(n_prev);
double n1_tilde = abs(n_prev)*abs(n_prev);
// Compute temporary terms
double n1_sin_th_2 = n1_tilde*sin(angle_of_incidence); // na*sin(theta)
n1_sin_th_2 *= n1_sin_th_2; // ^2
double norm_n_2 = n2_tilde*n2_tilde + k2_tilde*k2_tilde;
double term_a = 1.0+n1_sin_th_2/norm_n_2;
// Kovalenko 2001: Descartes-Snell law of refraction with absorption
// compute sin(theta)^2
double sin_th_2 = 0.5*(term_a - sqrt(term_a*term_a - 4.0*n2_tilde*n2_tilde*n1_sin_th_2/(norm_n_2*norm_n_2)));
double cos_th = sqrt(1.0-sin_th_2);
modules[quick_index_cavity[quick_index_cavity.size()-1]].setCosTh(cos_th,cos_th);
// Iterate over all cavities
for(int i=quick_index_cavity.size()-2; i>=0; i--)
{
n_curr = modules[quick_index_cavity[i]].getRefInd() + I*modules[quick_index_cavity[i]].getRefInd_im();
n_prev = modules[quick_index_cavity[i+1]].getRefInd() + I*modules[quick_index_cavity[i+1]].getRefInd_im();
// Convert to standard form
n2_tilde = real(n_prev)*real(n_curr) + imag(n_prev)*imag(n_curr);
k2_tilde = real(n_prev)*imag(n_curr) - real(n_curr)*imag(n_prev);
n1_tilde = abs(n_prev)*abs(n_prev);
// Compute temporary terms
n1_sin_th_2 = n1_tilde*n1_tilde*sin_th_2; // (n1 sin(th))^2
norm_n_2 = n2_tilde*n2_tilde + k2_tilde*k2_tilde;
term_a = 1.0+n1_sin_th_2/norm_n_2;
// Kovalenko 2001: Descartes-Snell law of refraction with absorption
// compute sin(theta)^2
sin_th_2 = 0.5*(term_a - sqrt(term_a*term_a - 4.0*n2_tilde*n2_tilde*n1_sin_th_2/(norm_n_2*norm_n_2)));
cos_th = sqrt(1.0-sin_th_2);
modules[quick_index_cavity[i]].setCosTh(cos_th,cos_th);
}
}
/*
* Create a gain medium on the left with QW.
*
* |---o-o-o-o-o-------------|--CAP--|--AR--|
*
* . If there is nothing on the left of this, a boundary is added
*
* Where:
* numQW -> Number of QW's in the medium [0,inf)
* - If numQW = 0 => Empty medium of length cavityLength
* dx0_qw -> Distance from LEFTMOST QW to the edge in units of lambda [0,1]
* dx_qw -> Distance between each QW in units of lambda (0,1]
* cavityLength -> Total length of cavity (not including AR and CAP)
* - If cavityLength = 0 => Fit cavity tight on QW's (If numQW = 0 => ERROR)
* - If cavityLength < space for QW with spacing => ERROR
* cavityIndex -> Refractive background index in medium
* capIndex -> Refractive index of CAP layer, if capIndex = 0 then NO CAP layer
* arIndex -> Refractive index of AR coating, if arIndex = 0 then NO ar coating
* angle_of_incidence -> Angle in radians for TE
* external_index -> Index in incoming medium
* */
void VECSEL::addRPG_QW_LEFT(int numQW, double dx0_qw, double dx_qw, double cavityLength, double cavityIndex, double capIndex, double arIndex, double angle_of_incidence, double external_index)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addRPG_QW_LEFT(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (dx0_qw < 0) {
cout << "addRPG_QW_LEFT(): dx0_qw < 0, quitting" << endl;
exit(-1);
} else if (dx_qw < 0) {
cout << "addRPG_QW_LEFT(): dx_qw <= 0, quitting" << endl;
exit(-1);
} else if (numQW < 0) {
cout << "addRPG_QW_LEFT(): numQW < 0, quitting" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength == 0))
{
cout << "addRPG_QW_LEFT(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_QW_LEFT: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((numQW > 0)&&(cavityLength>0))
{
double tmpWidth = dx0_qw + ((double)numQW -1.0)*dx_qw;
if (tmpWidth > cavityLength)
{
cout << "addRPG_QW_LEFT(): cavityLength too short, quitting" << endl;
exit(-1);
}
if ((dx_qw == 0)&&(numQW>1))
{
cout << "addRPG_QW_LEFT(): cannot have numQW>0 && dx_qw = 0, quitting" << endl;
exit(-1);
}
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
// CASE 2: numQW > 0
// First cavity
if (dx0_qw > 0)
{
tmpWidth = (getLambda()*dx0_qw)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
}
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addDevice();
tmpName.str("");
tmpName << "QW1_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
// Add rest in dx_qw distance
double deviceDistance = (getLambda()*dx_qw)/(cavityIndex);
for(int i = 1; i < numQW; i++)
{
// Add Cavity
tmp = addCavity(deviceDistance, cavityIndex);
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << i+1 << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
}
if (cavityLength > 0)
{
// Add rest of Cavity
tmpWidth = getLambda()*(cavityLength - dx0_qw - ((double)numQW -1.0)*dx_qw)/cavityIndex;
tmp = addCavity( tmpWidth , cavityIndex);
}
}
/*
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addCavity(tmpWidth, capIndex);
tmp->getCavity()->setName("Cap");
}
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (0.25*getLambda())/arIndex;
tmp = addCavity(tmpWidth, arIndex);
tmp->getCavity()->setName("Ar");
}
*/
// CAP
tmpWidth = 0.432421*(getLambda())/3.1778;
tmp = addCavity(tmpWidth, 3.1778);
tmp->getCavity()->setName("cap");
// AR 1
tmpWidth = 0.181938*(getLambda())/2.0781;
tmp = addCavity(tmpWidth, 2.0781);
tmp->getCavity()->setName("Ta2O5");
// AR 2
tmpWidth = 0.146560*(getLambda())/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("SiO2");
/*
// AR 4
tmpWidth = (getLambda()/2.0)/3.756268;
tmp = addCavity(tmpWidth, 3.756268);
tmp->getCavity()->setName("Ar4");
// AR 3
tmpWidth = (getLambda()/4.0)/2.870939;
tmp = addCavity(tmpWidth, 2.870939);
tmp->getCavity()->setName("Ar3");
// AR 2
tmpWidth = (getLambda()/4.0)/1.694157;
tmp = addCavity(tmpWidth, 1.694157);
tmp->getCavity()->setName("Ar2");
// AR 1
tmpWidth = (getLambda()/4.0)/1.126036;
tmp = addCavity(tmpWidth, 1.126036);
tmp->getCavity()->setName("Ar1");
*/
}
/* Similar to addRPG_QW_LEFT() however, this function will only add ONE qw at a given antinode and fill the rest with empty barrier material
*/
void VECSEL::addRPG_QW_LEFT_EFF(int anti_node, int numQW, double dx0_qw, double dx_qw, double cavityLength, double cavityIndex, double capIndex, double arIndex, double angle_of_incidence, double external_index)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addRPG_QW_LEFT_EFF(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (dx0_qw < 0) {
cout << "addRPG_QW_LEFT_EFF(): dx0_qw < 0, quitting" << endl;
exit(-1);
} else if (dx_qw < 0) {
cout << "addRPG_QW_LEFT_EFF(): dx_qw <= 0, quitting" << endl;
exit(-1);
} else if (numQW < 0) {
cout << "addRPG_QW_LEFT_EFF(): numQW < 0, quitting" << endl;
exit(-1);
} else if ((anti_node < 1) || (anti_node > numQW)) {
cout << "addRPG_QW_LEFT_EFF(): anti_node must be in range [1, numQW]" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength == 0))
{
cout << "addRPG_QW_LEFT(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_QW_LEFT: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((numQW > 0)&&(cavityLength>0))
{
double tmpWidth = dx0_qw + ((double)numQW -1.0)*dx_qw;
if (tmpWidth > cavityLength)
{
cout << "addRPG_QW_LEFT(): cavityLength too short, quitting" << endl;
exit(-1);
}
if ((dx_qw == 0)&&(numQW>1))
{
cout << "addRPG_QW_LEFT(): cannot have numQW>0 && dx_qw = 0, quitting" << endl;
exit(-1);
}
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
// CASE 2: numQW > 0
// First cavity
if (dx0_qw + (anti_node-1)*dx_qw > 0)
{
tmpWidth = getLambda()*(dx0_qw + (anti_node-1)*dx_qw)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
tmp->getCavity()->setName("FrontMatQW");
//tmp->setOutputToFile(1);
}
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << anti_node << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
//tmp->setOutputToFile(1);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
double delta_L = 0.0;
if (cavityLength > 0)
{
delta_L = cavityLength - dx0_qw - ((double)numQW -1.0)*dx_qw;
} else {
delta_L = 0.0;
}
if (anti_node < numQW)
{
tmpWidth = getLambda()*((numQW-anti_node)*dx_qw + delta_L)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
if (delta_L > 0)
{
// Add rest of Cavity
tmpWidth = getLambda()*(delta_L)/cavityIndex;
tmp = addCavity( tmpWidth , cavityIndex);
}
}
}
/*
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addCavity(tmpWidth, capIndex);
tmp->getCavity()->setName("Cap");
}
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (0.25*getLambda())/arIndex;
tmp = addCavity(tmpWidth, arIndex);
tmp->getCavity()->setName("Ar");
}
*/
// CAP
tmpWidth = 0.432421*(getLambda())/3.1778;
tmp = addCavity(tmpWidth, 3.1778);
tmp->getCavity()->setName("cap");
//tmp->setOutputToFile(1);
// AR 1
tmpWidth = 0.181938*(getLambda())/2.0781;
tmp = addCavity(tmpWidth, 2.0781);
tmp->getCavity()->setName("Ta2O5");
//tmp->setOutputToFile(1);
// AR 2
tmpWidth = 0.146560*(getLambda())/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("SiO2");
// tmp->setOutputToFile(1);
/*
// AR 4
tmpWidth = (getLambda()/2.0)/3.756268;
tmp = addCavity(tmpWidth, 3.756268);
tmp->getCavity()->setName("Ar4");
// AR 3
tmpWidth = (getLambda()/4.0)/2.870939;
tmp = addCavity(tmpWidth, 2.870939);
tmp->getCavity()->setName("Ar3");
// AR 2
tmpWidth = (getLambda()/4.0)/1.694157;
tmp = addCavity(tmpWidth, 1.694157);
tmp->getCavity()->setName("Ar2");
// AR 1
tmpWidth = (getLambda()/4.0)/1.126036;
tmp = addCavity(tmpWidth, 1.126036);
tmp->getCavity()->setName("Ar1");
*/
}
/* Similar to addRPG_QW_LEFT_EFF() but build from the opposite direction
*/
void VECSEL::addRPG_QW_RIGHT_EFF(int anti_node, int numQW, double dx0_qw, double dx_qw, double cavityLength, double cavityIndex, double capIndex, double arIndex, double angle_of_incidence, double external_index)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addRPG_QW_RIGHT_EFF(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (dx0_qw < 0) {
cout << "addRPG_QW_RIGHT_EFF(): dx0_qw < 0, quitting" << endl;
exit(-1);
} else if (dx_qw < 0) {
cout << "addRPG_QW_RIGHT_EFF(): dx_qw <= 0, quitting" << endl;
exit(-1);
} else if (numQW < 0) {
cout << "addRPG_QW_RIGHT_EFF(): numQW < 0, quitting" << endl;
exit(-1);
} else if ((anti_node < 1) || (anti_node > numQW)) {
cout << "addRPG_QW_RIGHT_EFF(): anti_node must be in range [1, numQW]" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength == 0))
{
cout << "addRPG_QW_RIGHT(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the RIGHT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_QW_RIGHT: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((numQW > 0)&&(cavityLength>0))
{
double tmpWidth = dx0_qw + ((double)numQW -1.0)*dx_qw;
if (tmpWidth > cavityLength)
{
cout << "addRPG_QW_RIGHT(): cavityLength too short, quitting" << endl;
exit(-1);
}
if ((dx_qw == 0)&&(numQW>1))
{
cout << "addRPG_QW_RIGHT(): cannot have numQW>0 && dx_qw = 0, quitting" << endl;
exit(-1);
}
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
// AR 2
tmpWidth = 0.146560*(getLambda())/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("SiO2");
// tmp->setOutputToFile(1);
// AR 1
tmpWidth = 0.181938*(getLambda())/2.0781;
tmp = addCavity(tmpWidth, 2.0781);
tmp->getCavity()->setName("Ta2O5");
//tmp->setOutputToFile(1);
// CAP
tmpWidth = 0.432421*(getLambda())/3.1778;
tmp = addCavity(tmpWidth, 3.1778);
tmp->getCavity()->setName("cap");
//tmp->setOutputToFile(1);
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
// CASE 2: numQW > 0
//First cavity
double delta_L = 0.0;
if (cavityLength > 0)
{
delta_L = cavityLength - dx0_qw - ((double)numQW -1.0)*dx_qw;
} else {
delta_L = 0.0;
}
if (anti_node < numQW)
{
tmpWidth = getLambda()*((numQW-anti_node)*dx_qw + delta_L)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
if (delta_L > 0)
{
// Add rest of Cavity
tmpWidth = getLambda()*(delta_L)/cavityIndex;
tmp = addCavity( tmpWidth , cavityIndex);
}
}
//QWs
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addDevice();
tmpName.str("");
tmpName << "QW" << anti_node << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
//tmp->setOutputToFile(1);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
// Last cavity
if (dx0_qw + (anti_node-1)*dx_qw > 0)
{
tmpWidth = getLambda()*(dx0_qw + (anti_node-1)*dx_qw)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
tmp->getCavity()->setName("FrontMatQW");
//tmp->setOutputToFile(1);
}
}
/*
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addCavity(tmpWidth, capIndex);
tmp->getCavity()->setName("Cap");
}
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (0.25*getLambda())/arIndex;
tmp = addCavity(tmpWidth, arIndex);
tmp->getCavity()->setName("Ar");
}
*/
/*
// AR 4
tmpWidth = (getLambda()/2.0)/3.756268;
tmp = addCavity(tmpWidth, 3.756268);
tmp->getCavity()->setName("Ar4");
// AR 3
tmpWidth = (getLambda()/4.0)/2.870939;
tmp = addCavity(tmpWidth, 2.870939);
tmp->getCavity()->setName("Ar3");
// AR 2
tmpWidth = (getLambda()/4.0)/1.694157;
tmp = addCavity(tmpWidth, 1.694157);
tmp->getCavity()->setName("Ar2");
// AR 1
tmpWidth = (getLambda()/4.0)/1.126036;
tmp = addCavity(tmpWidth, 1.126036);
tmp->getCavity()->setName("Ar1");
*/
}
/* Similar to addRPG_QW_LEFT() however, this function will only add ONE qw at a given antinode and fill the rest with empty barrier material
*/
void VECSEL::addRPG_QW_simple(int numQW, double cavityLength1, double cavityLength2, double cavityIndex, double angle_of_incidence, double external_index)
{
// Check the input for consistencty
if (cavityLength1<0 || cavityLength2<0)
{
cout<< "addRPG_QW_simple(): cavity lengths cannot be negative. Quitting." <<endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength1+cavityLength2 == 0))
{
cout << "addRPG_QW_simple(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the simple of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_QW_simple: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
/* tmpWidth = getLambda();
tmp = addCavity(tmpWidth, 100.0);
tmp->setOutputToFile(1);
//tmp->getCavity()->setName("BPMFS2");
tmp->getCavity()->setName("TESTCAV");*/
if (numQW == 0)
{
// CASE 1: EMPTY Cavity with probe
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
tmp->getCavity()->setName("CAVBACK");
tmp->setOutputToFile(2);
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
tmp->getCavity()->setName("CAVFRONT");
tmp->setOutputToFile(2);
} else {
// CASE 2: numQW > 0
// First cavity
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
tmp->getCavity()->setName("CAVBACK");
tmp->setOutputToFile(2);
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addDevice();
tmpName.str("");
tmpName << "QW6" << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(2);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
tmp->getCavity()->setName("CAVFRONT");
tmp->setOutputToFile(2);
}
}
/* Adds a basic twoArm cavity primarily for debugging purpoposes. Also adds a two arm interface in front if needed*/
/*void VECSEL::addTwoArmCavity(double cavityLength, double cavityIndex, double angle_of_incidence, double external_index)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
if (cavityLength < 0)
{
cout << "addTwoArmCavity(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (!(modules.back().isCavity()))
{
cout << "addTwoArmCavity(): Previous module must be a cavity, quitting" << endl;
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
double indx=getNumberModules();
tmpWidth = getLambda();
tmp = addTwoArmInterface(tmpWidth, cavityIndex, angle_of_incidence, 1.0);
tmpWidth = cavityLength*getLambda()/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex);
tmp->getTwoArmCavity()->setName("TACAV");
}*/
/* Similar to addRPG_QW_LEFT() however, this function will only add ONE qw at a given antinode and fill the rest with empty barrier material. This is the two arm equivalent.
*/
void VECSEL::addTwoArmRPG_QW_FRONT_EFF(int material, int anti_node, int numQW, double dx0_qw, double dx_qw, double cavityLength, double cavityIndex, double capIndex, double arIndex, double arIndex2, double angle_of_incidence, double external_index)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
double intIndex = cavityIndex;
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
arIndex2 = arIndex2*sqrt(1.0-a_sin2/(arIndex2*arIndex2));
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addTwoArmRPG_QW_front_EFF(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (dx0_qw < 0) {
cout << "addTwoArmRPG_QW_front_EFF(): dx0_qw < 0, quitting" << endl;
exit(-1);
} else if (dx_qw < 0) {
cout << "addTwoArmRPG_QW_front_EFF(): dx_qw <= 0, quitting" << endl;
exit(-1);
} else if (numQW < 0) {
cout << "addTwoArmRPG_QW_front_EFF(): numQW < 0, quitting" << endl;
exit(-1);
} else if (anti_node > numQW) {
cout << "addTwoArmRPG_QW_front_EFF(): anti_node must be <numQW" << endl;
exit(-1);
} else if ((anti_node < 1) && (numQW>0))
{
cout << "addTwoArmRPG_QW_front_EFF(): anti_node must be positive" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength == 0))
{
cout << "addTwoArmRPG_QW_front(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addTwoArmRPG_QW_front_EFF: No LEFT boundary detected, exiting for now. Not tested." << endl;
exit(-1);
} else if (modules[startInd-1].isBoundary())
{
cout<< "addTwoArmRPG_QW_front_EFF: TwoArm cavity proceeded by a boundary is untested. Exiting." << endl;
exit(-1);
}
if ((numQW > 0)&&(cavityLength>0))
{
double tmpWidth = dx0_qw + ((double)numQW -1.0)*dx_qw;
if (tmpWidth > cavityLength)
{
cout << "addTwoArmRPG_QW_front_EFF(): cavityLength too short, quitting" << endl;
exit(-1);
}
if ((dx_qw == 0)&&(numQW>1))
{
cout << "addTwoArmRPG_QW_front_EFF(): cannot have numQW>0 && dx_qw = 0, quitting" << endl;
exit(-1);
}
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
//WTF-Interface to start. Requires external index to be 1.0 and does not yet include forced delay. Need to make nonuniform cyclic structures.
if (modules[startInd-1].isCavity())
{
tmpWidth = 1.0*getLambda();
tmp = addTwoArmInterface(1.0, angle_of_incidence, 1.0, intIndex);
//tmp->getTwoArmInterface()->setReflect(-1.0); //Absorber has perfectly reflecting back boundary
}
// AR 1
tmpWidth = 0.146560*(getLambda())/arIndex;
tmp = addTwoArmCavity(tmpWidth, arIndex, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("SiO2");
// AR 2
tmpWidth = 0.181938*(getLambda())/arIndex2;
tmp = addTwoArmCavity(tmpWidth, arIndex2, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("Ta2O5");
// CAP
tmpWidth = 0.432421*(getLambda())/capIndex;
tmp = addTwoArmCavity(tmpWidth, capIndex, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("cap");
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else {
// CASE 2: numQW > 0
//Front cavity
double delta_L = 0.0;
if (cavityLength > 0)
{
delta_L = cavityLength - dx0_qw - ((double)numQW -1.0)*dx_qw;
} else {
delta_L = 0.0;
}
if (anti_node < numQW)
{
tmpWidth = getLambda()*((numQW-anti_node)*dx_qw + delta_L)/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else {
if (delta_L > 0)
{
// Add rest of Cavity
tmpWidth = getLambda()*(delta_L)/cavityIndex;
tmp = addTwoArmCavity( tmpWidth , cavityIndex, angle_of_incidence, external_index);
}
}
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "QW" << material << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
//WTFF-tmp->setOutputToFile(2);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
// Back cavity
if (dx0_qw + (anti_node-1)*dx_qw > 0)
{
tmpWidth = getLambda()*(dx0_qw + (anti_node-1)*dx_qw)/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
}
}
}
/* Generates a QW structure with two cavitiies separated by a QW.
*/
void VECSEL::addQW_STRUCT(int numQW, double cavityLength1, double cavityLength2, double cavityIndex, double angle_of_incidence, double external_index)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
double intIndex = cavityIndex;
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
// Check the input for consistencty
if (cavityLength1 < 0)
{
cout << "addQW_STRUCT(): cavityLength1 < 0, quitting" << endl;
exit(-1);
} else if (cavityLength2 < 0)
{
cout << "addQW_STRUCT(): cavityLength2 < 0, quitting" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength1 == 0 || cavityLength2 ==0))
{
cout << "addQW_STRUCT(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addQW_STRUCT: No LEFT boundary detected. TwoArmStructure as first cavity is untested. Exiting" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
tmpWidth = getLambda();
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*(cavityLength1+cavityLength2))/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else if (numQW < 0)
{
// CASE 2: numQW<0
//ABSORBING QW
//First cavity
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->setOutputToFile(2);
tmp->getCavity()->setName("CFRONT");
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addDevice();
tmpName.str("");
tmpName << "ABS1" << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(2);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
tmp->setOutputToFile(1);
tmp->getCavity()->setName("CBACK");
} else
{
// CASE 3: numQW > 0
// Gain QW
//First cavity
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->setOutputToFile(2);
tmp->getCavity()->setName("CFRONT");
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addDevice();
tmpName.str("");
tmpName << "QW6" << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(2);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
tmp->setOutputToFile(1);
tmp->getCavity()->setName("TACBACK");
}
}
/* Generates a two arm structure with an interface and two twoArmCavities separated by a QW. Will eventually support full angular implementation
*/
void VECSEL::addTwoArmQW_STRUCT(int numQW, double cavityLength1, double cavityLength2, double cavityIndex, double angle_of_incidence, double external_index, double reflect)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
double intIndex = cavityIndex;
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
// Check the input for consistencty
if (cavityLength1 < 0)
{
cout << "addTwoArmQW_STRUCT(): cavityLength1 < 0, quitting" << endl;
exit(-1);
} else if (cavityLength2 < 0)
{
cout << "addTwoArmQW_STRUCT(): cavityLength2 < 0, quitting" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength1 == 0 || cavityLength2 ==0))
{
cout << "addTwoArmQW_STRUCT(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addTwoArmQW_STRUCT: No LEFT boundary detected. TwoArmStructure as first cavity is untested. Exiting" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
tmpWidth = getLambda();
tmp = addTwoArmInterface(1.0, angle_of_incidence, 1.0, intIndex);
tmp->getTwoArmInterface()->setReflect(reflect); //Absorber has perfectly reflecting back boundary
//tmp->getTwoArmInterface()->setReflect(0.0); //Absorber has perfectly reflecting back boundary
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*(cavityLength1+cavityLength2))/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else if (numQW < 0)
{
// CASE 2: numQW<0
//ABSORBING QW
//First cavity
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->setOutputToFile(2);
tmp->getTwoArmCavity()->setName("TACFRONT");
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "ABS1" << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
tmp->setOutputToFile(2);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
tmp->setOutputToFile(1);
tmp->getTwoArmCavity()->setName("TACBACK");
} else
{
// CASE 3: numQW > 0
// Gain QW
//First cavity
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->setOutputToFile(2);
tmp->getTwoArmCavity()->setName("TACFRONT");
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "QW6" << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
tmp->setOutputToFile(2);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
tmp->setOutputToFile(1);
tmp->getTwoArmCavity()->setName("TACBACK");
}
}
/*
* Create an absorber on the RIGHT
*
* |--AR--|--CAP--|---------------o-o-o-o---|
*
* Where:
* numABS -> Number of ABS's in the medium [0,inf)
* - If numABS = 0 => Empty medium of length cavityLength
* dx0_abs -> Distance from RIGHTMOST ABS to the edge in units of lambda [0,1]
* dx_abs -> Distance between each ABS in units of lambda (0,1]
* cavityLength -> Total length of cavity (not including AR and CAP)
* - If cavityLength = 0 => Fit cavity tight on ABS's (If numABS = 0 => ERROR)
* - If cavityLength < space for ABS with spacing => ERROR
* cavityIndex -> Refractive background index in medium
* capIndex -> Refractive index of CAP layer, if capIndex = 0 then NO CAP layer
* arIndex -> Refractive index of AR coating, if arIndex = 0 then NO ar coating
* */
void VECSEL::addRPG_ABS_RIGHT(int numABS, double dx0_abs, double dx_abs, double cavityLength, double cavityIndex, double capIndex, double arIndex)
{
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addRPG_ABS_RIGHT(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (dx0_abs < 0) {
cout << "addRPG_ABS_RIGHT(): dx0_abs < 0, quitting" << endl;
exit(-1);
} else if (dx_abs < 0) {
cout << "addRPG_ABS_RIGHT(): dx_abs <= 0, quitting" << endl;
exit(-1);
} else if (numABS < 0) {
cout << "addRPG_ABS_RIGHT(): numABS < 0, quitting" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numABS == 0) && (cavityLength == 0))
{
cout << "addRPG_ABS_RIGHT(): numABS =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the ABS, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_ABS_RIGHT: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((numABS > 0)&&(cavityLength>0))
{
double tmpWidth = dx0_abs + ((double)numABS -1.0)*dx_abs;
if (tmpWidth > cavityLength)
{
cout << "addRPG_ABS_RIGHT(): cavityLength too short, quitting" << endl;
cout << "dx0_abs = " << dx0_abs << endl;
cout << "cavityL = " << cavityLength << endl;
exit(-1);
}
if ((dx_abs == 0)&&(numABS > 1))
{
cout << "addRPG_ABS_RIGHT(): cannot have numABS>0 && dx_qw = 0, quitting" << endl;
exit(-1);
}
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
/*
// AR 1
tmpWidth = 0.262484*getLambda()/1.45;
tmp = addCavity(tmpWidth, 1.45);
tmp->getCavity()->setName("Ar");
// AR 2
tmpWidth = 0.132304*getLambda()/3.195400;
tmp = addCavity(tmpWidth, 3.195400);
tmp->getCavity()->setName("cap");
// AR 1
tmpWidth = 0.180177*getLambda()/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar1");
// AR 2
tmpWidth = 0.149296*getLambda()/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("Ar2");
// AR 1
tmpWidth = 0.193327*getLambda()/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar1");
// AR 2
tmpWidth = 0.291200*getLambda()/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("Ar2");
// AR 1
tmpWidth = 0.358399*getLambda()/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar1");
// AR 2
tmpWidth = 0.222876*getLambda()/3.396376;
tmp = addCavity(tmpWidth, 3.396376);
tmp->getCavity()->setName("Ar2");
// AR 1
tmpWidth = 0.431467*getLambda()/2.963510;
tmp = addCavity(tmpWidth, 2.963510);
tmp->getCavity()->setName("Ar1");
*/
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (getLambda()/4.0)/arIndex;
tmp = addCavity(tmpWidth, arIndex);
tmp->getCavity()->setName("Ar");
}
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addCavity(tmpWidth, capIndex);
tmp->getCavity()->setName("Cap");
}
if (numABS == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
// CASE 2: numABS > 0
if (cavityLength > 0)
{
// Add first part of cavity
tmpWidth = getLambda()*(cavityLength - dx0_abs - ((double)numABS -1.0)*dx_abs)/cavityIndex;
tmp = addCavity( tmpWidth , cavityIndex);
}
// Add first device
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "ABS" << numABS << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
//tmp->setOutputToFile(2);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
// Add rest
double deviceDistance = (getLambda()*dx_abs)/cavityIndex;
for(int i = numABS-1; i>=1; i--)
{
// Add Cavity
tmp = addCavity(deviceDistance, cavityIndex);
// Add device
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "ABS" << i << "_T" << j+1;
tmp->getDevice()->setName(tmpName.str());
//tmp->setOutputToFile(1);
tmp->getDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
}
// Add final cavity
if (dx0_abs > 0)
{
tmpWidth = getLambda()*dx0_abs/cavityIndex;
tmp = addCavity(tmpWidth, cavityIndex);
tmp->getCavity()->setName("CBACK");
//tmp->setOutputToFile(1);
}
}
}
/* Create a twoArm simple quantum well structure without an interface
*
* |---|--QW--|---|
* */
void VECSEL::addTwoArmQW_noInterface(int numQW, double cavityLength1, double cavityLength2, double cavityIndex, double angle_of_incidence, double external_index)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
double intIndex = cavityIndex;
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
// Check the input for consistencty
if (cavityLength1 < 0)
{
cout << "addTwoArmQW_STRUCT(): cavityLength1 < 0, quitting" << endl;
exit(-1);
} else if (cavityLength2 < 0)
{
cout << "addTwoArmQW_STRUCT(): cavityLength2 < 0, quitting" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numQW == 0) && (cavityLength1 == 0 || cavityLength2 ==0))
{
cout << "addTwoArmQW_STRUCT(): numQW =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addTwoArmQW_STRUCT: No LEFT boundary detected. TwoArmStructure as first cavity is untested. Exiting" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
tmpWidth = getLambda();
if (numQW == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*(cavityLength1+cavityLength2))/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else if (numQW < 0)
{
// CASE 2: numQW<0
//ABSORBING QW
//First cavity
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->setOutputToFile(2);
tmp->getTwoArmCavity()->setName("TACFRONT");
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "ABS1" << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
tmp->setOutputToFile(2);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
tmp->setOutputToFile(1);
tmp->getTwoArmCavity()->setName("TACBACK");
} else
{
// CASE 3: numQW > 0
// Gain QW. Use QW6 material file. Hard-coded
//First cavity
tmpWidth = getLambda()*cavityLength1/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->setOutputToFile(2);
tmp->getTwoArmCavity()->setName("TACFRONT");
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add first device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "QW6" << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
tmp->setOutputToFile(2);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
tmpWidth = getLambda()*cavityLength2/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
tmp->setOutputToFile(1);
tmp->getTwoArmCavity()->setName("TACBACK");
}
}
/* Create a twoArm simple structure without an interface
* */
void VECSEL::addTwoArm_Space(double cavityLength, double cavityIndex, double angle_of_incidence, double external_index, const std::string &name)
{
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addTwoArm_Space(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addTwoArm_Space: No LEFT boundary detected. TwoArmStructure as first cavity is untested. Exiting" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
tmp->setOutputToFile(1);
tmp->getTwoArmCavity()->setName(name);
}
/* Create a birefringent crystal structure without an interface
* */
void VECSEL::addBirefringentCrystal(double width, double cavityIndex, double extraordinary_n, double angle_of_incidence)
{
// Check the input for consistencty
if (width < 0)
{
cout << "addBirefringentCrystal(): cavityLength1 < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addBirefringentCrystal: No LEFT boundary detected. TwoArmStructure as first cavity is untested. Exiting" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
tmpWidth = (getLambda()*width)/cavityIndex;
tmp = addBirefringentCrystal(tmpWidth, cavityIndex, extraordinary_n);
//tmp->setOutputToFile(1);
tmp->getBirefringentCrystal()->setName("BRC");
}
/* Create a kerr crystal structure without an interface
* */
void VECSEL::addKerrCrystal(double width, double cavityIndex, double n2, double angle_of_incidence)
{
// Check the input for consistencty
if (width < 0)
{
cout << "addKerrCrystal: cavityLength1 < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the QW, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addKerrCrystal: No LEFT boundary detected. TwoArmStructure as first cavity is untested. Exiting" << endl;
exit(-1);
}
Module *tmp;
double tmpWidth;
tmpWidth = (getLambda()*width)/cavityIndex;
tmp = addKerrCrystal(tmpWidth, cavityIndex, n2);
//tmp->setOutputToFile(1);
//tmp->getKerrCrystal()->setName("KERR");
}
/*
* Create a twoArm non-normal incidence absorber
*
* |--AR--|--CAP--|---------------o-o-o-o---|
*
* Where:
* numABS -> Number of ABS's in the medium [0,inf)
* - If numABS = 0 => Empty medium of length cavityLength
* dx0_abs -> Distance from RIGHTMOST ABS to the edge in units of lambda [0,1]
* dx_abs -> Distance between each ABS in units of lambda (0,1]
* cavityLength -> Total length of cavity (not including AR and CAP)
* - If cavityLength = 0 => Fit cavity tight on ABS's (If numABS = 0 => ERROR)
* - If cavityLength < space for ABS with spacing => ERROR
* cavityIndex -> Refractive background index in medium
* capIndex -> Refractive index of CAP layer, if capIndex = 0 then NO CAP layer
* arIndex -> Refractive index of AR coating, if arIndex = 0 then NO ar coating
* */
void VECSEL::addTwoArmRPG_ABS_LEFT(int numABS, double dx0_abs, double dx_abs, double cavityLength, double cavityIndex, double capIndex, double arIndex, double external_index, double angle_of_incidence)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
double intIndex = cavityIndex;
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addTwoArmRPG_ABS(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (dx0_abs < 0) {
cout << "addTwoArmRPG_ABS(): dx0_abs < 0, quitting" << endl;
exit(-1);
} else if (dx_abs < 0) {
cout << "addTwoArmRPG_ABS(): dx_abs <= 0, quitting" << endl;
exit(-1);
} else if (numABS < 0) {
cout << "addTwoArmRPG_ABS(): numABS < 0, quitting" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numABS == 0) && (cavityLength == 0))
{
cout << "addTwoArmRPG_ABS(): numABS =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the ABS, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addTwoArmRPG_ABS: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((numABS > 0)&&(cavityLength>0))
{
double tmpWidth = dx0_abs + ((double)numABS -1.0)*dx_abs;
if (tmpWidth > cavityLength)
{
cout << "addTwoArmRPG_ABS(): cavityLength too short, quitting" << endl;
cout << "dx0_abs = " << dx0_abs << endl;
cout << "cavityL = " << cavityLength << endl;
exit(-1);
}
if ((dx_abs == 0)&&(numABS > 1))
{
cout << "addTwoArmRPG_ABS(): cannot have numABS>0 && dx_qw = 0, quitting" << endl;
exit(-1);
}
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
if (modules[startInd-1].isCavity())
{
tmp = addTwoArmInterface(1.0, angle_of_incidence, 1.0, intIndex);
tmp->getTwoArmInterface()->setReflect(-1.0); //Absorber has perfectly reflecting back boundary
//tmp->getTwoArmInterface()->setReflect(0.0); //Absorber has perfectly reflecting back boundary
}
if (numABS == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else {
// CASE 2: numABS > 0
// Add final cavity
if (dx0_abs > 0)
{
tmpWidth = getLambda()*dx0_abs/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->getTwoArmCavity()->setName("TACBACK");
//tmp->setOutputToFile(1);
}
// Add rest
double deviceDistance = (getLambda()*dx_abs)/cavityIndex;
for(int i = numABS-1; i>=1; i--)
{
// Add device
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "ABS" << i << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
//WTFFF-tmp->setOutputToFile(1);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
// Add Cavity
tmp = addTwoArmCavity(deviceDistance, cavityIndex, angle_of_incidence, external_index);
}
// Add first device
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "ABS" << numABS << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
//tmp->setOutputToFile(0);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
if (cavityLength > 0)
{
// Add first part of cavity
tmpWidth = getLambda()*(cavityLength - dx0_abs - ((double)numABS -1.0)*dx_abs)/cavityIndex;
tmp = addTwoArmCavity( tmpWidth , cavityIndex, angle_of_incidence, external_index);
}
}
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addTwoArmCavity(tmpWidth, capIndex, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("Cap");
}
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (getLambda()/4.0)/arIndex;
tmp = addTwoArmCavity(tmpWidth, arIndex, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("Ar");
}
}
/*
* Create a twoArm non-normal incidence absorber
*
* |--AR--|--CAP--|---------------o-o-o-o---|
*
* Where:
* numABS -> Number of ABS's in the medium [0,inf)
* - If numABS = 0 => Empty medium of length cavityLength
* dx0_abs -> Distance from RIGHTMOST ABS to the edge in units of lambda [0,1]
* dx_abs -> Distance between each ABS in units of lambda (0,1]
* cavityLength -> Total length of cavity (not including AR and CAP)
* - If cavityLength = 0 => Fit cavity tight on ABS's (If numABS = 0 => ERROR)
* - If cavityLength < space for ABS with spacing => ERROR
* cavityIndex -> Refractive background index in medium
* capIndex -> Refractive index of CAP layer, if capIndex = 0 then NO CAP layer
* arIndex -> Refractive index of AR coating, if arIndex = 0 then NO ar coating
* */
void VECSEL::addTwoArmRPG_ABS(int numABS, double dx0_abs, double dx_abs, double cavityLength, double cavityIndex, double capIndex, double arIndex, double external_index, double angle_of_incidence, double reflect)
{
//==========================
// With angle of incidence
//==========================
double a_sin2 = external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence);
double intIndex = cavityIndex;
cavityIndex = cavityIndex*sqrt(1.0-a_sin2/(cavityIndex*cavityIndex));
capIndex = capIndex*sqrt(1.0-a_sin2/(capIndex*capIndex));
arIndex = arIndex*sqrt(1.0-a_sin2/(arIndex*arIndex));
// Check the input for consistencty
if (cavityLength < 0)
{
cout << "addTwoArmRPG_ABS(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (dx0_abs < 0) {
cout << "addTwoArmRPG_ABS(): dx0_abs < 0, quitting" << endl;
exit(-1);
} else if (dx_abs < 0) {
cout << "addTwoArmRPG_ABS(): dx_abs <= 0, quitting" << endl;
exit(-1);
} else if (numABS < 0) {
cout << "addTwoArmRPG_ABS(): numABS < 0, quitting" << endl;
exit(-1);
}
// Check a few logical inconsistencies
if ((numABS == 0) && (cavityLength == 0))
{
cout << "addTwoArmRPG_ABS(): numABS =0 && cavityLength = 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the ABS, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addTwoArmRPG_ABS: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((numABS > 0)&&(cavityLength>0))
{
double tmpWidth = dx0_abs + ((double)numABS -1.0)*dx_abs;
if (tmpWidth > cavityLength)
{
cout << "addTwoArmRPG_ABS(): cavityLength too short, quitting" << endl;
cout << "dx0_abs = " << dx0_abs << endl;
cout << "cavityL = " << cavityLength << endl;
exit(-1);
}
if ((dx_abs == 0)&&(numABS > 1))
{
cout << "addTwoArmRPG_ABS(): cannot have numABS>0 && dx_qw = 0, quitting" << endl;
exit(-1);
}
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
if (modules[startInd-1].isCavity())
{
tmp = addTwoArmInterface(1.0, angle_of_incidence, 1.0, intIndex);
tmp->getTwoArmInterface()->setReflect(reflect); //Absorber has perfectly reflecting back boundary
}
/* // AR 1
tmpWidth = 0.146560*(getLambda())/arIndex;
tmp = addTwoArmCavity(tmpWidth, arIndex, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("SiO2");
*/
// Add AR coating
if (arIndex > 0)
{
tmpWidth = (getLambda()/4.0)/arIndex;
tmp = addTwoArmCavity(tmpWidth, arIndex, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("Ar");
}
// Add CAP layer
if (capIndex > 0)
{
tmpWidth = (getLambda()/2.0)/capIndex;
tmp = addTwoArmCavity(tmpWidth, capIndex, angle_of_incidence, external_index);
tmp->getTwoArmCavity()->setName("Cap");
}
if (numABS == 0)
{
// CASE 1: EMPTY Cavity
tmpWidth = (getLambda()*cavityLength)/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
} else {
// CASE 2: numABS > 0
if (cavityLength > 0)
{
// Add first part of cavity
tmpWidth = getLambda()*(cavityLength - dx0_abs - ((double)numABS -1.0)*dx_abs)/cavityIndex;
tmp = addTwoArmCavity( tmpWidth , cavityIndex, angle_of_incidence, external_index);
}
// Add first device
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "ABS" << numABS << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
//tmp->setOutputToFile(0);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
// Add rest
double deviceDistance = (getLambda()*dx_abs)/cavityIndex;
for(int i = numABS-1; i>=1; i--)
{
// Add Cavity
tmp = addTwoArmCavity(deviceDistance, cavityIndex, angle_of_incidence, external_index);
// Add device
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
// Add device
tmp = addTwoArmDevice();
tmpName.str("");
tmpName << "ABS" << i << "_T" << j+1;
tmp->getTwoArmDevice()->setName(tmpName.str());
//WTFFF-tmp->setOutputToFile(1);
tmp->getTwoArmDevice()->setTransversePosition(VECSEL_transverse_points_y[j]);
}
}
// Add final cavity
if (dx0_abs > 0)
{
tmpWidth = getLambda()*dx0_abs/cavityIndex;
tmp = addTwoArmCavity(tmpWidth, cavityIndex, angle_of_incidence, external_index);
//tmp->getTwoArmCavity()->setName("TACBACK");
//tmp->setOutputToFile(1);
}
}
}
void VECSEL::addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(double arIndex, double arLength, double dx0, double dx1, double cavityIndex, double DBR_n1, double DBR_n1_length, double DBR_n2, double DBR_n2_length, int num_dbr_layers, double PHASE_n, double PHASE_length, double angle_of_incidence, double external_index)
{
// Check the input for consistencty
if (arIndex <= 1.0)
{
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): arIndex <= 1.0, quitting" << endl;
exit(-1);
} else if (arLength < 0.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): arLength < 0.0, quitting" << endl;
exit(-1);
} else if (dx0 < 0.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): dx0 < 0.0, quitting" << endl;
exit(-1);
} else if (dx1 < 0.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): dx1 < 0.0, quitting" << endl;
exit(-1);
} else if (cavityIndex <= 1.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): cavityIndex <= 1.0, quitting" << endl;
exit(-1);
} else if (DBR_n1 <= 1.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): DBR_n1 <= 1.0, quitting" << endl;
exit(-1);
} else if (DBR_n1_length <= 0.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): DBR_n1_length <= 0.0, quitting" << endl;
exit(-1);
} else if (DBR_n2 <= 1.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): DBR_n2 <= 1.0, quitting" << endl;
exit(-1);
} else if (DBR_n2_length <= 0.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): DBR_n2_length <= 0.0, quitting" << endl;
exit(-1);
} else if (num_dbr_layers <= 0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): num_dbr_layers <= 0.0, quitting" << endl;
exit(-1);
} else if (PHASE_n <= 1.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): PHASE_n <= 1.0, quitting" << endl;
exit(-1);
} else if (PHASE_length <= 0.0) {
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): PHASE_length <= 0.0, quitting" << endl;
exit(-1);
}
// Illogical statements
if (DBR_n1 == DBR_n2)
{
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): DBR layers cannot be equal, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the ABS, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_ABS_DBR_PHASE_RIGHT_ANGLE(): No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
Module *tmp;
double tmpWidth;
std::stringstream tmpName;
double ar1_l = 112.60*nm; // 111.1nm
double ar1_n = 1.4770;
// AR 1
tmp = addCavity(ar1_l, ar1_n, angle_of_incidence, external_index);
tmp->getCavity()->setName("Ar1");
int index_initial_cavity = quick_index_cavity.size()-1; // Store initial cavity (AR1)
// AR 2
double ar2_l = 113.54*nm; //114.07nm
double ar2_n = 1.9826;
tmp = addCavity(ar2_l, ar2_n, angle_of_incidence, external_index);
tmp->getCavity()->setName("Ar2");
// Surface layer
tmp = addCavity(dx0 , cavityIndex, angle_of_incidence, external_index);
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "ABS1";
tmp->getDevice()->setName(tmpName.str());
tmp->setOutputToFile(1);
// Add final cavity
tmp = addCavity(dx1 , cavityIndex, angle_of_incidence, external_index);
// ADD DBR
// Ensure alternating reflectors
double n_bragg[2] = {DBR_n1,DBR_n2};
double L_bragg[2] = {DBR_n1_length,DBR_n2_length};
// Create numLayers cavities of given length
for(int i = 0; i < num_dbr_layers; i++)
{
tmp = addCavity(L_bragg[i%2], n_bragg[i%2], angle_of_incidence, external_index);
}
// ADD PHASE LAYER
tmp = addCavity(PHASE_length , PHASE_n, angle_of_incidence, external_index);
//====================================================================
// Add in angle dependence for ALL layers in this function
// First cavity
std::complex<double> n_curr = modules[quick_index_cavity[index_initial_cavity]].getRefInd() + I*modules[quick_index_cavity[index_initial_cavity]].getRefInd_im();
std::complex<double> n_prev = external_index;
// Convert to standard form
double n2_tilde = real(n_prev)*real(n_curr) + imag(n_prev)*imag(n_curr);
double k2_tilde = real(n_prev)*imag(n_curr) - real(n_curr)*imag(n_prev);
double n1_tilde = abs(n_prev)*abs(n_prev);
// Compute temporary terms
double n1_sin_th_2 = n1_tilde*sin(angle_of_incidence); // na*sin(theta)
n1_sin_th_2 *= n1_sin_th_2; // ^2
double norm_n_2 = n2_tilde*n2_tilde + k2_tilde*k2_tilde;
double term_a = 1.0+n1_sin_th_2/norm_n_2;
// Kovalenko 2001: Descartes-Snell law of refraction with absorption
// compute sin(theta)^2
double sin_th_2 = 0.5*(term_a - sqrt(term_a*term_a - 4.0*n2_tilde*n2_tilde*n1_sin_th_2/(norm_n_2*norm_n_2)));
double cos_th = sqrt(1.0-sin_th_2);
modules[quick_index_cavity[index_initial_cavity]].setCosTh(cos_th,cos_th);
// Iterate over all cavities
for(int i=index_initial_cavity+1; i<quick_index_cavity.size(); i++)
{
n_curr = modules[quick_index_cavity[i]].getRefInd() + I*modules[quick_index_cavity[i]].getRefInd_im();
n_prev = modules[quick_index_cavity[i-1]].getRefInd() + I*modules[quick_index_cavity[i-1]].getRefInd_im();
// Convert to standard form
n2_tilde = real(n_prev)*real(n_curr) + imag(n_prev)*imag(n_curr);
k2_tilde = real(n_prev)*imag(n_curr) - real(n_curr)*imag(n_prev);
n1_tilde = abs(n_prev)*abs(n_prev);
// Compute temporary terms
n1_sin_th_2 = n1_tilde*n1_tilde*sin_th_2; // (n1 sin(th))^2
norm_n_2 = n2_tilde*n2_tilde + k2_tilde*k2_tilde;
term_a = 1.0+n1_sin_th_2/norm_n_2;
// Kovalenko 2001: Descartes-Snell law of refraction with absorption
// compute sin(theta)^2
sin_th_2 = 0.5*(term_a - sqrt(term_a*term_a - 4.0*n2_tilde*n2_tilde*n1_sin_th_2/(norm_n_2*norm_n_2)));
cos_th = sqrt(1.0-sin_th_2);
modules[quick_index_cavity[i]].setCosTh(cos_th,cos_th);
}
}
/*
* Add an empty space with a seperator in the middle for output
* -> probe_tune is the tuning of space. Range(probe_tine) = [-1,1] in units of lambda
* */
void VECSEL::addCUSTOM_SPACE(double cavityLength, double leftDeviceCavityLength, double cavityIndex, double probe_tune, const std::string &name)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = getLambda()*(cavityLength/2.0 + probe_tune)/cavityIndex - leftDeviceCavityLength;
double length2 = getLambda()*(cavityLength)/cavityIndex - length1;
Module *tmp;
tmp = addCavity(length1, cavityIndex);
tmp->setOutputToFile(1);
tmp->getCavity()->setName(name);
tmp = addCavity(length2, cavityIndex);
}
/*
* Add an empty space with a seperator in the middle for output
* -> probe_tune is the tuning of space. Range(probe_tine) = [-1,1] in units of lambda
* */
void VECSEL::addRPG_SPACE(double cavityLength, double cavityIndex, double probe_tune, const std::string &name)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
//cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
//addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = cavityLength/2.0 + probe_tune;
double length2 = cavityLength - length1;
Module *tmp;
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex);
tmp->setOutputToFile(1);
tmp->getCavity()->setName(name);
tmp = addCavity((getLambda()*length2)/cavityIndex, cavityIndex);
}
/*
* Add an ETALON + AIR AROUND with a seperator in the middle for output
* -> probe_tune is the tuning of space. Range(probe_tine) = [-1,1] in units of lambda
* */
void VECSEL::addRPG_SPACE_ETALON(double cavityLength, double cavityIndex, double probe_tune, const std::string &name, double ETALON_INDEX, double ETALON_WIDTH)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE_ETALON(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
//cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
//addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE_ETALON: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = (cavityLength-0.5)/2.0 + probe_tune;
Module *tmp;
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex);
tmp->setOutputToFile(1);
tmp->getCavity()->setName(name);
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex);
tmp = addCavity(ETALON_WIDTH, ETALON_INDEX);
tmp->getCavity()->setName("ETALON1");
tmp = addCavity((getLambda()*0.5)/cavityIndex, cavityIndex);
}
void VECSEL::addRPG_SPACE_ETALON2(double cavityLength, double cavityIndex, double probe_tune, const std::string &name, double ETALON_INDEX1, double ETALON_WIDTH1, double ETALON_INDEX2, double ETALON_WIDTH2)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE_ETALON(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
//cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
//addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE_ETALON: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
Module *tmp;
tmp = addCavity((getLambda()*cavityLength)/cavityIndex, cavityIndex);
tmp->setOutputToFile(1);
tmp->getCavity()->setName(name);
if (ETALON_WIDTH1 < ETALON_WIDTH2)
{
cout<< "VECSEL::addRPG_SPACE_ETALON2(): Are you sure you're designing the correct cavity etalon ORDER???" << endl;
exit(-1);
}
tmp = addCavity(ETALON_WIDTH1, ETALON_INDEX1);
tmp->getCavity()->setName("ETALON1");
tmp = addCavity((0.25*getLambda())/cavityIndex, cavityIndex);
tmp = addCavity(ETALON_WIDTH2, ETALON_INDEX2);
tmp->getCavity()->setName("ETALON2");
tmp = addCavity((0.25*getLambda())/cavityIndex, cavityIndex);
}
// wa_s -> is wa*dt
// wb_s -> wb*dt
// w0_s -> w0*dt
// width_s -> spectral_width*dt
// filter_length is number of timesteps in filter
void VECSEL::addRPG_SPACE_FILTER(double cavityLength, double cavityIndex, double probe_tune, const std::string &name, double wa_s, double wb_s, double w0_s, double width_s, int filter_length)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE_FILTER(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
//cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
//addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE_FILTER: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = cavityLength/2.0 + probe_tune;
double length2 = cavityLength - length1 - 10.0;
double length3 = 10.0;
Module *tmp;
tmp = addCavity((getLambda()*(0.1*length1))/cavityIndex, cavityIndex);
tmp = addFilter(filter_length);
//tmp->getFilter()->setdoubleExp_flatTopWindow(wa_s, wb_s);
tmp->getFilter()->setFilter_pluss_doubleGauss_flatTopWindow(wa_s, wb_s, width_s, w0_s); // Gauss filter
//tmp->getFilter()->setFilter_pluss_diagnostic_square(0.5);
//tmp->getFilter()->setFilter_pluss_PassThroughDelay(); // Delay "filter"
tmp->getFilter()->setFilter_minus_PassThroughDelay(); // Delay "filter"
tmp = addCavity((getLambda()*(0.9*length1))/cavityIndex, cavityIndex);
tmp->setOutputToFile(1);
tmp->getCavity()->setName(name);
tmp = addCavity((getLambda()*length2)/cavityIndex, cavityIndex);
tmp = addCavity((getLambda()*length3)/cavityIndex, cavityIndex); // Added layer to make the filter work better
}
void VECSEL::addRPG_SPACE_ANGLE(double cavityLength, double cavityIndex, double probe_tune, const std::string &name, double angle_of_incidence, double angle_of_incidence_transfer)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
//cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
//addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = cavityLength/2.0 + probe_tune;
double length2 = cavityLength - length1;
Module *tmp;
if (angle_of_incidence != angle_of_incidence_transfer)
{
tmp = addCavity(0.01*(getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
double cos_left, cos_right; tmp->getCosTh(&cos_left,&cos_right);
tmp->setCosTh(cos_left,1.0);
// Change left angle
tmp = addCavity(0.99*(getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence_transfer, cavityIndex);
} else {
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
}
tmp->setOutputToFile(2);
tmp->getCavity()->setName(name);
tmp = addCavity((getLambda()*length2)/cavityIndex, cavityIndex, angle_of_incidence_transfer, cavityIndex);
}
void VECSEL::addRPG_SPACE_ANGLE_LEFT(double cavityLength, double cavityIndex, double probe_tune, const std::string &name, double angle_of_incidence, double angle_of_incidence_transfer)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
//cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
//addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length2 = cavityLength/2.0 + probe_tune;
double length1 = cavityLength - length2;
Module *tmp;
if (angle_of_incidence != angle_of_incidence_transfer)
{
tmp = addCavity(0.01*(getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
double cos_left, cos_right; tmp->getCosTh(&cos_left,&cos_right);
tmp->setCosTh(cos_left,1.0);
// Change left angle
tmp = addCavity(0.99*(getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence_transfer, cavityIndex);
} else {
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
}
tmp = addCavity((getLambda()*length2)/cavityIndex, cavityIndex, angle_of_incidence_transfer, cavityIndex);
tmp->setOutputToFile(1);
tmp->getCavity()->setName(name);
}
void VECSEL::addRPG_SPACE_LENS(double cavityLength, double cavityIndex, double lens_1, double armLength, double lens_2)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE_LENS(): cavityLength < 0, quitting" << endl;
exit(-1);
} else if (abs(lens_1)>0.0 && abs(lens_2)>0.0)
{
cout << "addRPG_SPACE_LENS(): sing lens structure, ~(abs(lens_1)>0 && abs(lens_2)>0)"<<endl;
exit(-1);
}
Module *tmp;
tmp = addCavity((getLambda()*cavityLength)/cavityIndex, cavityIndex, 0.0, cavityIndex);
if(abs(lens_1)>0.0)
{
tmp->getCavity()->setName("BPMHCL");
tmp->getCavity()->set_equivalent_optical_cavity(lens_1, armLength, lens_2);
} else if (abs(lens_2)>0.0)
{
tmp->getCavity()->setName("BPMHCR");
tmp->getCavity()->set_equivalent_optical_cavity(lens_2, armLength, lens_1);
}
}
void VECSEL::addRPG_SPACE_LENS_ANGLE(double cavityLength, double cavityIndex, double lens_1, double armLength, double lens_2, double angle_of_incidence)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE_LENS_ANGLE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
Module *tmp;
tmp = addCavity((getLambda()*cavityLength)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
if(abs(lens_1)>0.0)
{
tmp->getCavity()->setName("BPMHCL");
tmp->getCavity()->set_equivalent_optical_cavity(lens_1, armLength, lens_2);
} else if (abs(lens_2)>0.0)
{
tmp->getCavity()->setName("BPMHCR");
tmp->getCavity()->set_equivalent_optical_cavity(lens_2, armLength, lens_1);
}
}
void VECSEL::addRPG_SPACE_BPM(double cavityLength, double opticalLength, double cavityIndex, double probe_tune, const std::string &name)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = cavityLength/2.0 + probe_tune;
double length2 = cavityLength - length1;
Module *tmp;
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex);
//tmp->setOutputToFile(2);
//tmp->getCavity()->setName("BPMFS2");
tmp->getCavity()->setName(name);
tmp = addCavity((getLambda()*length2)/cavityIndex, cavityIndex);
tmp->getCavity()->setName("BPMFS");
tmp->getCavity()->set_equivalent_optical_cavity(0.0, opticalLength, 0.0);
}
void VECSEL::addRPG_SPACE_BPM_ANGLE(double cavityLength, double opticalLength, double cavityIndex, double probe_tune, const std::string &name, double angle_of_incidence)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = cavityLength/2.0 + probe_tune;
double length2 = cavityLength - length1;
Module *tmp;
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
//tmp->setOutputToFile(2);
//tmp->getCavity()->setName("BPMFS2");
tmp->getCavity()->setName(name);
tmp = addCavity((getLambda()*length2)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
tmp->getCavity()->setName("BPMFS");
tmp->getCavity()->set_equivalent_optical_cavity(0.0, opticalLength, 0.0);
}
void VECSEL::addRPG_SPACE_BPM_APERTURE(double cavityLength, double opticalLength, double cavityIndex, double probe_tune, const std::string &name, double angle_of_incidence, double aperture_fwhm_ratio)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
addBoundary(1.0,1.0);
}
if ((probe_tune > 1.0)||(probe_tune < -1.0))
{
cout << "addRPG_SPACE: Probe is out of bounds, should be in [-1,1] but is = " << probe_tune << endl;
exit(-1);
}
double length1 = cavityLength/2.0 + probe_tune;
double length2 = cavityLength - length1;
Module *tmp;
tmp = addCavity((getLambda()*length1)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex);
//tmp->setOutputToFile(2);
//tmp->getCavity()->setName("BPMFS2");
tmp->getCavity()->setName(name);
tmp = addCavity_aperture((getLambda()*length2)/cavityIndex, cavityIndex, angle_of_incidence, cavityIndex, aperture_fwhm_ratio);
tmp->getCavity()->setName("BPMFS");
tmp->getCavity()->set_equivalent_optical_cavity(0.0, opticalLength, 0.0);
}
void VECSEL::addRPG_SPACE_LENS_transform(double cavityLength, double cavityIndex, double A, double B, double C, double D)
{
if (cavityLength < 0)
{
cout << "addRPG_SPACE(): cavityLength < 0, quitting" << endl;
exit(-1);
}
// If there is nothing on the LEFT of the SPACE, add a boundary for consistency
int startInd = getNumberModules();
if (startInd == 0)
{
//cout << "addRPG_SPACE: No LEFT boundary detected, adding perfect reflection" << endl;
//addBoundary(1.0,1.0);
}
// Construct Lengths/Focus from ABCD matrix formulation
double LENS_1 = B/(1.0-D);
double LENS_2 = B/(1.0-A);
double LENGTH = B;
Module *tmp;
tmp = addCavity((getLambda()*cavityLength)/cavityIndex, cavityIndex, 0.0, cavityIndex);
tmp->getCavity()->setName("BPMTRANS");
tmp->getCavity()->set_equivalent_optical_cavity(LENS_1, LENGTH, LENS_2);
}
void VECSEL::addQW_SPACE_ABS(int numQW, int numABS, double dx0_qw, double dx0_abs, double cavityLength, double cavityIndex)
{
// Check the input
if ((numQW < 0)||(numABS < 0))
{
cout << "addQW_SPACE_ABS: Need numQW, numABS >= 0" << endl;
exit(-1);
}
if ((dx0_qw < 0)||(dx0_abs < 0))
{
cout << "addQW_SPACE_ABS: Need dx0_qw, dx0_abs >= 0" << endl;
exit(-1);
}
if (cavityLength <= 0)
{
cout << "addQW_SPACE_ABS: Need cavityLength > 0" << endl;
exit(-1);
}
// Find position of previous element
int startInd = getNumberModules();
if (startInd == 0)
{
cout << "addQW_SPACE_ABS: Adding perfect absorbtion on the left" << endl;
addBoundary(0.0,1.0);
startInd += 1;
}
// Store starting position
double startPos = modules.back().getPosition1();
// Start adding cavity / devices
double deviceDistance = getLambda()/(2.0*cavityIndex);
double tmpWidth = 0;
// Start adding cavity
Module *tmp;
std::stringstream tmpName;
if ((numQW == 0)&&( numABS == 0))
{
// CASE 1: EMPTY Cavity
tmpWidth = getLambda()*cavityLength;
tmp = addCavity(tmpWidth, cavityIndex);
} else if ((numQW > 0)&&( numABS == 0)) {
// Check if too many QW's
if (getLambda()*cavityLength - ((double)numQW-1.0)*deviceDistance - dx0_qw < 0.0)
{
cout << "addQW_SPACE_ABS: Cannot fit all QW's into cavity. Either add length or reduce numQW" << endl;
exit(-1);
}
// CASE 2: No absorbers
// First cavity
tmpWidth = getLambda()*dx0_qw;
tmp = addCavity(tmpWidth, cavityIndex);
// Add first device
tmp = addDevice();
tmp->getDevice()->setName("QW 1");
// Add rest in lambda/2 distance
for(int i = 1; i < numQW; i++)
{
// Add Cavity
tmp = addCavity(deviceDistance, cavityIndex);
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "QW " << i+1;
tmp->getDevice()->setName(tmpName.str());
}
// Add rest of Cavity
tmpWidth = getLambda()*(cavityLength - modules.back().getPosition1());
tmp = addCavity( tmpWidth , cavityIndex);
} else if ((numQW == 0)&&( numABS > 0))
{
// Check if too many ABS's
if (getLambda()*cavityLength - ((double)numABS-1.0)*deviceDistance - dx0_abs < 0.0)
{
cout << "addQW_SPACE_ABS: Cannot fit all ABS's into cavity. Either add length or reduce numABS" << endl;
exit(-1);
}
// CASE 3: No QW
// First cavity
tmpWidth = getLambda()*cavityLength - ( getLambda()*dx0_abs + deviceDistance*((double)numABS-1.0) );
tmp = addCavity(tmpWidth, cavityIndex);
// Add first device
tmp = addDevice();
tmp->getDevice()->setName("ABS 1");
// Add rest in lambda/2 distance
for(int i = 1; i < numABS; i++)
{
// Add Cavity
tmp = addCavity(deviceDistance, cavityIndex);
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "ABS " << i+1;
tmp->getDevice()->setName(tmpName.str());
}
// Add final cavity
tmpWidth = getLambda()*dx0_abs;
tmp = addCavity(tmpWidth, cavityIndex);
} else {
// Check if too many ABS's
if (getLambda()*cavityLength - ((double)numQW-1.0)*deviceDistance - dx0_qw - ((double)numABS-1.0)*deviceDistance - dx0_abs < 0.0)
{
cout << "addQW_SPACE_ABS: Cannot fit all QW's + ABS's into cavity. Either add length or reduce numQW and numABS" << endl;
exit(-1);
}
// CASE 4: Both QW and ABS
// First cavity
tmpWidth = getLambda()*dx0_qw;
tmp = addCavity(tmpWidth, cavityIndex);
// Add 1st QW
tmp = addDevice();
tmp->getDevice()->setName("QW 1");
// Add rest in lambda/2 distance
for(int i = 1; i < numQW; i++)
{
// Add Cavity
tmp = addCavity(deviceDistance, cavityIndex);
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "QW " << i+1;
tmp->getDevice()->setName(tmpName.str());
}
// Add middle cavity
double middle_space = getLambda()*cavityLength - getLambda()*dx0_qw - deviceDistance*((double)numQW-1.0) - getLambda()*dx0_abs - deviceDistance*((double)numABS-1.0);
tmp = addCavity(middle_space,cavityIndex);
// Add first device
tmp = addDevice();
tmp->getDevice()->setName("ABS 1");
// Add ABSORBERS
for(int i = 1; i < numABS; i++)
{
// Add Cavity
tmp = addCavity(deviceDistance, cavityIndex);
// Add device
tmp = addDevice();
tmpName.str("");
tmpName << "ABS " << i+1;
tmp->getDevice()->setName(tmpName.str());
}
// Add final cavity
tmpWidth = getLambda()*dx0_abs;
tmp = addCavity(tmpWidth, cavityIndex);
}
cout << "addQW_SPACE_ABS: Adding REFLECTING boundary on the right" << endl;
addBoundary(1.0,1.0);
}
// Move QWs 1 to num to new positions given in newPos[0] -> newPos[num-1]
// Should only be used in a linear cavity
// Not set up for twoArmDevices
void VECSEL::moveQWpositions(int num, double *newPos, double DT)
{
// Find target cavities
int target_cav[num+1];
for(int i = 0; i < num; i++)
{
target_cav[i] = quick_index_device_previous_cavity[i];
}
// Find next cavity after the last QW
for(int i = target_cav[num-1]+1; i < modules.size(); i++)
{
if (modules[i].isCavity())
{
target_cav[num] = i;
break;
}
}
/*
// TODO: REMOVE fake placement
for(int i = 0; i < num; i++)
{
double oldPos = modules[target_cav[i]+1].getPosition1();
newPos[i] = oldPos - 10.0*nm;
}
cout << "Cav positions.. before" << endl;
for(int i = 0; i < num+1; i++)
{
double x0 = modules[target_cav[i]].getPosition0();
double x1 = modules[target_cav[i]].getPosition1();
cout << "[" << target_cav[i] << "]: x = [ " << x0/1.0e-6 << " / " << x1/1.0e-6 << "] [um] width = " << (x1-x0)/1.0e-9 << " [nm]" << endl;
}
*/
// check that new points are consistent
double x0 = modules[target_cav[0 ]].getPosition0();
double x1 = modules[target_cav[num]].getPosition1();
for(int i = 0; i < num; i++)
{
if ((newPos[i] <= x0)||(newPos[i] >= x1))
{
cout << "moveQWpositions():: Positions out of bound" << endl;
cout << "Boundaries = [ " << x0 << " / " << x1 << " ]" << endl;
cout << "Position:" << endl;
for(int j = 0; j < num; j++)
{
cout << "[" << j << "]: " << newPos[j] << endl;
}
exit(-1);
}
}
// Set new limits for cavities, keep boundaries fixed
modules[target_cav[0]].setPosition(modules[target_cav[0]].getPosition0(),newPos[0]); // Cav
modules[target_cav[0]+1].setPosition(newPos[0],newPos[0]); // Device
for(int i = 1; i < num; i++)
{
int indx = target_cav[i];
modules[target_cav[i]].setPosition(modules[target_cav[i]-1].getPosition1(),newPos[i]); // Cav
modules[target_cav[i]+1].setPosition(newPos[i],newPos[i]); // Device
}
modules[target_cav[num]].setPosition(newPos[num-1],modules[target_cav[num]].getPosition1()); // Cav
/*
cout << "Cav positions.. after" << endl;
for(int i = 0; i < num+1; i++)
{
double x0 = modules[target_cav[i]].getPosition0();
double x1 = modules[target_cav[i]].getPosition1();
cout << "[" << target_cav[i] << "]: x = [ " << x0/1.0e-6 << " / " << x1/1.0e-6 << "] [um] width = " << (x1-x0)/1.0e-9 << " [nm]" << endl;
}
*/
// Reset new storage with the initialize function
for(int i =0; i < num+1; i++)
{
modules[target_cav[i]].getCavity()->initializeZero(DT,VECSEL_transverse_points_number, VECSEL_transverse_points_y, VECSEL_transverse_points_R_max, VECSEL_transverse_points_boundary_guard_ratio);
}
//cout << "sucsess??" << endl;
//exit(-1);
}
void VECSEL::getQWpositions(int num, double **newPos)
{
// Export QW positnions
for(int i = 0; i < num; i++)
{
(*newPos)[i] = modules[quick_index_device[i]].getPosition0();
}
}
/*
Add EMPTY CAVITY
*/
Module * VECSEL::addCavity()
{
// Update number
setNumberCavities(getNumberCavities() + 1);
// Update Quick refrence
quick_index_cavity.push_back(getNumberModules());
// Check if previous cavity is end of two arm structure
if(modules.back().isTwoArmCavity())
{
quick_index_twoArmPostCav.push_back(getNumberModules());
for(unsigned i=0; i<getNumberModules()-1; i++)
{
if(modules[getNumberModules()-1-i].isTwoArmInterface())
{
modules[getNumberModules()-1-i].getTwoArmInterface()->setPostCav(getNumberModules());
break;
}
}
}
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addCavity();
modules.back().setToFileOutputKey(getToFileOutputKey());
return tmp;
}
/*
Copy structure into our currenct structure
*/
void VECSEL::appendStructure(VECSEL *baseStruct)
{
double offset;
if (getNumberModules()>0)
{
offset = modules.back().getPosition1();
} else {
offset = 0.0;
}
// Set transverse data to old cavity
set_transverse_dimensions(baseStruct->getTransversePoints(), baseStruct->getTransverseRmax(), baseStruct->getTransverseBoundaryGuardRatio());
for(int i =0; i < baseStruct->getNumberModules(); i++)
{
// Create a copy
//Module *tmp = addModule();
Module *base = baseStruct->getModule(i);
if (base->isDevice())
{
std::stringstream oldName;
oldName << base->getDevice()->getName();
Module *tmp = addDevice();
tmp->getDevice()->setName(oldName.str());
tmp->setOutputToFile(1);
double pos_y = base->getDevice()->getTransversePosition();
tmp->getDevice()->setTransversePosition(pos_y);
} else if (base->isCavity())
{
double width = base->getWidth();
double n1 = base->getCavity()->getRefInd();
double n2 = base->getCavity()->getRefInd_im();
std::complex<double> nc = n1 + I*n2;
double cos_th_left, cos_th_right;
base->getCavity()->getCosTh(&cos_th_left, &cos_th_right);
addCavity_cos(width, nc, cos_th_left, cos_th_right);
} else if (base->isBoundary())
{
// Boundary info
double ref = base->getBoundary()->getRefCoeff();
double nextN = base->getBoundary()->getNextCavityIndex();
addBoundary(ref,nextN);
} else if (base->isLossElement())
{
// Boundary info
double loss_plus = 0;
double loss_minus = 0;
base->getLossElement()->getLossCoeff(&loss_minus, &loss_plus);
addBoundary(loss_minus,loss_plus);
} else {
cout << "VECSEL::appendStructure(): Unknown module. Not configured for VCAV" << endl;
exit(-1);
}
double x0 = modules.back().getPosition0();
double x1 = modules.back().getPosition1();
modules.back().setPosition(x0+offset,x1+offset);
}
// Set all QWs with the given transverse gain profile
set_transverse_QW_pump_profile_SuperGaussian(baseStruct->getSGPumpDegree(), baseStruct->getSGPumpFWHM());
//set_transverse_QW_temp_profile_SuperGaussian(baseStruct->getSGTempDegree(), baseStruct->getSGTempFWHM());
set_transverse_QW_temp_profile(baseStruct->VECSEL_initial_temp_profile_T);
}
/*
Add TwoArmCAVITY with width and refractive index n1
Position is automatricly set from previous device
*/
Module * VECSEL::addTwoArmCavity(double width, std::complex<double> n1)
{
if (width<=0)
{
cout<<"addTwoArmCavity: Cannot have width<=0. Quitting"<<endl;
exit(-1);
}
if (abs(n1)<=0)
{
cout<<"addTwoArmCavity: Cannot have abs(n1)<=0. Quitting"<<endl;
exit(-1);
}
// Update number
setNumberTwoArmCavities(getNumberTwoArmCavities() + 1);
// Update Quick refrence
quick_index_twoArmCavity.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addTwoArmCavity();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addTwoArmInterface(std::complex<double> n1, double angle_of_incidence, double external_index, double interference_index)
{
if (abs(n1)<=0)
{
cout<<"addTwoArmInterface: Cannot have abs(n1)<=0. Quitting"<<endl;
exit(-1);
}
if (external_index<=0)
{
cout<<"addTwoArmInterface: Cannot have external_index<=0. Quitting"<<endl;
exit(-1);
}
if (interference_index<=0)
{
cout<<"addTwoArmInterface: Cannot have interferenceIndex<=0. Quitting"<<endl;
exit(-1);
}
if (angle_of_incidence<0)
{
cout<<"addTwoArmInterface: Negative angle of incidence untested. Quitting."<<endl;
exit(-1);
}
int indx=getNumberModules();
if (!modules[indx-1].isCavity())
{
cout<<"addTwoArmInterface: Previous modules must be a cavity. Coincident TwoArmStructs untested. Quitting."<<endl;
exit(-1);
}
// Snell's Law. Assumes real refractive indices
double cos_th = sqrt(1.0-external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence)/(real(n1)*real(n1)));
// Update number
setNumberTwoArmInterfaces(getNumberTwoArmInterfaces() + 1);
// Update Quick refrence
quick_index_twoArmInterface.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Two Arm Interface
modules.back().addTwoArmInterface();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
double width = getLambda();
#ifdef TRANS_DELAY
if(angle_of_incidence==0)
{
cout<<"addTwoArmInterface: Cannot use transverse delay with zero angle of incidence. Quitting."<<endl;
exit(-1);
} else
{
width = tan(angle_of_incidence)*(VECSEL_transverse_points_y[VECSEL_transverse_points_number-1]-VECSEL_transverse_points_y[0]);
}
#endif
double angle_of_interference=asin(sin(angle_of_incidence)*external_index/interference_index); //Snell's law
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setCosTh(cos_th,cos_th);
modules.back().setWidth(width);
modules.back().setAngle(angle_of_incidence); //Angle at interface
modules.back().setIntAngle(angle_of_interference); //Angle for interference fringes (scaled by QW refractive index)
modules.back().setPrevCav(getNumberModules()-1);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addBirefringentCrystal(double width, std::complex<double> n1, double extraordinary_n)
{
if (width<=0)
{
cout<<"addBirefringentCrystal: Cannot have width<=0. Quitting"<<endl;
exit(-1);
}
if (abs(n1)<=0)
{
cout<<"addBirefringentCrystal: Cannot have abs(n1)<=0. Quitting"<<endl;
exit(-1);
}
if (getNumberTwoArmCavities()==0)
{
cout<<"addBirefringentCrystal: BRC as first element is untested. Quitting."<<endl;
exit(-1);
}
// Update number
setNumberBirefringentCrystals(getNumberBirefringentCrystals() + 1);
// Update Quick refrence
quick_index_birefringentCrystal.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addBirefringentCrystal();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_extraAxis(extraordinary_n);
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addKerrCrystal(double width, std::complex<double> n1, double n2)
{
if (width<=0)
{
cout<<"addKerrCrystal: Cannot have width<=0. Quitting"<<endl;
exit(-1);
}
if (abs(n1)<=0)
{
cout<<"addKerrCrystal: Cannot have abs(n1)<=0. Quitting"<<endl;
exit(-1);
}
if(abs(n2)<=0)
{
cout<<"addKerrCrystal: Cannot have abs(n2)<=0. Quitting"<<endl;
exit(-1);
}
if (getNumberCavities()==0)
{
cout<<"addKerrCrystal: Kerr crystal as first element is untested. Quitting."<<endl;
exit(-1);
}
// Update number
setNumberKerrCrystals(getNumberKerrCrystals() + 1);
// Update Quick refrence
quick_index_kerrCrystal.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
//modules.back().addCavity();
modules.back().addKerrCrystal();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_n2(n2);
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addTwoArmCavity(double width, std::complex<double> n1, double angle_of_incidence, double external_index)
{
if (width<=0)
{
cout<<"addTwoArmCavity: Cannot have width<=0. Quitting"<<endl;
exit(-1);
}
if (abs(n1)<=0)
{
cout<<"addTwoArmCavity: Cannot have abs(n1)<=0. Quitting"<<endl;
exit(-1);
}
if (external_index<=0)
{
cout<<"addTwoArmCavity: Cannot have external_index<=0. Quitting"<<endl;
exit(-1);
}
if (angle_of_incidence<0)
{
cout<<"addTwoArmCavity: Negative angle of incidence untested. Quitting."<<endl;
exit(-1);
}
// Snell's Law. Assumes real refractive indices
double cos_th = sqrt(1.0-external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence)/(real(n1)*real(n1)));
//width = width/cos_th;
// Update number
setNumberTwoArmCavities(getNumberTwoArmCavities() + 1);
// Update Quick refrence
quick_index_twoArmCavity.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addTwoArmCavity();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setCosTh(cos_th,cos_th);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addTwoArmCavity_cos(double width, std::complex<double> n1, double cos_th_left, double cos_th_right)
{
if (width<=0)
{
cout<<"addTwoArmCavity: Cannot have width<=0. Quitting"<<endl;
exit(-1);
}
if (abs(n1)<=0)
{
cout<<"addTwoArmCavity: Cannot have abs(n1)<=0. Quitting"<<endl;
exit(-1);
}
// Update number
setNumberTwoArmCavities(getNumberTwoArmCavities() + 1);
// Update Quick refrence
quick_index_twoArmCavity.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addTwoArmCavity();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setCosTh(cos_th_left, cos_th_right);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
/*
Add CAVITY with width and refractive index n1
Position is automatricly set from previous device
*/
Module * VECSEL::addCavity(double width, std::complex<double> n1)
{
// Update number
setNumberCavities(getNumberCavities() + 1);
// Update Quick refrence
quick_index_cavity.push_back(getNumberModules());
// Check if previous cavity is end of two arm structure
if(modules.back().isTwoArmCavity())
{
quick_index_twoArmPostCav.push_back(getNumberModules());
for(unsigned i=0; i<getNumberModules()-1; i++)
{
if(modules[getNumberModules()-1-i].isTwoArmInterface())
{
modules[getNumberModules()-1-i].getTwoArmInterface()->setPostCav(getNumberModules());
break;
}
}
}
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addCavity();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addCavity(double width, std::complex<double> n1, double angle_of_incidence, double external_index)
{
// Snell's Law. Assumes real refractive indices
double cos_th = sqrt(1.0-external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence)/(real(n1)*real(n1)));
//width = width/cos_th;
// Update number
setNumberCavities(getNumberCavities() + 1);
// Update Quick refrence
quick_index_cavity.push_back(getNumberModules());
// Check if previous cavity is end of two arm structure
if(modules.back().isTwoArmCavity())
{
quick_index_twoArmPostCav.push_back(getNumberModules());
for(unsigned i=0; i<getNumberModules()-1; i++)
{
if(modules[getNumberModules()-1-i].isTwoArmInterface())
{
modules[getNumberModules()-1-i].getTwoArmInterface()->setPostCav(getNumberModules());
break;
}
}
}
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addCavity();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setCosTh(cos_th,cos_th);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addCavity_aperture(double width, std::complex<double> n1, double angle_of_incidence, double external_index, double aperture_fwhm_ratio)
{
// Snell's Law. Assumes real refractive indices
double cos_th = sqrt(1.0-external_index*external_index*sin(angle_of_incidence)*sin(angle_of_incidence)/(real(n1)*real(n1)));
//width = width/cos_th;
// Update number
setNumberCavities(getNumberCavities() + 1);
// Update Quick refrence
quick_index_cavity.push_back(getNumberModules());
// Check if previous cavity is end of two arm structure
if(modules.back().isTwoArmCavity())
{
quick_index_twoArmPostCav.push_back(getNumberModules());
for(unsigned i=0; i<getNumberModules()-1; i++)
{
if(modules[getNumberModules()-1-i].isTwoArmInterface())
{
modules[getNumberModules()-1-i].getTwoArmInterface()->setPostCav(getNumberModules());
break;
}
}
}
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addCavity();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setAperture(aperture_fwhm_ratio);
modules.back().setCosTh(cos_th,cos_th);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addCavity_cos(double width, std::complex<double> n1, double cos_th_left, double cos_th_right)
{
// Update number
setNumberCavities(getNumberCavities() + 1);
// Update Quick refrence
quick_index_cavity.push_back(getNumberModules());
// Check if previous cavity is end of two arm structure
if(modules.back().isTwoArmCavity())
{
quick_index_twoArmPostCav.push_back(getNumberModules());
for(unsigned i=0; i<getNumberModules()-1; i++)
{
if(modules[getNumberModules()-1-i].isTwoArmInterface())
{
modules[getNumberModules()-1-i].getTwoArmInterface()->setPostCav(getNumberModules());
break;
}
}
}
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addCavity();
double pos = 0;
if (getNumberModules() > 1) // It self + others
{
// Set position to previous device
pos = modules[getNumberModules()-2].getPosition1();
}
modules.back().setRefInd(real(n1));
modules.back().setRefInd_im(imag(n1));
modules.back().setWidth(width);
modules.back().setCosTh(cos_th_left, cos_th_right);
modules.back().setToFileOutputKey(getToFileOutputKey());
modules.back().setPosition(pos, pos + width);
return tmp;
}
Module * VECSEL::addDevice()
{
// Update Number of devices
setNumberDevices(getNumberDevices() + 1);
// Update Quick refrence
quick_index_device.push_back(getNumberModules());
// Update Quick refrence
quick_index_totalDevice.push_back(getNumberModules());
// Update Quick refrence
int prev_cav_index;
for(int i = getNumberModules()-1; i>=0; i--)
{
if (modules[i].isCavity())
{
prev_cav_index = i;
break;
}
}
quick_index_device_previous_cavity.push_back(prev_cav_index);
// Add new module
Module *tmp = addModule();
// Add device
modules.back().addDevice();
if (getNumberModules() <= 1)
{
cout << "VECSEL::addDevice(): Need boundary & cavity on the far left of VECSEL" << endl;
exit(-1);
} else if (getNumberModules() > 1)
{
// Set position to previous device
double pos = modules[getNumberModules()-2].getPosition1();
modules.back().setPosition(pos, pos);
modules.back().setToFileOutputKey(getToFileOutputKey());
}
return tmp;
}
Module * VECSEL::addTwoArmDevice()
{
// Update Number of devices
setNumberTwoArmDevices(getNumberTwoArmDevices() + 1);
// Update Quick refrence
quick_index_twoArmDevice.push_back(getNumberModules());
// Update Quick refrence
quick_index_totalDevice.push_back(getNumberModules());
// Update Quick refrence
int prev_cav_index;
for(int i = getNumberModules()-1; i>=0; i--)
{
if (modules[i].isTwoArmCavity())
{
prev_cav_index = i;
break;
}
}
quick_index_device_previous_cavity.push_back(prev_cav_index);
// Add new module
Module *tmp = addModule();
// Add device
modules.back().addTwoArmDevice();
if (getNumberModules() <= 1)
{
cout << "VECSEL::addTwoArmDevice(): Need boundary & cavity on the far left of VECSEL" << endl;
exit(-1);
} else if (getNumberModules() > 1)
{
// Set position to previous device
double pos = modules[getNumberModules()-2].getPosition1();
modules.back().setPosition(pos, pos);
modules.back().setToFileOutputKey(getToFileOutputKey());
}
return tmp;
}
Module * VECSEL::addBoundary()
{
// Update number
setNumberBoundaries(getNumberBoundaries() + 1);
// Update Quick refrence
quick_index_boundary.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addBoundary();
if (getNumberModules() > 1)
{
// Set position to previous device
double pos = modules[getNumberModules()-2].getPosition1();
modules.back().setPosition(pos, pos);
}
return tmp;
}
Module * VECSEL::addBoundary(double refCoeff, double next_cavity_index)
{
// Update number
setNumberBoundaries(getNumberBoundaries() + 1);
// Update Quick refrence
quick_index_boundary.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addBoundary(refCoeff);
modules.back().getBoundary()->setNextCavityIndex(next_cavity_index);
if (getNumberModules() > 1)
{
// Set position to previous device
double pos = modules[getNumberModules()-2].getPosition1();
modules.back().setPosition(pos, pos);
}
return tmp;
}
Module * VECSEL::addLossElement()
{
// Update number
//setNumberBoundaries(getNumberBoundaries() + 1);
// Update Quick refrence
//quick_index_boundary.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addLossElement();
if (getNumberModules() > 1)
{
// Set position to previous device
double pos = modules[getNumberModules()-2].getPosition1();
modules.back().setPosition(pos, pos);
}
return tmp;
}
Module * VECSEL::addLossElement(double loss_minus, double loss_plus)
{
// Update number
//setNumberBoundaries(getNumberBoundaries() + 1);
// Update Quick refrence
//quick_index_boundary.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addLossElement(loss_minus, loss_plus);
if (getNumberModules() > 1)
{
// Set position to previous device
double pos = modules[getNumberModules()-2].getPosition1();
modules.back().setPosition(pos, pos);
}
return tmp;
}
Module * VECSEL::addFilter(int numEl)
{
// Update number
//setNumberBoundaries(getNumberBoundaries() + 1);
// Update Quick refrence
//quick_index_boundary.push_back(getNumberModules());
// Add new module
Module *tmp = addModule();
// Add Cavity
modules.back().addFilter(numEl);
if (getNumberModules() > 1)
{
// Set position to previous device
double pos = modules[getNumberModules()-2].getPosition1();
modules.back().setPosition(pos, pos);
}
return tmp;
}
Module * VECSEL::addModule()
{
//Module *tmp = new Module(); // Initialize to NULL
//modules.push_back(*tmp);
modules.push_back(Module()); // Temporary object is copied in
return &modules.back();
}
//=======================================
// File IO functions and their helpers
/* Remove all output files from devices */
void VECSEL::file_output_device_disable()
{
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
modules[indx].setOutputToFile(0);
}
#endif
}
/* Reduce output files from devices by turning off output outside a given region */
void VECSEL::file_output_device_reduce(double x_max)
{
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
double trans_x;
if (modules[indx].isDevice())
{
trans_x = modules[indx].getDevice()->getTransversePosition();
} else
{
trans_x = modules[indx].getTwoArmDevice()->getTransversePosition();
}
if (abs(trans_x) < x_max/2.0)
{
modules[indx].setOutputToFileLevel(1);
modules[indx].setOutputToFile(1);
} else {
modules[indx].setOutputToFile(0); // No output outside of range
}
}
#endif
}
/* Set output frequency for devices y = 0, y = +/- dx, y +/- 2*dx, ... inside the rangle [-x_max/2, x_max/2] */
void VECSEL::file_output_device_set_freq(double output_frequency, double x_max, int twoArmDevice_OutputLevel, int device_OutputLevel)
{
if (output_frequency <= 0.0)
{
cout << "VECSEL::file_output_device_set_freq() Error. Cannot have 'output_frequency' <= 0" << endl;
cout << "output_frequency = " << output_frequency << endl;
exit(-1);
} else if (x_max <= 0.0)
{
cout << "VECSEL::file_output_device_set_freq() Error. Cannot have 'x_max' <= 0" << endl;
cout << "x_max = " << x_max << endl;
exit(-1);
} else if (x_max >= VECSEL_transverse_points_R_max)
{
cout << "VECSEL::file_output_device_set_freq() Error. Cannot have 'x_max' > domain size" << endl;
cout << "x_max = " << x_max << endl;
cout << "domain size = " << VECSEL_transverse_points_R_max << endl;
exit(-1);
} else if ((output_frequency < VECSEL_transverse_points_y[1]-VECSEL_transverse_points_y[0]) && VECSEL_transverse_points_number>1)
{
cout << "VECSEL::file_output_device_set_freq() Error. Cannot have 'output_frequency' faster than resolution" << endl;
cout << "output_frequency = " << output_frequency << endl;
cout << "domain resolution = " << VECSEL_transverse_points_y[1]-VECSEL_transverse_points_y[0] << endl;
exit(-1);
} else if (0.5*x_max <= output_frequency)
{
cout << "VECSEL::file_output_device_set_freq() Error. Cannot have 'output_frequency' longer than '0.5*x_max'" << endl;
cout << "0.5*x_max = " << 0.5*x_max << endl;
cout << "output_frequency = " << output_frequency << endl;
exit(-1);
}
#ifdef ITERATE_QW
// Turn off all output
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
if (modules[indx].isDevice())
{
double trans_x = modules[indx].getDevice()->getTransversePosition();
} else
{
double trans_x = modules[indx].getTwoArmDevice()->getTransversePosition();
}
modules[indx].setOutputToFile(0);
}
// Turn on output only for given devices
int MAX_OUTPUT = floor(0.5*x_max/output_frequency);
VECSEL_transverse_points_device_number = 1+2*(MAX_OUTPUT-1);
if (VECSEL_transverse_points_device_y == NULL)
{
VECSEL_transverse_points_device_y = new double[VECSEL_transverse_points_device_number];
}
for (int i = 0; i < MAX_OUTPUT; i++)
{
double output_x_p = +i*output_frequency;
int min_indx_p, min_indx_m;
double min_v;
if (abs(output_x_p) <= x_max/2.0)
{
min_indx_p = -1;
min_v = 1e99;
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
if (abs(VECSEL_transverse_points_y[j]-output_x_p) < min_v)
{
min_indx_p = j;
min_v = abs(VECSEL_transverse_points_y[j]-output_x_p);
}
}
if (min_indx_p >= 0)
{
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
double trans_x;
if (modules[indx].isDevice())
{
trans_x = modules[indx].getDevice()->getTransversePosition();
if (trans_x-VECSEL_transverse_points_y[min_indx_p] == 0)
{
// Set output to file
modules[indx].setOutputToFile(device_OutputLevel);
modules[indx].setOutputToFileLevel(device_OutputLevel);
}
} else
{
trans_x = modules[indx].getTwoArmDevice()->getTransversePosition();
if (trans_x-VECSEL_transverse_points_y[min_indx_p] == 0)
{
// Set output to file
modules[indx].setOutputToFile(twoArmDevice_OutputLevel);
modules[indx].setOutputToFileLevel(twoArmDevice_OutputLevel);
}
}
}
} else {
cout << "VECSEL::file_output_device_set_freq() Cannot find a QW in range [0, x_max/2] closer than max" << endl;
exit(-1);
}
}
double output_x_m = -i*output_frequency;
if (abs(output_x_m) <= x_max/2.0)
{
min_indx_m = -1;
min_v = 1e99;
for(int j = 0; j < VECSEL_transverse_points_number; j++)
{
if (abs(VECSEL_transverse_points_y[j]-output_x_m) < min_v)
{
min_indx_m = j;
min_v = abs(VECSEL_transverse_points_y[j]-output_x_m);
}
}
if (min_indx_m >= 0)
{
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
double trans_x;
if (modules[indx].isDevice())
{
trans_x = modules[indx].getDevice()->getTransversePosition();
if (trans_x-VECSEL_transverse_points_y[min_indx_m] == 0)
{
// Set output to file
modules[indx].setOutputToFile(device_OutputLevel);
modules[indx].setOutputToFileLevel(device_OutputLevel);
}
} else
{
trans_x = modules[indx].getTwoArmDevice()->getTransversePosition();
if (trans_x-VECSEL_transverse_points_y[min_indx_m] == 0)
{
// Set output to file
modules[indx].setOutputToFile(twoArmDevice_OutputLevel);
modules[indx].setOutputToFileLevel(twoArmDevice_OutputLevel);
}
}
}
} else {
cout << "VECSEL::file_output_device_set_freq() Cannot find a QW in range [-x_max/2, 0] closer than max" << endl;
exit(-1);
}
}
if (i==0)
{
VECSEL_transverse_points_device_y[MAX_OUTPUT-1] = VECSEL_transverse_points_y[min_indx_p];
} else{
if (abs(output_x_p) <= x_max/2.0)
{
VECSEL_transverse_points_device_y[MAX_OUTPUT-1+i] = VECSEL_transverse_points_y[min_indx_p];
}
if (abs(output_x_m) <= x_max/2.0)
{
VECSEL_transverse_points_device_y[MAX_OUTPUT-1-i] = VECSEL_transverse_points_y[min_indx_m];
}
}
}
std::stringstream fileName;
fileName.str("");
fileName << getToFileOutputKey() << "transverse_grid_device_y.dat";
saveBinary(fileName.str(), VECSEL_transverse_points_device_y, VECSEL_transverse_points_device_number);
#endif
}
/* Write the given cavity structure to file
* Each row represents a module
*
* Output format:
* 1st column: What type are we talking about
* -> 0 is boundary
* -> 1 is cavity
* -> 2 is device
* -> 3 is everything else
* 2nd column: Position of first vertex
* 3rd column: Position of second vertex
* 4th column: Refractive index if a cavity. else -1
* */
void VECSEL::file_output_structure(void)
{
if (MPI_MY_RANK==0)
{
std::ofstream printStruc;
std::cout.precision(5);
std::stringstream fileName;
fileName << getToFileOutputKey() << "system_structure.dat";
printStruc.open((fileName.str()).c_str(),std::ofstream::out);
for(unsigned i = 0; i < getNumberModules(); i++)
{
if (modules[i].isBoundary())
{
printStruc << std::fixed << std::setprecision(16) << 0 << " " << modules[i].getPosition0() << " " << modules[i].getPosition1() << " " << "-1" << endl;
}
if (modules[i].isCavity())
{
printStruc << std::fixed << std::setprecision(16) << 1 << " " << modules[i].getPosition0() << " " << modules[i].getPosition1() << " " << modules[i].getRefInd() << endl;
}
if (modules[i].isTwoArmInterface())
{
printStruc << std::fixed << std::setprecision(16) << 1 << " " << modules[i].getPosition0() << " " << modules[i].getPosition1() << " " << modules[i].getRefInd() << endl;
}
if (modules[i].isTwoArmCavity())
{
printStruc << std::fixed << std::setprecision(16) << 1 << " " << modules[i].getPosition0() << " " << modules[i].getPosition1() << " " << modules[i].getRefInd() << endl;
}
if (modules[i].isDevice())
{
int indx0 = i;
int indx1 = i;
while (modules[indx0].isCavity())
{
indx0--;
if (indx0 < 0)
{
cout << "VECSEL::file_output_structure() cannot find previous cavity" << endl;
}
}
while (modules[indx1].isCavity())
{
indx1++;
if (indx1 < 0)
{
cout << "VECSEL::file_output_structure() cannot find next cavity" << endl;
}
}
double position_x0 = modules[indx0].getPosition1();
double position_x1 = modules[indx1].getPosition0();
printStruc << std::fixed << std::setprecision(16) << 2 << " " << position_x0 << " " << position_x1 << " " << "-1" << endl;
}
if (modules[i].isTwoArmDevice())
{
int indx0 = i;
int indx1 = i;
while (modules[indx0].isTwoArmCavity())
{
indx0--;
if (indx0 < 0)
{
cout << "VECSEL::file_output_structure() cannot find previous cavity" << endl;
}
}
while (modules[indx1].isTwoArmCavity())
{
indx1++;
if (indx1 < 0)
{
cout << "VECSEL::file_output_structure() cannot find next cavity" << endl;
}
}
double position_x0 = modules[indx0].getPosition1();
double position_x1 = modules[indx1].getPosition0();
printStruc << std::fixed << std::setprecision(16) << 2 << " " << position_x0 << " " << position_x1 << " " << "-1" << endl;
}
// if (modules[i].isDevice())
// {
// printStruc << std::fixed << std::setprecision(16) << 2 << " " << modules[i].getPosition0() << " " << modules[i].getPosition1() << " " << "-1" << endl;
// }
if (modules[i].isLossElement())
{
printStruc << std::fixed << std::setprecision(16) << 3 << " " << modules[i].getPosition0() << " " << modules[i].getPosition1() << " " << "-1" << endl;
}
}
printStruc.close();
}
}
/* Open all output files everywhere */
void VECSEL::file_output_open_all(int out_count)
{
if (MPI_MY_RANK==0)
{
// Open global stuff
file_output_open(out_count);
for(unsigned i=0; i<getNumberModules(); i++)
{
if (!(modules[i].isDevice()||modules[i].isTwoArmDevice()))
{
modules[i].file_output_open(out_count);
}
}
}
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
modules[indx].file_output_open(out_count);
}
#endif
}
/* Close all output files everywhere */
void VECSEL::file_output_close_all()
{
if (MPI_MY_RANK==0)
{
// Close global stuff
file_output_close();
for(unsigned i=0; i<getNumberModules(); i++)
{
if (!(modules[i].isDevice()||modules[i].isTwoArmDevice()))
{
modules[i].file_output_close();
}
}
}
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
modules[indx].file_output_close();
}
#endif
}
/* Write to all output files everywhere */
void VECSEL::file_output_write_all(double t_sim)
{
if (MPI_MY_RANK==0)
{
// Output global stuff
file_output_write(t_sim);
// For output of Cavities
for(unsigned i=0; i<getNumberModules(); i++)
{
if (!(modules[i].isDevice()||modules[i].isTwoArmDevice()))
{
modules[i].file_output_write();
}
}
}
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
modules[indx].file_output_write();
}
#endif
}
/* Save dynamic variables to files everywhere */
void VECSEL::file_save_variables(int save_count, int offset)
{
// Iterate cavities
int cav_num = 1;
int filt_num = 1;
if (MPI_MY_RANK==0)
{
for(unsigned i=0; i<getNumberModules(); i++)
{
if (modules[i].isCavity())
{
modules[i].getCavity()->file_save_variables(save_count, offset+cav_num); // Simulation variables
cav_num++;
} else if (modules[i].isTwoArmInterface())
{
modules[i].getTwoArmInterface()->file_save_variables(save_count, offset+cav_num); // Simulation variables
cav_num++;
} else if (modules[i].isTwoArmCavity())
{
modules[i].getTwoArmCavity()->file_save_variables(save_count, offset+cav_num); // Simulation variables
cav_num++;
} else if (modules[i].isFilter())
{
modules[i].getFilter()->file_save_variables(save_count,offset+filt_num); // Simulation variables
filt_num++;
}
}
}
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
int dev_num = j+1;
if (modules[indx].isDevice())
{
modules[indx].getDevice()->file_save_variables(save_count,offset+dev_num); // Simulation variables
} else
{
modules[indx].getTwoArmDevice()->file_save_variables(save_count,offset+dev_num); // Simulation variables
}
//dev_num++;
}
#endif
}
/* Load dyanmic variables from files everywhere */
void VECSEL::file_load_variables(int save_count, int offset)
{
// Iterate cavities
int cav_num = 1;
int filt_num = 1;
if (MPI_MY_RANK==0)
{
for(unsigned i=0; i<getNumberModules(); i++)
{
if (modules[i].isCavity())
{
modules[i].getCavity()->file_load_variables(save_count, offset+cav_num); // Simulation variables
cav_num++;
} else if (modules[i].isTwoArmCavity())
{
modules[i].getTwoArmCavity()->file_load_variables(save_count, offset+cav_num); // Simulation variables
cav_num++;
} else if (modules[i].isTwoArmInterface())
{
modules[i].getTwoArmInterface()->file_load_variables(save_count, offset+cav_num); // Simulation variables
cav_num++;
} else if (modules[i].isFilter())
{
modules[i].getFilter()->file_load_variables(save_count, offset+filt_num); // Simulation variables
filt_num++;
}
}
}
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
int dev_num = j+1;
if (modules[indx].isDevice())
{
modules[indx].getDevice()->file_load_variables(save_count, offset+dev_num); // Simulation variables
} else
{
modules[indx].getTwoArmDevice()->file_load_variables(save_count, offset+dev_num); // Simulation variables
}
//dev_num++;
}
#endif
}
/* Load carriers from files at a spesific time in all devices
* output_name gives the target output name
* t_T is the requested time to load carriers at
* */
void VECSEL::file_load_device_carriers_time(const std::string &output_name, double t_T)
{
// Find line corresponding to target time from files with output_name
// Look through the files: output_name__*_t.dat for the correct file
int fileNum = -1; // Start looking at file = 0
int lineNum = -1;
std::stringstream fileName;
fileName << output_name << "0_t.dat";
double tmp;
double *t_int = new double[2];
while (fileExists(fileName.str()))
{
// Load file and check if it containes t_T
int tmpLines = detectNumberOfLines(fileName.str(), &tmp, 1);
loadBinaryLine(fileName.str(), &t_int[0], 1, 1);
loadBinaryLine(fileName.str(), &t_int[1], 1, tmpLines);
if ((t_int[0] <= t_T)&&(t_T <= t_int[1]))
{
double *allT = new double[tmpLines];
loadBinary(fileName.str(), allT, tmpLines);
int targetLine = 0;
double minT = 1.0;
for(int j = 0; j < tmpLines; j++)
{
if (abs(t_T - allT[j]) < minT)
{
targetLine = j;
minT = abs(t_T - allT[j]);
}
}
targetLine++; // Compensate for array index to line #
cout << "Found in file = " << fileName.str() << endl;
cout << "Target time = " << t_T/ps << " [ps]" << endl;
cout << "Found index = " << targetLine << " / " << tmpLines << endl;
cout << "Deviation time = " << abs(allT[targetLine-1] - t_T)/fs << " [fs]" << endl;
delete allT;
lineNum = targetLine;
}
// Check next file
fileNum++;
fileName.str("");
fileName << output_name << fileNum << "_t.dat";
if (lineNum != -1)
{
break;
}
}
if (fileNum == -1)
{
cout << "file_load_device_carriers_time(): Could not find requested file " << endl;
cout << "fileName = " << fileName.str() << endl;
exit(-1);
}
if (lineNum==-1)
{
cout << "file_load_device_carriers_time(): Could not find requested time " << endl;
cout << "Time = " << t_T << endl;
exit(-1);
}
file_load_device_carriers_line(output_name, fileNum, lineNum);
}
/* Load device carriers from a given line of output file */
void VECSEL::file_load_device_carriers_line(int out_count, int line_num)
{
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
if (modules[indx].isDevice())
{
modules[indx].getDevice()->file_load_carriers_line(out_count,line_num); // Simulation variables
} else
{
modules[indx].getTwoArmDevice()->file_load_carriers_line(out_count,line_num); // Simulation variables
}
}
#endif
}
/* Load device carriers from save point */
void VECSEL::file_load_device_carriers(int out_count)
{
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
int dev_num = j+1;
if (modules[indx].isDevice())
{
modules[indx].getDevice()->file_load_carriers(out_count,dev_num); // Simulation variables
} else
{
modules[indx].getTwoArmDevice()->file_load_carriers(out_count,dev_num); // Simulation variables
}
dev_num++;
}
#endif
}
/* Load device carriers from a given line of output file */
void VECSEL::file_load_device_carriers_line(const std::string &output_name, int out_count, int line_num)
{
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
if (modules[indx].isDevice())
{
modules[indx].getDevice()->file_load_carriers_line(output_name,out_count,line_num); // Simulation variables
} else
{
modules[indx].getTwoArmDevice()->file_load_carriers_line(output_name,out_count,line_num); // Simulation variables
}
}
#endif
}
/* Load device carriers from an ascii file in a directory
* line_num is the folder identifier
* */
void VECSEL::file_load_device_carriers_ascii(int line_num)
{
// Iterate cavities
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
int dev_num = j+1;
if (modules[indx].isDevice())
{
modules[indx].getDevice()->file_load_carriers_ascii(dev_num, line_num); // Simulation variables
} else
{
modules[indx].getTwoArmDevice()->file_load_carriers_ascii(dev_num, line_num); // Simulation variables
}
dev_num++;
}
#endif
cout << "file_load_device_carriers_ascii: Load line " << line_num << " Complete" << endl;
}
/* Write output to output files
* t_sim is the current simulation time
* */
void VECSEL::file_output_write(double t_sim)
{
if (MPI_MY_RANK==0)
{
output_simulation_time.write(reinterpret_cast<const char*>(&t_sim),sizeof(double));
#ifdef USE_CAVITY_SNAPSHOT
if (VECSEL_cav_snapshot_output_count >= VECSEL_cav_snapshot_output_wait)
{
file_snapshot_write(t_sim);
VECSEL_cav_snapshot_output_count = 0;
} else {
VECSEL_cav_snapshot_output_count++;
}
#endif
#ifdef DUAL_PROP
if(true) //(modules[0].isBoundary() && VECSEL_pulse_start_l == 1)
{
/*==============================
Output of device on LEFT
==============================*/
int indx = quick_index_twoArmCavity[0]; // Final cavity
double rR = modules[0].getBoundary()->getRefCoeff(); // Right boundary
double ni = modules[indx].getRefInd();
std::complex<double> E_bp[VECSEL_transverse_points_number];
std::complex<double> E_bm[VECSEL_transverse_points_number];
std::complex<double> E_prop;
modules[indx].getTwoArmCavity()->getEbp_front_wall(E_bp);
modules[indx].getTwoArmCavity()->getEbm_front_wall(E_bm);
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
// output
E_prop=E_bp[i];
double tmp = real(sqrt(ni*(1.0-rR))*E_prop);
output_E_real[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
tmp = imag(sqrt(ni*(1.0-rR))*E_prop);
output_E_imag[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
E_prop=E_bm[i];
tmp = real(sqrt(ni*(1.0-rR))*E_prop);
output_back_E_real[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
tmp = imag(sqrt(ni*(1.0-rR))*E_prop);
output_back_E_imag[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
}
}
#elif defined DUAL_CHIP
if(true) //(modules[0].isBoundary() && VECSEL_pulse_start_l == 1)
{
/*==============================
Output of device on LEFT
==============================*/
int indx_int = quick_index_twoArmInterface[0]; // Final cavity
int indx_back = modules[indx_int].getTwoArmInterface()->getPostCav()-1;
std::complex<double> rR = modules[indx_int].getTwoArmInterface()->getReflect(); // Right boundary
std::complex<double> ni = modules[indx_back].getRefInd();
std::complex<double> E_fp[VECSEL_transverse_points_number];
std::complex<double> E_fm[VECSEL_transverse_points_number];
std::complex<double> E_prop;
modules[indx_back].getTwoArmCavity()->getEfp_back_wall(E_fp);
modules[indx_back].getTwoArmCavity()->getEfm_back_wall(E_fm);
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
// output
E_prop=E_fp[i];
double tmp = real(sqrt(ni*(1.0-rR))*E_prop);
output_E_real[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
tmp = imag(sqrt(ni*(1.0-rR))*E_prop);
output_E_imag[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
E_prop=E_fm[i];
tmp = real(sqrt(ni*(1.0-rR))*E_prop);
output_back_E_real[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
tmp = imag(sqrt(ni*(1.0-rR))*E_prop);
output_back_E_imag[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
}
}
#else
if(VECSEL_output_left) //(modules[0].isBoundary() && VECSEL_pulse_start_l == 1)
{
/*==============================
Output of device on LEFT
==============================*/
int indx = quick_index_cavity[0]; // Final cavity
double rR = modules[0].getBoundary()->getRefCoeff(); // Right boundary
double ni = modules[indx].getRefInd();
std::complex<double> E_prop[VECSEL_transverse_points_number];
//std::complex<double> E_plus[VECSEL_transverse_points_number];
//std::complex<double> E_minus[VECSEL_transverse_points_number];
modules[indx].getCavity()->getEminus_left_wall(E_prop);
//modules[indx].getCavity()->getEminus_right_wall(E_minus);
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
// output
double tmp = real(sqrt(ni*(1.0-rR))*E_prop[i]);
output_E_real[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
tmp = imag(sqrt(ni*(1.0-rR))*E_prop[i]);
output_E_imag[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
}
}
if(VECSEL_output_right) //(modules.back().isBoundary() && VECSEL_pulse_start_r ==1)
{
/*==============================
Output of device on RIGHT
==============================*/
int indx = quick_index_cavity.back(); // Final cavity
double rR = modules.back().getBoundary()->getRefCoeff(); // Right boundary
double ni = modules[indx].getRefInd();
std::complex<double> E_prop[VECSEL_transverse_points_number];
//std::complex<double> E_plus[VECSEL_transverse_points_number];
//std::complex<double> E_minus[VECSEL_transverse_points_number];
modules[indx].getCavity()->getEpluss_right_wall(E_prop);
//modules[indx].getCavity()->getEminus_right_wall(E_minus);
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
// output
double tmp = real(sqrt(ni*(1.0-rR))*E_prop[i]);
output_back_E_real[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
tmp = imag(sqrt(ni*(1.0-rR))*E_prop[i]);
output_back_E_imag[i].write(reinterpret_cast<const char*>(&tmp),sizeof(double));
}
}
#endif
}
}
/* Initialize output files, open with correct numbering
* out_count is the output identification number
* */
void VECSEL::file_output_open(int out_count)
{
if (MPI_MY_RANK==0)
{
// Setup output to files
std::stringstream baseName;
baseName << getToFileOutputKey() << out_count;
std::stringstream fileName;
fileName << baseName.str() << "_t.dat";
//output_simulation_time.open((fileName.str()).c_str(), std::ofstream::out|std::ofstream::binary|std::ofstream::app);
openAppendBinary(&output_simulation_time, fileName.str());
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
if(VECSEL_output_left)//( VECSEL_pulse_start_l == 1 )
{
fileName.str("");
fileName << baseName.str() << "_E_re_OUTPUT_T" << i << ".dat";
openAppendBinary(&output_E_real[i], fileName.str());
fileName.str("");
fileName << baseName.str() << "_E_im_OUTPUT_T" << i << ".dat";
openAppendBinary(&output_E_imag[i], fileName.str());
}
if(VECSEL_output_right)//( VECSEL_pulse_start_r == 1)
{
fileName.str("");
fileName << baseName.str() << "_E_re_OUTPUTBACK_T" << i << ".dat";
openAppendBinary(&output_back_E_real[i], fileName.str());
fileName.str("");
fileName << baseName.str() << "_E_im_OUTPUTBACK_T" << i << ".dat";
openAppendBinary(&output_back_E_imag[i], fileName.str());
}
}
#ifdef USE_CAVITY_SNAPSHOT
VECSEL_cav_snapshot_output_count = VECSEL_cav_snapshot_output_wait;
fileName.str("");
fileName << baseName.str() << "_cav_snapshot_t.dat";
openAppendBinary(&output_Cav_Snapshot_t, fileName.str());
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
fileName.str("");
fileName << baseName.str() << "_cav_snapshot_E_re_T"<< i <<".dat";
openAppendBinary(&output_Cav_Snapshot_E_real[i], fileName.str());
fileName.str("");
fileName << baseName.str() << "_cav_snapshot_E_im_T"<< i <<".dat";
openAppendBinary(&output_Cav_Snapshot_E_imag[i], fileName.str());
}
#endif
}
}
/* Close all output files */
void VECSEL::file_output_close()
{
if (MPI_MY_RANK==0)
{
output_simulation_time.close();
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
if(VECSEL_output_left) //( VECSEL_pulse_start_l == 1)
{
output_E_real[i].close();
output_E_imag[i].close();
}
if(VECSEL_output_right) //( VECSEL_pulse_start_r == 1)
{
output_back_E_real[i].close();
output_back_E_imag[i].close();
}
}
#ifdef USE_CAVITY_SNAPSHOT
output_Cav_Snapshot_t.close();
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
output_Cav_Snapshot_E_real[i].close();
output_Cav_Snapshot_E_imag[i].close();
}
#endif
}
}
/* Print out the field in the z-direction in the cavity
* Requires alot of calculations, so takes a long time
* VECSEL_cav_snapshot_num_points: Sets number of z-points to print at
* */
void VECSEL::file_snapshot_write(double t)
{
cout << "VECSEL::file_snapshot_write() Snapshot not updated for transverse dimensions.." << endl;
exit(-1);
/*
for(int i = 0; i < VECSEL_cav_snapshot_num_points; i++)
{
int indx = VECSEL_cav_snapshot_index[i]; // Find correct cavity
VECSEL_cav_snapshot_E[i] = modules[indx].getCavity()->evaluateEprop(VECSEL_cav_snapshot_x[i]);
VECSEL_cav_snapshot_E_re[i] = real(VECSEL_cav_snapshot_E[i]);
VECSEL_cav_snapshot_E_im[i] = imag(VECSEL_cav_snapshot_E[i]);
}
output_Cav_Snapshot_E_real.write(reinterpret_cast<const char*>(VECSEL_cav_snapshot_E_re),VECSEL_cav_snapshot_num_points*sizeof(double));
output_Cav_Snapshot_E_imag.write(reinterpret_cast<const char*>(VECSEL_cav_snapshot_E_im),VECSEL_cav_snapshot_num_points*sizeof(double));
output_Cav_Snapshot_t.write(reinterpret_cast<const char*>(&t),sizeof(double));
*/
}
/* Print out ONLY ONCE the field in the z-direction in the cavity
* Requires alot of calculations, so takes a long time
* VECSEL_cav_snapshot_num_points: Sets number of z-points to print at
* */
void VECSEL::file_snapshot_write_single(int ID, int NUM_POINTS)
{
cout << "VECSEL::file_snapshot_write_single() Snapshot not updated for transverse dimensions.." << endl;
exit(-1);
/*
std::stringstream fileName;
std::stringstream baseName;
baseName << getToFileOutputKey() << ID;
fileName << baseName.str() << "_cav_snapshot_E_re.dat";
openAppendBinary(&output_Cav_Snapshot_E_real, fileName.str());
fileName.str("");
fileName << baseName.str() << "_cav_snapshot_E_im.dat";
openAppendBinary(&output_Cav_Snapshot_E_imag, fileName.str());
//=================
// Compute x, data
//=================
baseName.str("");
baseName << getToFileOutputKey() << ID;
fileName.str("");
fileName << baseName.str() << "_cav_snapshot_x.dat";
openAppendBinary(&output_Cav_Snapshot_x, fileName.str());
double DX = (modules.back().getPosition1() - modules[0].getPosition0())/((double)NUM_POINTS);
#ifndef USE_CAVITY_SNAPSHOT
//VECSEL_cav_snapshot_x = new double[NUM_POINTS];
#endif
for(int i =0; i < NUM_POINTS; i++)
{
VECSEL_cav_snapshot_x[i] = modules[0].getPosition0() + ((double)i+0.5)*DX;
}
output_Cav_Snapshot_x.write(reinterpret_cast<const char*>(&VECSEL_cav_snapshot_x[0]),NUM_POINTS*sizeof(double));
output_Cav_Snapshot_x.close();
// Find correct indices
#ifndef USE_CAVITY_SNAPSHOT
//VECSEL_cav_snapshot_index = new int[NUM_POINTS];
#endif
for(int i =0; i < NUM_POINTS; i++)
{
// Find correct cavity
for(int j = 0; j < modules.size(); j++)
{
if (((VECSEL_cav_snapshot_x[i] >= modules[j].getPosition0())&&(VECSEL_cav_snapshot_x[i] <= modules[j].getPosition1()))&&(modules[j].isCavity()))
{
VECSEL_cav_snapshot_index[i] = j;
break;
}
}
}
// Initialize E
#ifndef USE_CAVITY_SNAPSHOT
VECSEL_cav_snapshot_E = new std::complex<double>[NUM_POINTS];
VECSEL_cav_snapshot_E_re = new double[NUM_POINTS];
VECSEL_cav_snapshot_E_im = new double[NUM_POINTS];
#endif
for(int i = 0; i < NUM_POINTS; i++)
{
int indx = VECSEL_cav_snapshot_index[i]; // Find correct cavity
VECSEL_cav_snapshot_E[i] = modules[indx].getCavity()->evaluateEprop(VECSEL_cav_snapshot_x[i]);
VECSEL_cav_snapshot_E_re[i] = real(VECSEL_cav_snapshot_E[i]);
VECSEL_cav_snapshot_E_im[i] = imag(VECSEL_cav_snapshot_E[i]);
}
output_Cav_Snapshot_E_real.write(reinterpret_cast<const char*>(VECSEL_cav_snapshot_E_re),NUM_POINTS*sizeof(double));
output_Cav_Snapshot_E_imag.write(reinterpret_cast<const char*>(VECSEL_cav_snapshot_E_im),NUM_POINTS*sizeof(double));
//output_Cav_Snapshot_t.write(reinterpret_cast<const char*>(&t),sizeof(double));
//output_Cav_Snapshot_t.close();
output_Cav_Snapshot_E_real.close();
output_Cav_Snapshot_E_imag.close();
*/
}
//===================
// Maxwells function
/**
Update an edge 'i' on to the RIGHT of a cavity, inside the domain using the iteration scheme
The contribution from any devices on the edge is precomputed in 'device_MacPol'
device_MacPol -> Any contribution from the device itself = MacPol*(eff_qw/focusE)
Should not be used on boundary edges such as Vcav, boundary or others
*/
void VECSEL::iterateModules_updateSingleSurface_transfer_matrix(int i)
{
std::complex<double> a11, a12, a21, a22, *E_pl, *E_mi, *E_pl_k, *E_mi_k, *MacPol;
int indx = quick_index_cavity[i]; // Current cavity
int indx_k = quick_index_cavity[i+1]; // Next cavity
modules[indx].getCavity()->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol);
E_pl = modules[indx ].getCavity()->interpolateEpluss_x1();
E_mi_k = modules[indx_k].getCavity()->interpolateEminus_x0();
E_pl_k = modules[indx_k].getCavity()->setEpluss();
E_mi = modules[indx].getCavity()->setEminus();
cblas_zcopy(VECSEL_transverse_points_number, MacPol, 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_pl , 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_mi_k, 1 , E_pl_k, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol, 1 , E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_pl , 1, E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_mi_k, 1, E_mi, 1);
}
void VECSEL::iterateModules_updateSingleSurface_transfer_matrix(Cavity *cav0, Cavity *cav1)
{
std::complex<double> a11, a12, a21, a22, *E_pl, *E_mi, *E_pl_k, *E_mi_k, *MacPol;
cav0->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol);
E_pl = cav0->interpolateEpluss_x1();
E_mi_k = cav1->interpolateEminus_x0();
E_pl_k = cav1->setEpluss();
E_mi = cav0->setEminus();
cblas_zcopy(VECSEL_transverse_points_number, MacPol, 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_pl , 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_mi_k, 1 , E_pl_k, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol, 1 , E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_pl , 1, E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_mi_k, 1, E_mi, 1);
}
void VECSEL::iterateModules_updateSingleSurface_transfer_matrix_noQW(Cavity *cav0, Cavity *cav1)
{
std::complex<double> a11, a12, a21, a22, *E_pl, *E_mi, *E_mi_k, *E_pl_k, *MacPol;
cav0->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol);
E_pl = cav0->interpolateEpluss_x1();
E_mi_k = cav1->interpolateEminus_x0();
E_pl_k = cav1->setEpluss();
E_mi = cav0->setEminus();
memset(E_pl_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_pl , 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_mi_k, 1 , E_pl_k, 1);
memset(E_mi, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_pl , 1, E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_mi_k, 1, E_mi, 1);
}
void VECSEL::iterateModules_updateSingleSurface_transfer_matrix_kerrCrystal_post(Cavity *cav0, Cavity *kerrCrystal)
{
std::complex<double> a11, a12, a21, a22, *E_pl, *E_mi, *E_mi_k, *E_pl_k, *MacPol;
cav0->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol);
E_pl = kerrCrystal->interpolateEpluss_x1();
E_mi_k = cav0->interpolateEminus_x0();
E_pl_k = cav0->setEpluss();
E_mi = kerrCrystal->setEminus();
std::complex<double> E_pl_kerr[VECSEL_transverse_points_number];
std::complex<double> kerrPhase=kerrCrystal->get_transport_const();
std::complex<double> trans_const=kerrCrystal->get_transport_const();
for (int j=0; j<VECSEL_transverse_points_number; j++)
{
kerrPhase=trans_const*abs(E_pl[j])*abs(E_pl[j]);
E_pl_kerr[j]=exp(kerrPhase)*E_pl[j];
}
memset(E_pl_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_pl_kerr , 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_mi_k, 1 , E_pl_k, 1);
memset(E_mi, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_pl_kerr , 1, E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_mi_k, 1, E_mi, 1);
}
void VECSEL::iterateModules_updateSingleSurface_transfer_matrix_kerrCrystal_pre(Cavity *cav0, Cavity *kerrCrystal)
{
std::complex<double> a11, a12, a21, a22, *E_pl, *E_mi, *E_mi_k, *E_pl_k, *MacPol;
kerrCrystal->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol);
E_pl = cav0->interpolateEpluss_x1();
E_mi_k = kerrCrystal->interpolateEminus_x0();
E_pl_k = kerrCrystal->setEpluss();
E_mi = cav0->setEminus();
std::complex<double> E_mi_kerr[VECSEL_transverse_points_number];
std::complex<double> kerrPhase;
std::complex<double> trans_const=kerrCrystal->get_transport_const();
for (int j=0; j<VECSEL_transverse_points_number; j++)
{
kerrPhase=trans_const*abs(E_mi_k[j])*abs(E_mi_k[j]);
E_mi_kerr[j]=exp(kerrPhase)*E_mi_k[j];
}
memset(E_pl_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_pl , 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_mi_kerr , 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_mi_k , 1 , E_pl_k, 1);
memset(E_mi, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_pl , 1, E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_mi_kerr , 1, E_mi, 1);
}
void VECSEL::iterateModules_updateSingleSurface_transfer_matrix_noQW_debug(Cavity *cav0, Cavity *cav1)
{
std::complex<double> a11, a12, a21, a22, *E_pl, *E_mi, *E_pl_k, *MacPol;
std::complex<double> *E_mi_k;
cav0->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol);
E_pl = cav0->interpolateEpluss_x1();
E_mi_k = cav1->interpolateEminus_x0();
E_pl_k = cav1->setEpluss();
E_mi = cav0->setEminus();
memset(E_pl_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_pl , 1 , E_pl_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_mi_k, 1 , E_pl_k, 1);
memset(E_mi, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_pl , 1, E_mi, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_mi_k, 1, E_mi, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix(int i)
{
std::complex<double> a11, a12, a21, a22, *E_fp, *E_fp_k, *E_fm, *E_fm_k, *E_bp, *E_bp_k, *E_bm, *E_bm_k, *MacPol_fp, *MacPol_fm, *MacPol_bp, *MacPol_bm;
int indx = quick_index_twoArmCavity[i]; // Current cavity
int indx_k = quick_index_twoArmCavity[i+1]; // Next cavity
std::complex<double> dummy=1.0;
modules[indx ].getTwoArmCavity()->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol_fp, &MacPol_fm, &MacPol_bp, &MacPol_bm);
E_fp = modules[indx ].getTwoArmCavity()->interpolateEfp_x1();
E_fm = modules[indx ].getTwoArmCavity()->interpolateEfm_x1();
E_bp_k = modules[indx_k].getTwoArmCavity()->interpolateEbp_x0();
E_bm_k = modules[indx_k].getTwoArmCavity()->interpolateEbm_x0();
E_fp_k = modules[indx_k].getTwoArmCavity()->setEfp();
E_fm_k = modules[indx_k].getTwoArmCavity()->setEfm();
E_bp = modules[indx ].getTwoArmCavity()->setEbp();
E_bm = modules[indx ].getTwoArmCavity()->setEbm();
cblas_zcopy(VECSEL_transverse_points_number, MacPol_fp, 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_bp, 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bp_k , 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fp, 1 , E_fp_k, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol_fm, 1 , E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_bm, 1 , E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bm_k, 1, E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fm , 1, E_fm_k, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol_fp, 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_bp, 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fp , 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bp_k, 1 , E_bp, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol_fm, 1 , E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_bm, 1 , E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fm , 1, E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bm_k, 1, E_bm, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix(TwoArmCavity *cav0, TwoArmCavity *cav1)
{
std::complex<double> a11, a12, a21, a22, *E_fp, *E_fp_k, *E_fm, *E_fm_k, *E_bp, *E_bp_k, *E_bm, *E_bm_k, *MacPol_fp, *MacPol_fm, *MacPol_bp, *MacPol_bm;
std::complex<double> dummy=1.0;
cav0->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol_fp, &MacPol_fm, &MacPol_bp, &MacPol_bm);
E_fp = cav0->interpolateEfp_x1();
E_bp_k = cav1->interpolateEbp_x0();
E_bm_k = cav1->interpolateEbm_x0();
E_fm = cav0->interpolateEfm_x1();
E_fp_k = cav1->setEfp();
E_fm_k = cav1->setEfm();
E_bp = cav0->setEbp();
E_bm = cav0->setEbm();
cblas_zcopy(VECSEL_transverse_points_number, MacPol_fp, 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_bp, 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bp_k, 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fp , 1 , E_fp_k, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol_fm, 1 , E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_bm, 1 , E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bm_k, 1, E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fm , 1, E_fm_k, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol_bp, 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_fp, 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bp_k , 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fp , 1 , E_bp, 1);
cblas_zcopy(VECSEL_transverse_points_number, MacPol_bm, 1 , E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &dummy, MacPol_fm, 1 , E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bm_k, 1, E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fm , 1, E_bm, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface_delay_uncoupled(Cavity *cav0, TwoArmInterface *cavInt, Cavity *cav1, TwoArmCavity *cavFront)
{
std::complex<double> a11_left, a12_left, a21_left, a22_left, a11_right, a12_right, a21_right, a22_right, *E_p_in, *E_m_in, *E_bm, *E_bp, *E_p_out, *E_m_out, *E_fp, *E_fm, *phase_in, *phase_out;
std::complex<double> E_fp_int[VECSEL_transverse_points_number], E_fm_int[VECSEL_transverse_points_number], E_bp_int[VECSEL_transverse_points_number], E_bm_int[VECSEL_transverse_points_number];
std::complex<double> dummy=1.0;
std::complex<double> E_tmp;
cavInt->get_transfer_matrix(&a11_left,&a12_left,&a21_left,&a22_left, &a11_right, &a12_right, &a21_right, &a22_right);
E_p_in = cav0->interpolateEpluss_x1();
E_m_in = cav1->interpolateEminus_x0();
E_bm = cavFront->interpolateEbm_x0();
E_bp = cavFront->interpolateEbp_x0();
E_m_out = cav1->setEpluss();
E_p_out = cav0->setEminus();
E_fp = cavFront->setEfp();
E_fm = cavFront->setEfm();
phase_in=cavInt->getPhaseIn();
phase_out=cavInt->getPhaseOut();
cavInt->getBoundary_Efp(E_fp_int);
cavInt->getBoundary_Efm(E_fm_int);
cavInt->getBoundary_Ebp(E_bp_int);
cavInt->getBoundary_Ebm(E_bm_int);
for( int i =0; i < VECSEL_transverse_points_number; i++)
{
//Forward field into interface
cavInt->setEfp(i, &E_p_in[i]);
cavInt->setEfm(i, &E_m_in[i]);
//Backward pluss field
E_tmp=a21_right*E_fm_int[i]+a22_right*phase_in[i]*E_bm[i];
//E_tmp=a21_right*E_fm_int[i]+a22_right*E_bm[i];
cavInt->setEbm(i, &E_tmp);
//Backward minus field
E_tmp=a21_left*E_fp_int[i]+a22_left*phase_out[i]*E_bp[i];
//E_tmp=a21_left*E_fp_int[i]+a22_left*E_bp[i];
cavInt->setEbp(i, &E_tmp);
E_fp_int[i]*=phase_in[i];
E_fm_int[i]*=phase_out[i];
}
memset(E_fp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_left , E_bp , 1 , E_fp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_left , E_fp_int , 1 , E_fp, 1);
memset(E_fm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_right , E_bm , 1 , E_fm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_right , E_fm_int , 1 , E_fm, 1);
memset(E_m_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &dummy , E_bm_int , 1 , E_m_out, 1);
memset(E_p_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &dummy , E_bp_int , 1 , E_p_out, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface_delay(Cavity *cav0, TwoArmInterface *cavInt, Cavity *cav1, TwoArmCavity *cavFront)
{
std::complex<double> a11_left, a12_left, a21_left, a22_left, a11_right, a12_right, a21_right, a22_right, *E_p_in, *E_m_in, *E_bm, *E_bp, *E_p_out, *E_m_out, *E_fp, *E_fm, *phase_in, *phase_out;
std::complex<double> E_fp_int[VECSEL_transverse_points_number], E_fm_int[VECSEL_transverse_points_number], E_bp_int[VECSEL_transverse_points_number], E_bm_int[VECSEL_transverse_points_number];
std::complex<double> dummy=1.0;
std::complex<double> E_tmp;
cavInt->get_transfer_matrix(&a11_left,&a12_left,&a21_left,&a22_left, &a11_right, &a12_right, &a21_right, &a22_right);
E_p_in = cav0->interpolateEpluss_x1();
E_m_in = cav1->interpolateEminus_x0();
E_bm = cavFront->interpolateEbm_x0();
E_bp = cavFront->interpolateEbp_x0();
E_m_out = cav1->setEpluss();
E_p_out = cav0->setEminus();
E_fp = cavFront->setEfp();
E_fm = cavFront->setEfm();
phase_in=cavInt->getPhaseIn();
phase_out=cavInt->getPhaseOut();
cavInt->getBoundary_Efp(E_fp_int);
cavInt->getBoundary_Efm(E_fm_int);
cavInt->getBoundary_Ebp(E_bp_int);
cavInt->getBoundary_Ebm(E_bm_int);
for( int i =0; i < VECSEL_transverse_points_number; i++)
{
//Forward field into interface
cavInt->setEfp(i, &E_p_in[i]);
cavInt->setEfm(i, &E_m_in[i]);
//Backward pluss field
E_tmp=a21_right*E_fm_int[i]+a22_right*phase_in[i]*E_bm[i];
//E_tmp=a21_right*E_fm_int[i]+a22_right*E_bm[i];
cavInt->setEbp(i, &E_tmp);
//Backward minus field
E_tmp=a21_left*E_fp_int[i]+a22_left*phase_out[i]*E_bp[i];
//E_tmp=a21_left*E_fp_int[i]+a22_left*E_bp[i];
cavInt->setEbm(i, &E_tmp);
E_fp_int[i]*=phase_in[i];
E_fm_int[i]*=phase_out[i];
}
memset(E_fp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_left , E_bp , 1 , E_fp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_left , E_fp_int , 1 , E_fp, 1);
memset(E_fm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_right , E_bm , 1 , E_fm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_right , E_fm_int , 1 , E_fm, 1);
memset(E_m_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &dummy , E_bm_int , 1 , E_m_out, 1);
memset(E_p_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &dummy , E_bp_int , 1 , E_p_out, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface_uncoupled(Cavity *cav0, TwoArmInterface *cavInt, Cavity *cav1, TwoArmCavity *cavFront)
{
std::complex<double> a11_left, a12_left, a21_left, a22_left, a11_right, a12_right, a21_right, a22_right, *E_m_in, *E_p_in, *E_bm, *E_bp, *E_p_out, *E_m_out, *E_fp, *E_fm;
cavInt->get_transfer_matrix(&a11_left,&a12_left,&a21_left,&a22_left, &a11_right, &a12_right, &a21_right, &a22_right);
E_p_in = cav0->interpolateEpluss_x1();
E_m_in = cav1->interpolateEminus_x0();
E_bm = cavFront->interpolateEbm_x0();
E_bp = cavFront->interpolateEbp_x0();
E_m_out = cav1->setEpluss();
E_p_out = cav0->setEminus();
E_fp = cavFront->setEfp();
E_fm = cavFront->setEfm();
memset(E_fp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_left , E_bp , 1 , E_fp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_left , E_p_in, 1 , E_fp, 1);
memset(E_fm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_right , E_bm , 1, E_fm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_right , E_m_in, 1, E_fm, 1);
memset(E_m_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
memset(E_p_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a22_right , E_bm , 1 , E_m_out, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21_right , E_m_in, 1 , E_m_out, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22_left , E_bp , 1 , E_p_out, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21_left , E_p_in, 1 , E_p_out, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface(Cavity *cav0, TwoArmInterface *cavInt, Cavity *cav1, TwoArmCavity *cavFront)
{
std::complex<double> a11_left, a12_left, a21_left, a22_left, a11_right, a12_right, a21_right, a22_right, *E_m_in, *E_p_in, *E_bm, *E_bp, *E_p_out, *E_m_out, *E_fp, *E_fm;
cavInt->get_transfer_matrix(&a11_left,&a12_left,&a21_left,&a22_left, &a11_right, &a12_right, &a21_right, &a22_right);
E_p_in = cav0->interpolateEpluss_x1();
E_m_in = cav1->interpolateEminus_x0();
E_bm = cavFront->interpolateEbm_x0();
E_bp = cavFront->interpolateEbp_x0();
E_m_out = cav1->setEpluss();
E_p_out = cav0->setEminus();
E_fp = cavFront->setEfp();
E_fm = cavFront->setEfm();
memset(E_fp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_left , E_bp , 1 , E_fp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_left , E_p_in, 1 , E_fp, 1);
memset(E_fm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_right , E_bm , 1, E_fm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_right , E_m_in, 1, E_fm, 1);
memset(E_m_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
memset(E_p_out, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
//VCAV implementation
cblas_zaxpy(VECSEL_transverse_points_number, &a22_right , E_bp , 1 , E_m_out, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21_left , E_p_in, 1 , E_m_out, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a22_left , E_bm , 1, E_p_out, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21_right, E_m_in , 1, E_p_out, 1);
//MockLinear implementation
//cblas_zaxpy(VECSEL_transverse_points_number, &a22_right , E_bm , 1 , E_m_out, 1);
//cblas_zaxpy(VECSEL_transverse_points_number, &a21_right , E_m_in, 1 , E_m_out, 1);
//cblas_zaxpy(VECSEL_transverse_points_number, &a22_left , E_bp , 1 , E_p_out, 1);
//cblas_zaxpy(VECSEL_transverse_points_number, &a21_left , E_p_in, 1 , E_p_out, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_back(double t_sim, TwoArmCavity *cav0, std::complex<double> Reflection)
{
std::complex<double> *E_bp, *E_bm;
std::complex<double> E_fp[VECSEL_transverse_points_number], E_fm[VECSEL_transverse_points_number];
cav0->getEfp_back_wall(E_fp);
cav0->getEfm_back_wall(E_fm);
E_bp = cav0->setEbp();
E_bm = cav0->setEbm();
memset(E_bp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
memset(E_bm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
std::complex<double> scale = -sqrt(Reflection);
#ifdef DUAL_CHIP
if (VECSEL_pulse_start_l == 1)
{
maxwell_initial_E(t_sim,E_bp);
}
if (VECSEL_pulse_start_r == 1)
{
maxwell_initial_E(t_sim,E_bm);
}
#endif
cblas_zaxpy(VECSEL_transverse_points_number, &scale, E_fp, 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, E_fm, 1 , E_bm, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_noQW(TwoArmCavity *cav0, TwoArmCavity *cav1)
{
std::complex<double> a11, a12, a21, a22, *E_fp, *E_fp_k, *E_fm, *E_fm_k, *E_bp, *E_bp_k, *E_bm, *E_bm_k, *MacPol_fp, *MacPol_fm, *MacPol_bp, *MacPol_bm;
cav0->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol_fp, &MacPol_fm, &MacPol_bp, &MacPol_bm);
E_fp = cav0->interpolateEfp_x1();
E_bp_k = cav1->interpolateEbp_x0();
E_fm = cav0->interpolateEfm_x1();
E_bm_k = cav1->interpolateEbm_x0();
E_fp_k = cav1->setEfp();
E_bp = cav0->setEbp();
E_fm_k = cav1->setEfm();
E_bm = cav0->setEbm();
memset(E_fp_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bp_k , 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fp , 1 , E_fp_k, 1);
memset(E_fm_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bm_k , 1, E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fm , 1, E_fm_k, 1);
memset(E_bp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bp_k , 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fp , 1 , E_bp, 1);
memset(E_bm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bm_k , 1, E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fm , 1, E_bm, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_birefringentCrystal_front(TwoArmCavity *cav0, TwoArmCavity *brc)
{
std::complex<double> a11, a12, a21, a22, a11_ex, a12_ex, a21_ex, a22_ex, *E_fp, *E_fp_k, *E_fm, *E_fm_k, *E_bp, *E_bp_k, *E_bm, *E_bm_k, *MacPol_fp, *MacPol_fm, *MacPol_bp, *MacPol_bm;
cav0->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol_fp, &MacPol_fm, &MacPol_bp, &MacPol_bm);
brc->get_transfer_matrix_extraAxis(&a11_ex,&a12_ex,&a21_ex,&a22_ex);
E_fp = cav0->interpolateEfp_x1();
E_bp_k = brc->interpolateEbp_x0();
E_fm = cav0->interpolateEfm_x1();
E_bm_k = brc->interpolateEbm_x0();
E_fp_k = brc->setEfp();
E_bp = cav0->setEbp();
E_fm_k = brc->setEfm();
E_bm = cav0->setEbm();
memset(E_fp_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bp_k , 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fp , 1 , E_fp_k, 1);
memset(E_fm_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12_ex , E_bm_k , 1, E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fm , 1, E_fm_k, 1);
memset(E_bp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bp_k , 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fp , 1 , E_bp, 1);
memset(E_bm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a22_ex , E_bm_k , 1, E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fm , 1, E_bm, 1);
}
void VECSEL::iterateModules_updateSingleSurface_TwoArm_transfer_matrix_birefringentCrystal_back(TwoArmCavity *brc, TwoArmCavity *cav1)
{
std::complex<double> a11, a12, a21, a22, a11_ex, a12_ex, a21_ex, a22_ex, *E_fp, *E_fp_k, *E_fm, *E_fm_k, *E_bp, *E_bp_k, *E_bm, *E_bm_k, *MacPol_fp, *MacPol_fm, *MacPol_bp, *MacPol_bm;
brc->get_transfer_matrix(&a11,&a12,&a21,&a22,&MacPol_fp, &MacPol_fm, &MacPol_bp, &MacPol_bm);
brc->get_transfer_matrix_extraAxis(&a11_ex,&a12_ex,&a21_ex,&a22_ex);
E_fp = brc->interpolateEfp_x1();
E_bp_k = cav1->interpolateEbp_x0();
E_fm = brc->interpolateEfm_x1();
E_bm_k = cav1->interpolateEbm_x0();
E_fp_k = cav1->setEfp();
E_bp = brc->setEbp();
E_fm_k = cav1->setEfm();
E_bm = brc->setEbm();
memset(E_fp_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bp_k , 1 , E_fp_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11 , E_fp , 1 , E_fp_k, 1);
memset(E_fm_k, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a12 , E_bm_k , 1, E_fm_k, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a11_ex , E_fm , 1, E_fm_k, 1);
memset(E_bp, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bp_k , 1 , E_bp, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21 , E_fp , 1 , E_bp, 1);
memset(E_bm, 0.0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &a22 , E_bm_k , 1, E_bm, 1);
cblas_zaxpy(VECSEL_transverse_points_number, &a21_ex , E_fm , 1, E_bm, 1);
}
void VECSEL::iterateModules_updateAllSurface(VECSEL *model, double t_sim)
{
//================================================================
// 1. Apply boundary conditions: Reflecting/Absorbing periodic boundaries: 1st boundary
//================================================================
if (model->modules[0].isBoundary())
{
#ifdef DUAL_PROP
int indx = model->quick_index_twoArmCavity[0]; // Current cavity
int indx_k = model->quick_index_twoArmCavity.back(); // Last cavity
double r1 = model->modules[0].getBoundary()->getRefCoeff();
double r2 = model->modules.back().getBoundary()->getRefCoeff();
double x0 = model->modules[indx].getPosition0();
double ni = model->modules[indx].getRefInd();
double n0 = model->modules[0].getBoundary()->getNextCavityIndex();
// Reflected from cavity
model->modules[indx].getTwoArmCavity()->getEbp_front_wall(cavity_trans_E_mi);
model->modules[0].getBoundary()->getEpluss(cavity_trans_E_pl);
// Transmission through boundary for output
std::complex<double> *transmitted = model->modules[0].getBoundary()->setEminus();
std::complex<double> scale = sqrt((ni/n0)*(1.0-r1));
memcpy(transmitted, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zscal(VECSEL_transverse_points_number, &scale, transmitted, 1);
model->modules[indx].getTwoArmCavity()->getEbm_front_wall(cavity_trans_E_mi);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_mi , 1, transmitted, 1);
// Feedback into cavity
std::complex<double> *feedback = model->modules[indx].getTwoArmCavity()->setEfp();
#ifdef CYCLIC_BOUNDARIES
memcpy(feedback, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
model->modules[indx_k].getTwoArmCavity()->getEfp_right_wall(cavity_trans_E_pl);
scale = -sqrt(r2);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, feedback, 1);
#else
scale = -sqrt(r1);
memcpy(feedback, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
model->modules[indx].getTwoArmCavity()->getEbp_front_wall(cavity_trans_E_mi);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_mi , 1, feedback, 1);
#endif
feedback = model->modules[indx].getTwoArmCavity()->setEfm();
#ifdef CYCLIC_BOUNDARIES
memcpy(feedback, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
model->modules[indx_k].getTwoArmCavity()->getEfm_right_wall(cavity_trans_E_pl);
scale = -sqrt(r2);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, feedback, 1);
#else
scale = -sqrt(r1);
model->modules[indx].getTwoArmCavity()->getEbm_front_wall(cavity_trans_E_mi);
memcpy(feedback, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_mi , 1, feedback, 1);
#endif
#else
int indx = model->quick_index_cavity[0]; // Current cavity
int indx_k = model->quick_index_cavity.back(); // Last cavity
double r1 = model->modules[0].getBoundary()->getRefCoeff();
double r2 = model->modules.back().getBoundary()->getRefCoeff();
double x0 = model->modules[indx].getPosition0();
double ni = model->modules[indx].getRefInd();
double n0 = model->modules[0].getBoundary()->getNextCavityIndex();
// Reflected from cavity
model->modules[indx].getCavity()->getEminus_left_wall(cavity_trans_E_mi);
model->modules[0].getBoundary()->getEpluss(cavity_trans_E_pl);
// Transmission through boundary for output
std::complex<double> *transmitted = model->modules[0].getBoundary()->setEminus();
std::complex<double> scale = sqrt((ni/n0)*(1.0-r1));
memcpy(transmitted, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zscal(VECSEL_transverse_points_number, &scale, transmitted, 1);
// Feedback into cavity
std::complex<double> *feedback = model->modules[indx].getCavity()->setEpluss();
#ifdef CYCLIC_BOUNDARIES
memcpy(feedback, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
model->modules[indx_k].getCavity()->getEpluss_right_wall(cavity_trans_E_pl);
scale = -sqrt(r2);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, feedback, 1);
#else
scale = -sqrt(r1);
memcpy(feedback, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_mi , 1, feedback, 1);
#endif
#endif
}
//================================================================
// 2. Apply boundary conditions: Reflecting/Absorbing periodic boundaries: Last boundary
//================================================================
if (model->modules.back().isBoundary())
{
#ifdef DUAL_PROP
int indx = model->quick_index_twoArmCavity[0]; // Current cavity
int indx_k = model->quick_index_twoArmCavity.back(); // Last cavity
// Final boundary
double r1 = model->modules[0].getBoundary()->getRefCoeff();
double r2 = model->modules.back().getBoundary()->getRefCoeff();
double x1 = model->modules[indx_k].getPosition1();
double ni = model->modules[indx_k].getRefInd();
double n0 = model->modules.back().getBoundary()->getNextCavityIndex();
// Reflected from cavity
model->modules[indx_k].getTwoArmCavity()->getEfp_back_wall(cavity_trans_E_pl);
model->modules.back().getBoundary()->getEminus(cavity_trans_E_mi);
// Transmission through boundary for output
std::complex<double> *transmitted = model->modules.back().getBoundary()->setEpluss();
std::complex<double> scale = sqrt((ni/n0)*(1.0-r2));
memcpy(transmitted, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zscal(VECSEL_transverse_points_number, &scale, transmitted, 1);
model->modules[indx_k].getTwoArmCavity()->getEfm_back_wall(cavity_trans_E_pl);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, transmitted, 1);
// Feedback into cavity
std::complex<double> *feedback = model->modules[indx_k].getTwoArmCavity()->setEbm();
#ifdef CYCLIC_BOUNDARIES
memcpy(feedback, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
model->modules[indx].getTwoArmCavity()->getEbm_front_wall(cavity_trans_E_pl);
scale = -sqrt(r1);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, feedback, 1);
#else
scale = -sqrt(r2);
memcpy(feedback, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, feedback, 1);
#endif
feedback = model->modules[indx_k].getTwoArmCavity()->setEbp();
#ifdef CYCLIC_BOUNDARIES
memcpy(feedback, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
model->modules[indx].getTwoArmCavity()->getEbp_front_wall(cavity_trans_E_mi);
scale = -sqrt(r1);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_mi , 1, feedback, 1);
#else
scale = -sqrt(r2);
model->modules[indx_k].getTwoArmCavity()->getEfp_back_wall(cavity_trans_E_pl);
memcpy(feedback, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, feedback, 1);
#endif
#else
int indx = model->quick_index_cavity[0]; // Current cavity
int indx_k = model->quick_index_cavity.back(); // Last cavity
// Final boundary
double r1 = model->modules[0].getBoundary()->getRefCoeff();
double r2 = model->modules.back().getBoundary()->getRefCoeff();
double x1 = model->modules[indx_k].getPosition1();
double ni = model->modules[indx_k].getRefInd();
double n0 = model->modules.back().getBoundary()->getNextCavityIndex();
// Reflected from cavity
model->modules[indx_k].getCavity()->getEpluss_right_wall(cavity_trans_E_pl);
model->modules.back().getBoundary()->getEminus(cavity_trans_E_mi);
// Transmission through boundary for output
std::complex<double> *transmitted = model->modules.back().getBoundary()->setEpluss();
std::complex<double> scale = sqrt((ni/n0)*(1.0-r2));
memcpy(transmitted, cavity_trans_E_pl, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zscal(VECSEL_transverse_points_number, &scale, transmitted, 1);
// Feedback into cavity
std::complex<double> *feedback = model->modules[indx_k].getCavity()->setEminus();
#ifdef CYCLIC_BOUNDARIES
memcpy(feedback, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
model->modules[indx].getCavity()->getEminus_left_wall(cavity_trans_E_mi);
scale = -sqrt(r1);
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_mi , 1, feedback, 1);
#else
scale = -sqrt(r2);
memcpy(feedback, cavity_trans_E_mi, VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &scale, cavity_trans_E_pl , 1, feedback, 1);
#endif
#endif
}
if( model->quick_index_cavity_noQW.size() > 0 )
{
// Iterate over all (noQW) cavities
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int i=0; i<model->quick_index_cavity_noQW.size()-1; i++)
{
int indx = quick_index_cavity_noQW[i]; // Current cavity
int indx_k = indx+1; // Next cavity
if(modules[indx_k].isTwoArmInterface())
{
int indx_end = modules[indx_k].getTwoArmInterface()->getPostCav();
#ifdef DUAL_CHIP
#ifdef TRANS_DELAY
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface_delay_uncoupled(modules[indx].getCavity(),modules[indx_k].getTwoArmInterface(),modules[indx_end].getCavity(), modules[indx_k+1].getTwoArmCavity()); //Update interface with transversal delay
#else
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface_uncoupled(modules[indx].getCavity(),modules[indx_k].getTwoArmInterface(),modules[indx_end].getCavity(), modules[indx_k+1].getTwoArmCavity()); //Update interface without any pulse delay
#endif
#else
#ifdef TRANS_DELAY
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface_delay(modules[indx].getCavity(),modules[indx_k].getTwoArmInterface(),modules[indx_end].getCavity(), modules[indx_k+1].getTwoArmCavity()); //Update interface with transversal delay
#else
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_interface(modules[indx].getCavity(),modules[indx_k].getTwoArmInterface(),modules[indx_end].getCavity(), modules[indx_k+1].getTwoArmCavity()); //Update interface without any pulse delay
#endif
#endif
std::complex<double> tmp_reflect=modules[indx_k].getTwoArmInterface()->getReflect();
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_back(t_sim, modules[indx_end-1].getTwoArmCavity(),tmp_reflect);
}else if (modules[indx_k].isKerrCrystal())
{
int indx_kk=indx+2;
model->iterateModules_updateSingleSurface_transfer_matrix_kerrCrystal_pre(modules[indx].getCavity(), modules[indx_k].getKerrCrystal());
model->iterateModules_updateSingleSurface_transfer_matrix_kerrCrystal_post(modules[indx_kk].getCavity(), modules[indx_k].getKerrCrystal());
} else
{
model->iterateModules_updateSingleSurface_transfer_matrix_noQW(modules[indx].getCavity(), modules[indx_k].getCavity());
}
}
}
if( model->quick_index_twoArmCavity_noQW.size() > 0 )
{
// Iterate over all (noQW) two arm cavities
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int i=0; i<model->quick_index_twoArmCavity_noQW.size()-1; i++)
{
int indx = quick_index_twoArmCavity_noQW[i]; // Current cavity
int indx_k = indx+1; // Next cavity
if(modules[indx_k].isTwoArmCavity())
{
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_noQW(modules[indx].getTwoArmCavity(), modules[indx_k].getTwoArmCavity());
}
}
}
if( model->quick_index_birefringentCrystal.size() > 0 )
{
// Iterate over all (noQW) two arm cavities
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int i=0; i<model->quick_index_birefringentCrystal.size(); i++)
{
int indx = quick_index_birefringentCrystal[i]; // Current cavity
int indx_mk = indx-1; // Next cavity
int indx_pk = indx+1;
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_birefringentCrystal_front(modules[indx_mk].getTwoArmCavity(), modules[indx].getBirefringentCrystal());
model->iterateModules_updateSingleSurface_TwoArm_transfer_matrix_birefringentCrystal_back(modules[indx].getBirefringentCrystal(), modules[indx_pk].getTwoArmCavity());
}
}
}
void VECSEL::iterateModules(double t_sim, double DT)
{
/* ===========================================
* SOLVE MAXWELL's EQUATIONS
* */
if (MPI_MY_RANK == 0)
{
#ifdef MPI_BALANCE_WORKLOAD
MPI_load->start();
#endif
#ifdef USE_MAIN_TIMERS
MainStat->start("VECSEL::transfer matrix");
#endif
#ifndef DUAL_CHIP
if (VECSEL_pulse_start_l == 1)
{
std::complex<double> *tmp = modules[0].getBoundary()->setEpluss();
maxwell_initial_E(t_sim,tmp);
}
if (VECSEL_pulse_start_r == 1)
{
std::complex<double> *tmp = modules.back().getBoundary()->setEminus();
maxwell_initial_E(t_sim,tmp);
}
#endif
#ifdef USE_MAIN_TIMERS
MainStat->start("TM Update Storage");
#endif
#pragma omp parallel num_threads(OMP_THREADS_LEVEL_1)
{
for(unsigned i=0; i<quick_index_cavity_lens.size(); i++)
{
#pragma omp single nowait
{
int indx = quick_index_cavity_lens[i];
modules[indx].getCavity()->updateStorage_lens_pluss();
}
#pragma omp single nowait
{
int indx = quick_index_cavity_lens[i];
modules[indx].getCavity()->updateStorage_lens_minus();
}
}
for(unsigned i=0; i<quick_index_cavity_lens_halfCav.size(); i++)
{
#pragma omp single nowait
{
int indx = quick_index_cavity_lens_halfCav[i];
modules[indx].getCavity()->updateStorage_lens_pluss();
}
#pragma omp single nowait
{
int indx = quick_index_cavity_lens_halfCav[i];
modules[indx].getCavity()->updateStorage_lens_minus();
}
}
#pragma omp for
for(unsigned i = 0; i < quick_index_cavity_freeSpace.size(); i++)
{
int indx = quick_index_cavity_freeSpace[i];
modules[indx].getCavity()->updateStorage_freeSpace_forcedBPM(); // Update storage of fields
}
#pragma omp for
for(unsigned i = 0; i < quick_index_cavity_noBPM.size(); i++)
{
int indx = quick_index_cavity_noBPM[i];
modules[indx].getCavity()->updateStorage_freeSpace(); // Update storage of fields
}
#pragma omp for
for(unsigned i = 0; i < quick_index_twoArmCavity.size(); i++)
{
int indx = quick_index_twoArmCavity[i];
modules[indx].getTwoArmCavity()->updateStorage_freeSpace(); // Update storage of fields
}
#pragma omp for
for(unsigned i = 0; i < quick_index_birefringentCrystal.size(); i++)
{
int indx = quick_index_birefringentCrystal[i];
modules[indx].getBirefringentCrystal()->updateStorage_freeSpace(); // Update storage of fields
}
#pragma omp for
for(unsigned i = 0; i < quick_index_kerrCrystal.size(); i++)
{
int indx = quick_index_kerrCrystal[i];
modules[indx].getKerrCrystal()->updateStorage_freeSpace(); // Update storage of fields
}
#pragma omp for
for(unsigned i = 0; i < quick_index_twoArmInterface.size(); i++)
{
int indx = quick_index_twoArmInterface[i];
modules[indx].getTwoArmInterface()->updateStorage_freeSpace(); // Update storage of fields
}
}
#ifdef USE_MAIN_TIMERS
MainStat->stop("TM Update Storage");
#endif
#ifdef USE_MAIN_TIMERS
MainStat->start("TM B.C.");
#endif
//============
// Update Cav
//============
iterateModules_updateAllSurface(this,t_sim);
#ifdef USE_MAIN_TIMERS
MainStat->stop("TM B.C.");
#endif
#ifdef USE_MAIN_TIMERS
MainStat->stop("VECSEL::transfer matrix");
#endif
#ifdef MPI_BALANCE_WORKLOAD
MPI_load->stop();
#endif
//=============================================
// Code moved from iterateModules_updateAllSurface
// Collect macroscopic polarizations
#ifdef USE_MAIN_TIMERS
MainStat->start("VECSEL::MPI_comm_gath");
#endif
#ifdef ITERATE_QW
MPI_Gatherv( MPI_WORK_DIST_P_LOCAL, MPI_WORK_DIST_P_SIZE[MPI_MY_RANK],MPI_DOUBLE_COMPLEX, // Where I store my stuff
MPI_WORK_DIST_P_GLOBAL[0], MPI_WORK_DIST_P_SIZE, MPI_WORK_DIST_P_OFFSET, MPI_DOUBLE_COMPLEX, // Distribution of work
0, *MPI_WORK_GANG); // Who is recieving the data
#endif
#ifdef USE_MAIN_TIMERS
MainStat->stop("VECSEL::MPI_comm_gath");
#endif
#ifdef USE_MAIN_TIMERS
MainStat->start("VECSEL::prepare MPI");
#endif
// unscramble
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int i = 0; i < quick_index_totalDevice.size(); i++)
{
MPI_LoadBalancer_P_tmp[4*MPI_LoadBalancer_index_set[i]] = MPI_WORK_DIST_P_GLOBAL[0][4*i];
MPI_LoadBalancer_P_tmp[1+4*MPI_LoadBalancer_index_set[i]] = MPI_WORK_DIST_P_GLOBAL[0][1+4*i];
MPI_LoadBalancer_P_tmp[2+4*MPI_LoadBalancer_index_set[i]] = MPI_WORK_DIST_P_GLOBAL[0][2+4*i];
MPI_LoadBalancer_P_tmp[3+4*MPI_LoadBalancer_index_set[i]] = MPI_WORK_DIST_P_GLOBAL[0][3+4*i];
}
#endif
#pragma omp parallel num_threads(OMP_THREADS_LEVEL_1)
{
// Set all MacPol into correct cavities
#ifdef ITERATE_QW
#pragma omp for
for(int j = 0; j < quick_index_totalDevice.size(); j = j + VECSEL_transverse_points_number)
{
int indx_k = quick_index_device_previous_cavity[j];
if (modules[indx_k].isCavity())
{
modules[indx_k].getCavity()->set_transfer_matrix_macPol(&(MPI_LoadBalancer_P_tmp[4*j]));
} else
{
modules[indx_k].getTwoArmCavity()->set_transfer_matrix_macPol_fp(&(MPI_LoadBalancer_P_tmp[4*j]));
modules[indx_k].getTwoArmCavity()->set_transfer_matrix_macPol_fm(&(MPI_LoadBalancer_P_tmp[4*j+1]));
modules[indx_k].getTwoArmCavity()->set_transfer_matrix_macPol_bp(&(MPI_LoadBalancer_P_tmp[4*j+2]));
modules[indx_k].getTwoArmCavity()->set_transfer_matrix_macPol_bm(&(MPI_LoadBalancer_P_tmp[4*j+3]));
}
}
#endif
// Iterate final parts of transfer matrix for cavities with QWs
if( quick_index_cavity_QW.size() > 0)
{
#pragma omp for
for(int i=0; i<quick_index_cavity_QW.size()-1; i = i + 2)
{
int indx = quick_index_cavity_QW[i]; // Current cavity
int indx_k = quick_index_cavity_QW[i+1]; // Next cavity
iterateModules_updateSingleSurface_transfer_matrix(modules[indx].getCavity(), modules[indx_k].getCavity());
}
}
// Iterate final parts of transfer matrix for two arm cavities with QWs
if( quick_index_twoArmCavity_QW.size() > 0)
{
#pragma omp for
for(int i=0; i<quick_index_twoArmCavity_QW.size()-1; i = i + 2)
{
int indx = quick_index_twoArmCavity_QW[i]; // Current cavity
int indx_k = quick_index_twoArmCavity_QW[i+1]; // Next cavity
iterateModules_updateSingleSurface_TwoArm_transfer_matrix(modules[indx].getTwoArmCavity(), modules[indx_k].getTwoArmCavity());
}
}
}
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int i = 0; i < quick_index_device_previous_cavity.size(); i = i + VECSEL_transverse_points_number)
{
int indx_k = quick_index_device_previous_cavity[i];
if(modules[indx_k].isCavity())
{
modules[indx_k].getCavity()->evaluateEprop_x1_fast( &MPI_LoadBalancer_E_tmp[8*i ], 8);
modules[indx_k].getCavity()->evaluateEprop_x1_tp1_fast(&MPI_LoadBalancer_E_tmp[8*i+1], 8);
}
else
{
//WTFF-modules[indx_k].getTwoArmCavity()->evaluateEprop_back_wall( &MPI_LoadBalancer_E_tmp[8*i]);
modules[indx_k+VECSEL_transverse_points_number+1].getTwoArmCavity()->evaluateEprop_front_wall( &MPI_LoadBalancer_E_tmp[8*i]);
}
}
// scramble
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int i = 0; i < quick_index_totalDevice.size(); i++)
{
for(int j=0; j < 8; j++)
{
MPI_WORK_DIST_E_GLOBAL[8*i+j] = MPI_LoadBalancer_E_tmp[8*MPI_LoadBalancer_index_set[i]+j];
}
}
// Update the storage of polarization vectors
std::complex<double> *dummy = MPI_WORK_DIST_P_GLOBAL[2];
MPI_WORK_DIST_P_GLOBAL[2] = MPI_WORK_DIST_P_GLOBAL[1];
MPI_WORK_DIST_P_GLOBAL[1] = MPI_WORK_DIST_P_GLOBAL[0];
MPI_WORK_DIST_P_GLOBAL[0] = dummy; // Will be overwritten by QWs, does not need to be zeroed
#endif
#ifdef USE_MAIN_TIMERS
MainStat->stop("VECSEL::prepare MPI");
#endif
} else {
// WORKERS WAIT HERE
#ifdef USE_MAIN_TIMERS
MainStat->start("VECSEL::MPI_comm_gath");
#endif
#ifdef ITERATE_QW
MPI_Gatherv( MPI_WORK_DIST_P_LOCAL, MPI_WORK_DIST_P_SIZE[MPI_MY_RANK],MPI_DOUBLE_COMPLEX, // Where I store my stuff
MPI_WORK_DIST_P_GLOBAL[0], MPI_WORK_DIST_P_SIZE, MPI_WORK_DIST_P_OFFSET, MPI_DOUBLE_COMPLEX, // Distribution of work
0, *MPI_WORK_GANG); // Who is recieving the data
#endif
#ifdef USE_MAIN_TIMERS
MainStat->stop("VECSEL::MPI_comm_gath");
#endif
}
/* ===========================================
* SOLVE SBE
* */
#ifdef ITERATE_QW
// MPI_Barrier(*MPI_WORK_GANG);
/*
if (MPI_MY_RANK==0)
{
for(int i = 0; i < MPI_WORK_DIST_TOTAL; i++)
{
MPI_WORK_DIST_E_GLOBAL[i] = std::complex<double>(i+1,i+1);
}
}
//=====
MPI_Comm new_world;
MPI_Comm_dup(*MPI_WORK_GANG,&new_world);
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_Barrier(new_world);
if (i == MPI_MY_RANK)
{
cout << "Process[" << i << "]: a)" << endl;
}
}
MPI_Barrier(new_world);
*/
//=====
#ifdef USE_MAIN_TIMERS
MainStat->start("VECSEL::MPI_comm_scatt");
#endif
// Send E(t) at the given QW to workers
MPI_Scatterv(MPI_WORK_DIST_E_GLOBAL, MPI_WORK_DIST_E_SIZE, MPI_WORK_DIST_E_OFFSET, MPI_DOUBLE_COMPLEX, // Distribution of work
MPI_WORK_DIST_E_LOCAL, MPI_WORK_DIST_E_SIZE[MPI_MY_RANK],MPI_DOUBLE_COMPLEX, // Where I store my stuff
0, *MPI_WORK_GANG); // Who is sending the data
#ifdef USE_MAIN_TIMERS
MainStat->stop("VECSEL::MPI_comm_scatt");
#endif
/*
for(int i = 0; i < 2*MPI_WORK_DIST_TOTAL; i++)
{
MPI_WORK_DIST_E_LOCAL[i] = MPI_WORK_DIST_E_GLOBAL[i];
}
*/
//=====
/*
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_Barrier(new_world);
if (i == MPI_MY_RANK)
{
cout << "Process[" << i << "]: b) E_local = ";
for(int j = 0; j < MPI_WORK_DIST_E_SIZE[MPI_MY_RANK]; j++)
{
cout << MPI_WORK_DIST_E_LOCAL[j] << " ";
}
cout << endl;
}
}
MPI_Barrier(new_world);
*/
//=====
#ifdef USE_MAIN_TIMERS
MainStat->start("VECSEL::compute all QWs");
#endif
// Compute P(t) for my own QWs using MPI_WORK_DIST_E_LOCAL
std::complex<double> *openmp_MPI_WORK_DIST_E_LOCAL = MPI_WORK_DIST_E_LOCAL;
int **openmp_MPI_WORK_DIST = MPI_WORK_DIST;
std::complex<double> *openmp_MPI_WORK_DIST_P_LOCAL = MPI_WORK_DIST_P_LOCAL;
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1) shared(openmp_MPI_WORK_DIST_E_LOCAL, openmp_MPI_WORK_DIST) firstprivate(openmp_MPI_WORK_DIST_P_LOCAL)
for(int j = openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < openmp_MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
// do work inside QW
//#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_2)
//for(int j = 0; j < number_K_points; j++)
int indx = quick_index_totalDevice[j]; // Index of device
if(modules[indx].isDevice())
{
std::complex<double> E_prop = openmp_MPI_WORK_DIST_E_LOCAL[ 8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))]; // Set propagating field at device
std::complex<double> E_prop_tp1 = openmp_MPI_WORK_DIST_E_LOCAL[1+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))];
Device *dev0 = modules[indx].getDevice();
// Electric field in device
double focusElectricField = dev0->getFocusE();
dev0->setElectricField(E_prop*focusElectricField);
std::complex<double> E_prop_tp05 = 0.5*(E_prop + E_prop_tp1);
dev0->setElectricField_tp1(E_prop_tp1*focusElectricField);
dev0->setElectricField_tp05(E_prop_tp05*focusElectricField);
// Iterate device
dev0->sbe_iterate(t_sim, DT);
double focusE = dev0->getFocusE();
double eff_qw = dev0->getEffectiveQW();
openmp_MPI_WORK_DIST_P_LOCAL[4*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))] = VECSEL_QW_FEEDBACK*dev0->getMacroscopicPolarization()*(eff_qw/focusE);
} else
{
std::complex<double> E_prop_fp = openmp_MPI_WORK_DIST_E_LOCAL[ 8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))]; // Set propagating field at device
std::complex<double> E_prop_fp_tp1 = openmp_MPI_WORK_DIST_E_LOCAL[1+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))];
std::complex<double> E_prop_fm = openmp_MPI_WORK_DIST_E_LOCAL[2+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))]; // Set propagating field at device
std::complex<double> E_prop_fm_tp1 = openmp_MPI_WORK_DIST_E_LOCAL[3+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))];
std::complex<double> E_prop_bp = openmp_MPI_WORK_DIST_E_LOCAL[4+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))]; // Set propagating field at device
std::complex<double> E_prop_bp_tp1 = openmp_MPI_WORK_DIST_E_LOCAL[5+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))];
std::complex<double> E_prop_bm = openmp_MPI_WORK_DIST_E_LOCAL[6+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))]; // Set propagating field at device
std::complex<double> E_prop_bm_tp1 = openmp_MPI_WORK_DIST_E_LOCAL[7+8*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))];
std::complex<double> E_prop_fp_tp05 = 0.5*(E_prop_fp + E_prop_fp_tp1);
std::complex<double> E_prop_fm_tp05 = 0.5*(E_prop_fm + E_prop_fm_tp1);
std::complex<double> E_prop_bp_tp05 = 0.5*(E_prop_bp + E_prop_bp_tp1);
std::complex<double> E_prop_bm_tp05 = 0.5*(E_prop_bm + E_prop_bm_tp1);
TwoArmDevice *dev0 = modules[indx].getTwoArmDevice();
// Electric field in device
double focusElectricField = dev0->getFocusE();
dev0->setElectricField_fp(E_prop_fp*focusElectricField);
dev0->setElectricField_fm(E_prop_fm*focusElectricField);
dev0->setElectricField_bp(E_prop_bp*focusElectricField);
dev0->setElectricField_bm(E_prop_bm*focusElectricField);
dev0->setElectricField_fp_tp1(E_prop_fp_tp1*focusElectricField);
dev0->setElectricField_fm_tp1(E_prop_fm_tp1*focusElectricField);
dev0->setElectricField_bp_tp1(E_prop_bp_tp1*focusElectricField);
dev0->setElectricField_bm_tp1(E_prop_bm_tp1*focusElectricField);
dev0->setElectricField_fp_tp05(E_prop_fp_tp05*focusElectricField);
dev0->setElectricField_fm_tp05(E_prop_fm_tp05*focusElectricField);
dev0->setElectricField_bp_tp05(E_prop_bp_tp05*focusElectricField);
dev0->setElectricField_bm_tp05(E_prop_bm_tp05*focusElectricField);
// Iterate device
dev0->sbe_iterate(t_sim, DT);
double eff_qw = dev0->getEffectiveQW();
openmp_MPI_WORK_DIST_P_LOCAL[4*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))] = VECSEL_QW_FEEDBACK*dev0->getMacroscopicPolarization_fp1()*(eff_qw/focusElectricField);
openmp_MPI_WORK_DIST_P_LOCAL[1+4*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))] = VECSEL_QW_FEEDBACK*dev0->getMacroscopicPolarization_fm1()*(eff_qw/focusElectricField);
openmp_MPI_WORK_DIST_P_LOCAL[2+4*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))] = VECSEL_QW_FEEDBACK*dev0->getMacroscopicPolarization_bp1()*(eff_qw/focusElectricField);
openmp_MPI_WORK_DIST_P_LOCAL[3+4*(j-(openmp_MPI_WORK_DIST[MPI_MY_RANK][0]-1))] = VECSEL_QW_FEEDBACK*dev0->getMacroscopicPolarization_bm1()*(eff_qw/focusElectricField);
}
}
#ifdef USE_MAIN_TIMERS
MainStat->stop("VECSEL::compute all QWs");
#endif
//=====
/*
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_Barrier(new_world);
if (i == MPI_MY_RANK)
{
cout << "Process[" << i << "]: d) P_local";
for(int j = 0; j < MPI_WORK_DIST_P_SIZE[MPI_MY_RANK]; j++)
{
cout << MPI_WORK_DIST_P_LOCAL[j] << " ";
}
cout << endl;
}
}
MPI_Barrier(new_world);
*/
//=====
// Send P(t) back to master
/*
if (MPI_MY_RANK>0)
{
#ifdef USE_MAIN_TIMERS
MainStat->start("VECSEL::MPI_comm_gath");
#endif
MPI_Gatherv( MPI_WORK_DIST_P_LOCAL, MPI_WORK_DIST_P_SIZE[MPI_MY_RANK],MPI_DOUBLE_COMPLEX, // Where I store my stuff
MPI_WORK_DIST_P_GLOBAL[0], MPI_WORK_DIST_P_SIZE, MPI_WORK_DIST_P_OFFSET, MPI_DOUBLE_COMPLEX, // Distribution of work
0, *MPI_WORK_GANG); // Who is recieving the data
#ifdef USE_MAIN_TIMERS
MainStat->stop("VECSEL::MPI_comm_gath");
#endif
}
*/
/*
for(int i = 0; i < MPI_WORK_DIST_TOTAL; i++)
{
MPI_WORK_DIST_P_GLOBAL[0][i] = MPI_WORK_DIST_P_LOCAL[i];
}
*/
//=====
/*
if (MPI_MY_RANK==0)
{
for(int j = 0; j < 3; j++)
{
cout << "P_global["<< j <<"][...] = ";
for(int i = 0; i < MPI_WORK_DIST_TOTAL; i++)
{
cout << MPI_WORK_DIST_P_GLOBAL[j][i] << " ";
}
cout << endl;
}
}
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_Barrier(new_world);
if (i == MPI_MY_RANK)
{
cout << "Process[" << i << "]: e)" << endl;
}
}
MPI_Barrier(new_world);
exit(-1);
*/
#endif
}
//===============================
// Maxwell functions
/* Initialize all simulation variables
* DT is the requested time step for the simulation
* Calles initialize on all objects
* */
void VECSEL::maxwell_initialize(double DT, int mpi_rank)
{
#ifdef MPI_BALANCE_WORKLOAD
MPI_load = new myTimer("Maxwell timer");
#endif
mpi_initialize_rank(mpi_rank);
if (MPI_MY_RANK==0)
{
// Initialize Transverse Dimension and output
output_E_real = new std::ofstream[VECSEL_transverse_points_number];
output_E_imag = new std::ofstream[VECSEL_transverse_points_number];
output_back_E_real = new std::ofstream[VECSEL_transverse_points_number];
output_back_E_imag = new std::ofstream[VECSEL_transverse_points_number];
output_Cav_Snapshot_E_real = new std::ofstream[VECSEL_transverse_points_number];
output_Cav_Snapshot_E_imag = new std::ofstream[VECSEL_transverse_points_number];
// Set initial pulse transverse profile
if (VECSEL_initial_transverse_pulse_profile == NULL)
{
VECSEL_initial_transverse_pulse_profile = new std::complex<double>[VECSEL_transverse_points_number];
}
double waist0 = (1.0/sqrt(2.0))*VECSEL_initial_transverse_FWHM/sqrt(2.0*log(2.0)); // For Gaussian shape with beam waist, fwhm of |E(t)|
//double waist0 = VECSEL_initial_transverse_FWHM/sqrt(2.0*log(2.0)); // For Gaussian shape with beam waist, fwhm of |E(t)|^2
for(int i = 0; i < VECSEL_transverse_points_number; i++)
{
VECSEL_initial_transverse_pulse_profile[i] = exp(-VECSEL_transverse_points_y[i]*VECSEL_transverse_points_y[i]/(waist0*waist0));
}
// Update delays in Cavities
double maximal_index = 0;
double minTime = 1.0;
double totalTime = 0;
bool toLargeDT = false;
VECSEL_DT = DT;
int ext_rtt_steps = 0; // Number of timesteps in a round-trip outside of the filters averaging interface length
int ext_rtt_steps2 = 0; // Number of timesteps in a round-trip outside of the filters for Initial condition
// Boundaries
modules[0].getBoundary()->initializeZero(VECSEL_transverse_points_number);
modules.back().getBoundary()->initializeZero(VECSEL_transverse_points_number);
// Cavities
if(quick_index_cavity.size()>0)
{
for(unsigned i=0; i<quick_index_cavity.size(); i++)
{
int indx = quick_index_cavity[i];
modules[indx].getCavity()->initializeZero(DT,VECSEL_transverse_points_number, VECSEL_transverse_points_y, VECSEL_transverse_points_R_max, VECSEL_transverse_points_boundary_guard_ratio); // Simulation variables
//Find next cavity's refractive index
double leftRefInd = modules[indx].getCavity()->getRefInd();
double leftWidth = modules[indx].getCavity()->getWidth();
if (leftRefInd > maximal_index)
{
maximal_index = leftRefInd;
}
// Get total length
totalTime += leftWidth/(c0/leftRefInd);
// Get minimal width
if (leftWidth/(c0/leftRefInd) < minTime)
{
minTime = leftWidth/(c0/leftRefInd);
}
ext_rtt_steps += 2*(modules[indx].getCavity()->getNumberOfTimesteps()-1); // CORRECT
ext_rtt_steps2 += 2*(modules[indx].getCavity()->getNumberOfTimesteps()-2); // CORRECT
}
}
if(quick_index_twoArmInterface.size()>0)
{
for(unsigned i=0; i<quick_index_twoArmInterface.size(); i++)
{
int indx = quick_index_twoArmInterface[i];
modules[indx].getTwoArmInterface()->initializeZero(DT,VECSEL_transverse_points_number, VECSEL_transverse_points_y, VECSEL_transverse_points_R_max, VECSEL_transverse_points_boundary_guard_ratio); // Simulation variables
//Find next cavity's refractive index
double leftRefInd = modules[indx].getTwoArmInterface()->getRefInd();
double leftWidth = modules[indx].getTwoArmInterface()->getWidth();
if (leftRefInd > maximal_index)
{
maximal_index = leftRefInd;
}
// Get total length
totalTime += leftWidth/(c0/leftRefInd);
// Get minimal width
if (leftWidth/(c0/leftRefInd) < minTime)
{
minTime = leftWidth/(c0/leftRefInd);
}
ext_rtt_steps += 2*(modules[indx].getTwoArmInterface()->getNumberOfTimesteps()-1); // CORRECT
ext_rtt_steps2 += 2*(modules[indx].getTwoArmInterface()->getNumberOfTimesteps()-2); // CORRECT
}
}
if(quick_index_twoArmCavity.size()>0)
{
for(unsigned i=0; i<quick_index_twoArmCavity.size(); i++)
{
int indx = quick_index_twoArmCavity[i];
// Simulation variables
double leftRefInd=0.0;
double leftWidth=0.0;
//Find next cavity's refractive index
modules[indx].getTwoArmCavity()->initializeZero(DT,VECSEL_transverse_points_number, VECSEL_transverse_points_y, VECSEL_transverse_points_R_max, VECSEL_transverse_points_boundary_guard_ratio);
leftRefInd = modules[indx].getTwoArmCavity()->getRefInd();
leftWidth = modules[indx].getTwoArmCavity()->getWidth();
ext_rtt_steps += 2*(modules[indx].getTwoArmCavity()->getNumberOfTimesteps()-1); // CORRECT
ext_rtt_steps2 += 2*(modules[indx].getTwoArmCavity()->getNumberOfTimesteps()-2); // CORRECT
if (leftRefInd > maximal_index)
{
maximal_index = leftRefInd;
}
// Get total length. Doubled accounting for correct number of passes
totalTime += 2.0*leftWidth/(c0/leftRefInd);
// Get minimal width
if (leftWidth/(c0/leftRefInd) < minTime)
{
minTime = leftWidth/(c0/leftRefInd);
}
}
}
if(quick_index_kerrCrystal.size()>0)
{
for(unsigned i=0; i<quick_index_kerrCrystal.size(); i++)
{
int indx = quick_index_kerrCrystal[i];
// Simulation variables
double leftRefInd=0.0;
double leftWidth=0.0;
//Find next cavity's refractive index
modules[indx].getKerrCrystal()->initializeZero(DT,VECSEL_transverse_points_number, VECSEL_transverse_points_y, VECSEL_transverse_points_R_max, VECSEL_transverse_points_boundary_guard_ratio);
leftRefInd = modules[indx].getKerrCrystal()->getRefInd();
leftWidth = modules[indx].getKerrCrystal()->getWidth();
ext_rtt_steps += 2*(modules[indx].getKerrCrystal()->getNumberOfTimesteps()-1); // CORRECT
ext_rtt_steps2 += 2*(modules[indx].getKerrCrystal()->getNumberOfTimesteps()-2); // CORRECT
if (leftRefInd > maximal_index)
{
maximal_index = leftRefInd;
}
// Get total length. Doubled accounting for correct number of passes
totalTime += 2.0*leftWidth/(c0/leftRefInd);
// Get minimal width
if (leftWidth/(c0/leftRefInd) < minTime)
{
minTime = leftWidth/(c0/leftRefInd);
}
}
}
if(quick_index_birefringentCrystal.size()>0)
{
for(unsigned i=0; i<quick_index_birefringentCrystal.size(); i++)
{
int indx = quick_index_birefringentCrystal[i];
// Simulation variables
double leftRefInd=0.0;
double leftWidth=0.0;
//Find next cavity's refractive index
modules[indx].getBirefringentCrystal()->initializeZero(DT,VECSEL_transverse_points_number, VECSEL_transverse_points_y, VECSEL_transverse_points_R_max, VECSEL_transverse_points_boundary_guard_ratio);
leftRefInd = modules[indx].getBirefringentCrystal()->getRefInd();
leftWidth = modules[indx].getBirefringentCrystal()->getWidth();
ext_rtt_steps += 2*(modules[indx].getBirefringentCrystal()->getNumberOfTimesteps()-1); // CORRECT
ext_rtt_steps2 += 2*(modules[indx].getBirefringentCrystal()->getNumberOfTimesteps()-2); // CORRECT
if (leftRefInd > maximal_index)
{
maximal_index = leftRefInd;
}
// Get total length. Doubled accounting for correct number of passes
totalTime += 2.0*leftWidth/(c0/leftRefInd);
// Get minimal width
if (leftWidth/(c0/leftRefInd) < minTime)
{
minTime = leftWidth/(c0/leftRefInd);
}
}
}
#ifndef CYCLIC_BOUNDARIES
VECSEL_ROUND_TRIP_TIME = 2.0*totalTime;
#endif
// Set FILTER DELAY
int filter_rtt_steps = 0;
for(unsigned i=0; i<modules.size(); i++)
{
if (modules[i].isFilter())
{
modules[i].getFilter()->setFilter_pluss_active_steps(ext_rtt_steps);
VECSEL_ROUND_TRIP_TIME += (modules[i].getFilter()->getFilterLength()-1)*VECSEL_DT;
filter_rtt_steps += (modules[i].getFilter()->getFilterLength()-1); // Subtract 2 to avoid double counting
}
}
VECSEL_ROUND_TRIP_ITERATIONS = ext_rtt_steps2 + filter_rtt_steps;
//cout << "STRUCTURE: LINEAR CAVITY" << endl;
cout << " Round trip time = " << VECSEL_ROUND_TRIP_TIME/ps << " [ps]" << endl;
cout << " Round trip #timesteps = " << ext_rtt_steps + filter_rtt_steps << " ("<< ext_rtt_steps <<", "<< filter_rtt_steps <<")" << endl;
cout << " Largest timestep = " << (minTime)/fs << " [fs]"<< endl;
// Output round trip time to file
std::stringstream fileName;
fileName << getToFileOutputKey() << "round_trip_time" << ".dat";
saveBinary(fileName.str(), &VECSEL_ROUND_TRIP_TIME, 1);
double cos_th_k_left, cos_th_k_right;
if(quick_index_cavity.size()>0)
{
// Set up transfer matrix
for(unsigned i=0; i<quick_index_cavity.size()-1; i++)
{
int indx = quick_index_cavity[i];
std::complex<double> nk = 1.0;
std::complex<double> T_Em = 1.0;
if(modules[indx+1].isTwoArmInterface())
{
int indx_k=indx+1;
nk = modules[indx_k].getTwoArmInterface()->getRefInd() + I*modules[indx_k].getTwoArmInterface()->getRefInd_im();
modules[indx_k].getCosTh(&cos_th_k_left, &cos_th_k_right);
nk = nk*cos_th_k_left;
T_Em = modules[indx_k].getTwoArmInterface()->get_transport_Eb_x0();
} else
{
int indx_k = quick_index_cavity[i+1];
nk = modules[indx_k].getCavity()->getRefInd() + I*modules[indx_k].getCavity()->getRefInd_im();
modules[indx_k].getCosTh(&cos_th_k_left, &cos_th_k_right);
nk = nk*cos_th_k_left;
T_Em = modules[indx_k].getCavity()->get_transport_Em_x0();
}
double loss_p = 0.0;
double loss_m = 0.0;
if (modules[indx+1].isLossElement())
{
modules[indx+1].getLossElement()->getLossCoeff(&loss_p, &loss_m);
}
modules[indx].getCavity()->set_transfer_matrix(nk, T_Em, loss_p, loss_m);
std::complex<double> a11,a12,a21,a22,*M;
modules[indx].getCavity()->get_transfer_matrix(&a11,&a12,&a21,&a22,&M);
}
}
if(quick_index_twoArmCavity.size()>0)
{
for(unsigned i=0; i<quick_index_twoArmCavity.size()-1; i++)
{
int indx = quick_index_twoArmCavity[i];
int indx_k = quick_index_twoArmCavity[i+1];
std::complex<double> nk = 1.0;
std::complex<double> T_Em = 1.0;
if(!modules[indx+1].isCavity())
{
nk = modules[indx_k].getTwoArmCavity()->getRefInd() + I*modules[indx_k].getTwoArmCavity()->getRefInd_im();
modules[indx_k].getCosTh(&cos_th_k_left, &cos_th_k_right);
nk = nk*cos_th_k_left;
T_Em = modules[indx_k].getTwoArmCavity()->get_transport_Eb_x0();
}
double loss_p = 0.0;
double loss_m = 0.0;
if (modules[indx+1].isLossElement())
{
modules[indx+1].getLossElement()->getLossCoeff(&loss_p, &loss_m);
}
modules[indx].getTwoArmCavity()->set_transfer_matrix(nk, T_Em, loss_p, loss_m);
std::complex<double> a11,a12,a21,a22,*M;
modules[indx].getTwoArmCavity()->get_transfer_matrix(&a11,&a12,&a21,&a22,&M, &M, &M, &M);
}
}
if(quick_index_kerrCrystal.size()>0)
{
for(unsigned i=0; i<quick_index_kerrCrystal.size(); i++)
{
int indx = quick_index_kerrCrystal[i];
int indx_post = indx+1;
std::complex<double> n_post = 1.0;
std::complex<double> n_pre = 1.0;
std::complex<double> T_Em = 1.0;
double loss_p = 0.0;
double loss_m = 0.0;
T_Em = modules[indx_post].getCavity()->get_transport_Em_x0();
n_post = modules[indx_post].getCavity()->getRefInd() + I*modules[indx_post].getCavity()->getRefInd_im();
modules[indx].getKerrCrystal()->set_transfer_matrix(n_post, T_Em, loss_p, loss_m);
}
}
if(quick_index_birefringentCrystal.size()>0)
{
for(unsigned i=0; i<quick_index_birefringentCrystal.size(); i++)
{
int indx = quick_index_birefringentCrystal[i];
int indx_pre = indx-1;
int indx_post = indx+1;
std::complex<double> n_post = 1.0;
std::complex<double> n_pre = 1.0;
std::complex<double> T_Em = 1.0;
double loss_p = 0.0;
double loss_m = 0.0;
T_Em = modules[indx_post].getTwoArmCavity()->get_transport_Eb_x0();
n_pre = modules[indx_pre].getTwoArmCavity()->getRefInd() + I*modules[indx_pre].getTwoArmCavity()->getRefInd_im();
n_post = modules[indx_post].getTwoArmCavity()->getRefInd() + I*modules[indx_pre].getTwoArmCavity()->getRefInd_im();
modules[indx].getBirefringentCrystal()->set_transfer_matrix(n_post, T_Em, loss_p, loss_m);
modules[indx].getBirefringentCrystal()->set_transfer_matrix_extraAxis(n_pre, n_post);
std::complex<double> a11_ex,a12_ex,a21_ex,a22_ex,*M;
modules[indx].getBirefringentCrystal()->get_transfer_matrix_extraAxis(&a11_ex,&a12_ex,&a21_ex,&a22_ex);
}
}
if(quick_index_twoArmInterface.size()>0)
{
for(unsigned i=0; i<quick_index_twoArmInterface.size(); i++)
{
int indx = quick_index_twoArmInterface[i];
int indx_k = indx+1;
int indx_end = quick_index_twoArmPostCav[i];
std::complex<double> nk = modules[indx_k].getTwoArmCavity()->getRefInd() + I*modules[indx_k].getTwoArmCavity()->getRefInd_im();
modules[indx_k].getCosTh(&cos_th_k_left, &cos_th_k_right);
nk = nk*cos_th_k_left;
std::complex<double> T_Em = modules[indx_k].getTwoArmCavity()->get_transport_Eb_x0();
std::complex<double> T_Ep_left = modules[indx-1].getCavity()->get_transport_Ep_x1();
std::complex<double> T_Ep_right = modules[indx_end].getCavity()->get_transport_Em_x0();
double loss_p = 0.0;
double loss_m = 0.0;
if (modules[indx+1].isLossElement())
{
modules[indx+1].getLossElement()->getLossCoeff(&loss_p, &loss_m);
}
modules[indx].getTwoArmInterface()->set_transfer_matrix(nk, T_Ep_left, T_Ep_right, T_Em, loss_p, loss_m);
std::complex<double> a11_left,a12_left,a21_left,a22_left, a11_right, a12_right, a21_right, a22_right;
modules[indx].getTwoArmInterface()->get_transfer_matrix(&a11_left,&a12_left,&a21_left,&a22_left, &a11_right, &a12_right, &a21_right, &a22_right);
}
}
// Output central frequency to file.
fileName.str("");
fileName << getToFileOutputKey() << "w0.dat";
double tmp = (2.0*Pi*c0)/getLambda();
saveBinary(fileName.str(), &tmp, 1);
// Output transverse grid to file
fileName.str("");
fileName << getToFileOutputKey() << "transverse_grid_y.dat";
saveBinary(fileName.str(), VECSEL_transverse_points_y, VECSEL_transverse_points_number);
double rL = modules.front().getBoundary()->getRefCoeff(); // Left boundary
fileName.str("");
fileName << getToFileOutputKey() << "reflection_left.dat";
saveBinary(fileName.str(), &rL, 1);
double rR = modules.back().getBoundary()->getRefCoeff(); // Right boundary
fileName.str("");
fileName << getToFileOutputKey() << "reflection_right" << ".dat";
saveBinary(fileName.str(), &rR, 1);
cout << "Intensity reflection coeff [L/R] = " << rL << " / " << rR << endl;
cout << "Intensity tansmission coeff [L/R] = " << 1.0-rL << " / " << 1.0-rR << endl;
// } // end: VCAV
} // if (MPI_MY_RANK==0)
#ifdef ITERATE_QW
// Find total #QWs
int total_work = quick_index_totalDevice.size();
// 1. Init. schedule for all nodes
mpi_initialize_work_arrays(total_work);
// 2. Initialize QWs located in MPI_WORK_DIST[MPI_MY_RANK][0] = 1, MPI_WORK_DIST[MPI_MY_RANK][1] = #QWs
// Serial
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int i = MPI_WORK_DIST[MPI_MY_RANK][0]-1; i < MPI_WORK_DIST[MPI_MY_RANK][1]; i++)
{
int index = quick_index_totalDevice[i];
if (modules[index].isDevice())
{
// Hole filling
modules[index].getDevice()->sbe_initialize(DT); // Simulation variables
} else
{
// Hole filling
modules[index].getTwoArmDevice()->sbe_initialize(DT); // Simulation variables
}
}
#endif
if (MPI_MY_RANK==0)
{
//=================================
// Cavity snapshot - Also in LOAD
//=================================
// Setup output to files
#ifdef USE_CAVITY_SNAPSHOT
//Not setup for TwoArmCavity
std::stringstream baseName;
baseName << getToFileOutputKey();
fileName.str("");
fileName << baseName.str() << "cav_snapshot_x.dat";
openAppendBinary(&output_Cav_Snapshot_x, fileName.str());
int inda = quick_index_cavity[0];
int indb = quick_index_cavity[quick_index_cavity.size()-1];
// Find correct indices
//VECSEL_cav_snapshot_index = new int[VECSEL_cav_snapshot_num_points];
double xi = modules[inda].getPosition0();
int count = 0;
while(xi < modules[indb].getPosition1())
{
VECSEL_cav_snapshot_x.push_back(xi);
// Find correct cavity
for(int k = 0; k < modules.size(); k++)
{
if (((VECSEL_cav_snapshot_x[count] >= modules[k].getPosition0())&&(VECSEL_cav_snapshot_x[count] < modules[k].getPosition1()))&&(modules[k].isCavity()))
{
VECSEL_cav_snapshot_index.push_back(k);
break;
}
}
int indx = VECSEL_cav_snapshot_index[count];
double DX;
if (modules[indx].getCavity()->getRefInd() > 1.0)
{
DX = 0.2*0.25*getLambda()/modules[indx].getCavity()->getRefInd(); // 5 points per L/4
} else {
// In AIR we will sample at one rate
DX = 0.5*0.25*getLambda()/modules[indx].getCavity()->getRefInd(); // dx <=0.25 L/n
}
if (xi+DX < modules[indx].getPosition1())
{
xi += DX;
} else {
xi = modules[indx].getPosition1();
}
count += 1;
}
VECSEL_cav_snapshot_num_points = count;
cout << "CAVITY SNAPSHOT: num points = " << VECSEL_cav_snapshot_num_points << endl;
output_Cav_Snapshot_x.write(reinterpret_cast<const char*>(&VECSEL_cav_snapshot_x[0]),VECSEL_cav_snapshot_num_points*sizeof(double));
output_Cav_Snapshot_x.close();
// Initialize E
VECSEL_cav_snapshot_E = new std::complex<double>[VECSEL_cav_snapshot_num_points];
VECSEL_cav_snapshot_E_re = new double[VECSEL_cav_snapshot_num_points];
VECSEL_cav_snapshot_E_im = new double[VECSEL_cav_snapshot_num_points];
// Initialize counters
VECSEL_cav_snapshot_output_wait = ceil(cav_snapshot_freq/DT);
VECSEL_cav_snapshot_output_count = VECSEL_cav_snapshot_output_wait;
#endif
}
// Find LENS cavity and move to correct quick index list
// Above the round-trip time includes the lens cavity
// thus: this should only change the Maxwell update iteration
quick_index_cavity_noBPM = quick_index_cavity;
int BPM_ctr=0;
for(unsigned i=0; i<quick_index_cavity.size(); i++)
{
int indx = quick_index_cavity[i];
if (modules[indx].getCavity()->getName().substr(0,3) == "BPM")
{
if(modules[indx].getCavity()->getName().substr(0,5) == "BPMHC")
{
// Add to quick_index_cavity_halfCav
quick_index_cavity_lens_halfCav.push_back(indx);
} else if (modules[indx].getCavity()->getName().substr(0,5) == "BPMFS")
{
quick_index_cavity_freeSpace.push_back(indx);
} else if (modules[indx].getCavity() -> getName().substr(0,8) == "BPMTRANS")
{
// Add to quick_index_cavity_lens
quick_index_cavity_lens.push_back(indx);
} else
{
cout<<"BPM cavity not recognized"<<endl;
exit(-1);
}
// Remove from quick_index_cavity_noBPM
quick_index_cavity_noBPM.erase(quick_index_cavity_noBPM.begin()+i-BPM_ctr);
BPM_ctr++;
}
}
if (quick_index_birefringentCrystal.size()>0 && quick_index_birefringentCrystal.back()==getNumberModules())
{
cout<<"Birefringent crystal at last element. Untested. Quitting."<<endl;
exit(-1);
}
if (quick_index_twoArmCavity.size()>0)
{
// Find two arm cavities with NO QWs between them
for(unsigned i=0; i<quick_index_twoArmCavity.size()-1; i++)
{
int i1 = quick_index_twoArmCavity[i];
int i2 = quick_index_twoArmCavity[i+1];
if (i2-i1 == 1)
{
// No distance => No QWs
quick_index_twoArmCavity_noQW.push_back(i1);
} else {
// Can be QWs between
bool has_qw = false;
for(int j = i1; j <= i2; j++)
{
if (modules[j].isTwoArmDevice())
{
has_qw = true;
break;
}
}
if (has_qw == true)
{
quick_index_twoArmCavity_QW.push_back(i1);
quick_index_twoArmCavity_QW.push_back(i2);
} else {
quick_index_twoArmCavity_noQW.push_back(i1);
}
}
}
quick_index_twoArmCavity_noQW.push_back(quick_index_twoArmCavity.back());
}
if(quick_index_cavity.size()>0)
{
// Find cavities with NO QWs between them
for(unsigned i=0; i<quick_index_cavity.size()-1; i++)
{
int i1 = quick_index_cavity[i];
int i2 = quick_index_cavity[i+1];
if (i2-i1 == 1)
{
// No distance => No QWs
quick_index_cavity_noQW.push_back(i1);
} else {
// Can be QWs between
bool has_qw = false;
for(int j = i1; j <= i2; j++)
{
if (modules[j].isDevice())
{
has_qw = true;
break;
}
}
if (has_qw == true)
{
quick_index_cavity_QW.push_back(i1);
quick_index_cavity_QW.push_back(i2);
} else {
quick_index_cavity_noQW.push_back(i1);
}
}
}
quick_index_cavity_noQW.push_back(quick_index_cavity.back());
}
}
/* The initaial pulse in system
* Will create a seed pulse for a given amount of time.
* There are multiple options for the type of pulse
* -> Bump function
* -> Sinc function
* -> (default) Sech()^2
* Or one can use
* -> dual frequency input
* -> Single frequency input
* -> Triangular pulse input
* Or one can turn it off for spont. emission. as input.
* */
void VECSEL::maxwell_initial_E(double x_t , std::complex<double> *tmp)
{
// if (init_VECSEL_iteration < VECSEL_ROUND_TRIP_ITERATIONS)
if (abs(x_t-VECSEL_initial_delay) < 1000*ps)
{
init_VECSEL_iteration++;
// Energy: int(|E|^2) = 4*(amp^2)/(3*const1)
double const1 = 1.76275/VECSEL_initial_fwhm;// Correct constant , fwhm of |E(t)|
//double const1 = 1.21169/VECSEL_initial_fwhm;// Correct constant , fwhm of |E(t)|^2
double mc = cosh((x_t - VECSEL_initial_delay)*const1);
std::complex<double> shift = exp(-I*(VECSEL_initial_energy_shift)*(x_t - VECSEL_initial_delay));
std::complex<double> z_profile = VECSEL_initial_amplitude*shift/(mc*mc);
// Scale transverse profile with the z_profile
memset(tmp,0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
cblas_zaxpy(VECSEL_transverse_points_number, &z_profile, VECSEL_initial_transverse_pulse_profile, 1, tmp, 1);
} else {
memset(tmp,0,VECSEL_transverse_points_number*sizeof(std::complex<double>));
}
}
//=================
// Misc functions
/* Return the cavity field evaluatated at the given device nr. Not setup for VCAV */
void VECSEL::misc_getFieldAtDevice(int device_nr, std::complex<double> *tmp)
{
if(quick_index_device.size() > 0)
{
if (device_nr >= quick_index_totalDevice.size())
{
cout << "misc_getFieldAtDevice(): Requesting device not in list" << endl;
cout << "Requesting = " << device_nr << endl;
cout << "# of devices = " << quick_index_device.size() << endl;
}
// Index of previous cavity
int indx_k = quick_index_device_previous_cavity[device_nr];
modules[indx_k].getCavity()->evaluateEprop_x1(tmp);
} else {
// Use boundary
if (modules.back().isBoundary())
{
// Index of previous cavity
int indx_k = quick_index_cavity.back();
modules[indx_k].getCavity()->evaluateEprop_x1(tmp);
} else {
cout << "misc_getFieldAtDevice():: Cannot detect any cavities.." << endl;
exit(-1);
}
}
}
//=====================
// Filter functions
void VECSEL::setFilter_pluss_minus_pass()
{
for(unsigned i = 0; i < modules.size(); i++)
{
if (modules[i].isFilter()){
modules[i].getFilter()->setFilter_pluss_PassThroughDelay(); // Delay "filter"
modules[i].getFilter()->setFilter_minus_PassThroughDelay(); // Delay "filter"
}
}
}
void VECSEL::setFilter_pluss_gauss_minus_pass(double wa_s, double wb_s, double width_s, double w0_s)
{
for(unsigned i = 0; i < modules.size(); i++)
{
if (modules[i].isFilter()){
modules[i].getFilter()->setFilter_minus_PassThroughDelay(); // Delay "filter"
modules[i].getFilter()->setFilter_pluss_doubleGauss_flatTopWindow(wa_s, wb_s, width_s, w0_s); // Gauss filter
}
}
}
//=====================================================
// Functions for access to devices and their variables
/* Disable the spontaneous emissions from all devices
* If one wants to do this all the time, it is faster to turn it off from the flag.
* */
void VECSEL::device_disable_spont_emissions_all()
{
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
if (modules[indx].isDevice())
{
modules[indx].getDevice()->sbe_set_spont_emissions(false);
} else
{
modules[indx].getTwoArmDevice()->sbe_set_spont_emissions(false);
}
}
#endif
}
/* When using a realistic pump and you want to change the parameters
* Set the pump parameters for each device
* */
void VECSEL::device_set_qw_real_pump_parameters(double W0, double E0, double ETA, double nCavity)
{
// TODO: Modify Pump strength based on QW placement and pump absorbtion...
int ind_qw_cav = 0;
int ind_air_cav = 0;
// Possible expansion: Set strength different for each QW based on pump frequency
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
if (modules[indx].isDevice())
{
modules[indx].getDevice()->sbe_set_real_pump_model(W0, E0, ETA,VECSEL_DT);
} else
{
modules[indx].getTwoArmDevice()->sbe_set_real_pump_model(W0, E0, ETA,VECSEL_DT);
}
}
#endif
}
/* Change background carrier density in all devices
* */
void VECSEL::device_set_background_carrier_density(double new_density,int NUM_QW)
{
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
if (modules[indx].isDevice())
{
modules[indx].getDevice()->sbe_set_background_carrier_density(new_density);
} else
{
modules[indx].getTwoArmDevice()->sbe_set_background_carrier_density(new_density);
}
}
#endif
}
/* Set a delay for when computations are supposed to start
* Used on in special situations
* */
void VECSEL::device_set_computational_delay(double delay)
{
// For a given delay in computation
// computations will start after the delay
#ifdef ITERATE_QW
#pragma omp parallel for num_threads(OMP_THREADS_LEVEL_1)
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
int indx = quick_index_totalDevice[j]; // Index of device
if(modules[indx].isDevice())
{
modules[indx].getDevice()->sbe_delay_computations(delay);
} else
{
modules[indx].getTwoArmDevice()->sbe_delay_computations(delay);
}
}
#endif
cout << "device_set_computational_delay: " << delay/ps << " [ps] Complete" << endl;
}
//=================================
// Diagnostics function
/* Remove all field content in the cavity
* */
void VECSEL::diagnostics_zero_all_cavity_fields()
{
for(unsigned i = 0; i < modules.size(); i++)
{
if (modules[i].isCavity())
{
modules[i].getCavity()->clearFields();
} else if (modules[i].isFilter()){
modules[i].getFilter()->clearFields();
}
}
}
/* Set this in order to REMOVE the polarization feedback into the pulse
* */
void VECSEL::diagnostics_set_qw_feedback(double newFeedback)
{
VECSEL_QW_FEEDBACK = newFeedback;
}
/* Return the maximally allowed timestep based on cavity lengths
* */
double VECSEL::diagnostics_findMaxTimestep()
{
double dt = 1000;
if(quick_index_cavity.size()>0)
{
for(unsigned i=0; i<quick_index_cavity.size(); i++)
{
int indx = quick_index_cavity[i];
//Find next cavity's refractive index
double leftRefInd = modules[indx].getCavity()->getRefInd();
double leftWidth = modules[indx].getCavity()->getWidth();
// Get minimal width
if (leftWidth/(c0/leftRefInd) < dt)
{
dt = leftWidth/(c0/leftRefInd);
}
}
}
if(quick_index_twoArmCavity.size()>0)
{
for(unsigned i=0; i<quick_index_twoArmCavity.size(); i++)
{
int indx = quick_index_twoArmCavity[i];
//Find next cavity's refractive index
double leftRefInd = modules[indx].getTwoArmCavity()->getRefInd();
double leftWidth = modules[indx].getTwoArmCavity()->getWidth();
// Get minimal width
if (leftWidth/(c0/leftRefInd) < dt)
{
dt = leftWidth/(c0/leftRefInd);
}
}
}
return dt;
}
/* To remove everything from this device
* */
void VECSEL::diagnostics_clear_VECSEL()
{
cout << "VECSEL: Remove all modules" << endl;
for(unsigned i=0; i<getNumberModules(); i++)
{
modules[i].Remove();
}
modules.clear();
cout << "VECSEL: Clearing variables" << endl;
setName("");
setLambda(0.0);
}
/* Initialize MPI worker arrays
* distribute the total work as equal as possible over all nodes
* Note: Will quit if the number of nodes > number of devices
* */
void VECSEL::mpi_initialize_work_arrays(int total_devices)
{
// Set up QW distribution depending on #QWs and #NODES
if (MPI_WORK_GANG_SIZE < 1)
{
cout << "mpi_initialize_work_arrays()::ERROR cannot have number of nodes < 1.." << endl;
cout << "total devices = " << total_devices << endl;
cout << "# of nodes = " << MPI_WORK_GANG_SIZE << endl;
cout << " Please run program with number of nodes >= 1" << endl << endl;
MPI_Finalize();
exit(-1);
}
// Set up work distribution
MPI_WORK_DIST = new int*[MPI_WORK_GANG_SIZE];
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DIST[i] = new int[2]; // Store QW # from-to
}
if (total_devices < 0)
{
cout << "mpi_initialize_work_arrays()::ERROR cannot process < 0 devices.." << endl;
cout << "total devices = " << total_devices << endl;
cout << "# of nodes = " << MPI_WORK_GANG_SIZE << endl;
cout << " Please run program with total number of devices >= 0" << endl << endl;
MPI_Finalize();
exit(-1);
}
if ((MPI_WORK_GANG_SIZE>1)&&(total_devices < MPI_WORK_GANG_SIZE))
{
cout << "mpi_initialize_work_arrays()::ERROR Too MANY nodes used!" << endl;
cout << "total devices = " << total_devices << endl;
cout << "# of nodes = " << MPI_WORK_GANG_SIZE << endl;
cout << " Please run program with number of nodes <= number of devices" << endl << endl;
MPI_Finalize();
exit(-1);
}
MPI_WORK_DIST_TOTAL = total_devices;
MPI_Barrier(*MPI_WORK_GANG);
//===============================
// Work scheduling
MPI_WORK_DEVICE_SIZE = new int[MPI_WORK_GANG_SIZE];
if (total_devices > 0)
{
MPI_LoadBalancer_index_set = new int[total_devices];
for(int i = 0; i < total_devices; i++)
{
MPI_LoadBalancer_index_set[i] = i;
}
#ifdef MPI_BALANCE_WORKLOAD
// Use uniform distribution to allow for easy timing
//====================================================================
double work_per_thread = ((double)MPI_WORK_DIST_TOTAL/(double)MPI_WORK_GANG_SIZE)/((double)OMP_THREADS_LEVEL_1);
if (work_per_thread >= 10)
{
// Safe region
} else {
cout << "Hybrid MPI-OpenMP issue.." << endl;
cout << "The # work/thread is too low and speedup will saturate above work/thread < 10" << endl;
cout << "Parallel speedup ratio is saturating, but total time will still improve" << endl;
cout << "Total work = " << MPI_WORK_DIST_TOTAL << endl;
cout << "MPI_nodes = " << MPI_WORK_GANG_SIZE << endl;
cout << "Thread/node = " << OMP_THREADS_LEVEL_1 << endl;
cout << "work/thread = " << work_per_thread << endl;
// exit(-1);
}
// MPI_WORK_DIST[n][0] with elements in [1,MPI_WORK_DIST_TOTAL]
// MPI_WORK_DIST[n][1] with elements in [1,MPI_WORK_DIST_TOTAL]
// such that MPI_WORK_DIST[n][0] <= MPI_WORK_DIST[n][1]
// for each MPI_node: n
int base_val = floor((double)MPI_WORK_DIST_TOTAL/(double)MPI_WORK_GANG_SIZE);
int remain = MPI_WORK_DIST_TOTAL - base_val*MPI_WORK_GANG_SIZE;
int remove = MPI_WORK_GANG_SIZE-1-remain;
if (remain > 0)
{
// Work is NOT multiple of workforce
MPI_WORK_DEVICE_SIZE[0] = base_val - remove;
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DEVICE_SIZE[i] = base_val + 1;
}
} else {
// Work is multiple of workforce
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DEVICE_SIZE[i] = base_val;
}
}
//========================================================
// Finetune hybrid MPI node usage for better performance.
// Only tuned for FAST QWs i.e. no 2nd Born scattering
//#if !defined(USE_ISAK_HOLE_FILLING) && !defined(USE_ISAK_HOLE_FILLING_TABLE)
#if defined(__ICC) || defined(__INTEL_COMPILER)
if (1.0/(double)MPI_WORK_GANG_SIZE < 0.1)
#else
if (false)
#endif
{
// Reduce MASTER workload
// This reduces memory load times for the master node AND reduces wait times
// but only usefull for large number of MPI nodes.
if (MPI_WORK_DEVICE_SIZE[0] >= MPI_WORK_GANG_SIZE-1)
{
// Option 1: NO QWs for master
int cnt = MPI_WORK_DEVICE_SIZE[0];
MPI_WORK_DEVICE_SIZE[0] = 0;
int counter = 1;
while (cnt>0)
{
if( counter >= MPI_WORK_GANG_SIZE)
{
counter = 1;
}
MPI_WORK_DEVICE_SIZE[counter] += 1;
cnt--;
counter++;
}
/*
// Option 2: All workers have SAME number of QWs, master takes remaining or 0
int mult = floor((double)MPI_WORK_DEVICE_SIZE[0]/((double)MPI_WORK_GANG_SIZE-1));
int scale = +mult; // Give master less work
MPI_WORK_DEVICE_SIZE[0] = MPI_WORK_DEVICE_SIZE[0] - scale*(MPI_WORK_GANG_SIZE-1);
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DEVICE_SIZE[i] = MPI_WORK_DEVICE_SIZE[i] + scale;
}
*/
}
} else if ((MPI_WORK_GANG_SIZE > 1)&&((work_per_thread < 200))) {
// For cases where there is a medium amount of work, but not enough MPI workers
// Reduce work on MASTER by 10%, if possible
// This will compensate for memory load times for very high number of QWs..
// This number (10%) can be changed if you think this is a problem..
if (MPI_WORK_DEVICE_SIZE[0] >= MPI_WORK_GANG_SIZE-1)
{
int mult = floor(0.1*MPI_WORK_DEVICE_SIZE[0]/((double)MPI_WORK_GANG_SIZE-1));
int scale = +mult; // Give master less work
MPI_WORK_DEVICE_SIZE[0] = MPI_WORK_DEVICE_SIZE[0] - scale*(MPI_WORK_GANG_SIZE-1);
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DEVICE_SIZE[i] = MPI_WORK_DEVICE_SIZE[i] + scale;
}
}
}
#else
// Use preset from file OR attempt to estimate best setting
if (fileExists("MPI_CONFIG_WEIGHTS.dat"))
{
// IF MPI preset exists, load from file
// Format:
// Line 1: Number of subgroups, Sub-group-size
// Line 2: Total number of devices, Index set of jobs
FILE *mpi_setup = fopen("MPI_CONFIG_WEIGHTS.dat","r+");
if (mpi_setup != NULL)
{
double maxwell_time, maxwell_std;
double device_times[total_devices];
// Load MPI work sizes
int row_size = -1;
fscanf(mpi_setup, "%d", &row_size);
if (row_size == total_devices)
{
fscanf(mpi_setup, "%lf %lf", &maxwell_time, &maxwell_std);
for(int i = 0; i < row_size; i++)
{
double time, std;
fscanf(mpi_setup, "%lf %lf", &time, &std);
device_times[i] = time + 3.0*std;
}
fclose(mpi_setup);
} else {
cout << "mpi_initialize_work_arrays()::ERROR file MPI_CONFIG_WEIGHTS.dat is set for a different total number of devices" << endl;
cout << "total number of devices = " << total_devices << endl;
cout << "value in file = " << row_size << endl;
exit(-1);
}
MPI_LoadBalancer = new parSchedule();
if (1.0/(double)MPI_WORK_GANG_SIZE < 0.05)
{
MPI_LoadBalancer->optimize_schedule(total_devices, device_times, MPI_WORK_GANG_SIZE-1, 0.0, 1.0);
MPI_WORK_DEVICE_SIZE[0] = 0;
MPI_LoadBalancer->get_sub_group_info(&(MPI_WORK_DEVICE_SIZE[1]));
} else {
MPI_LoadBalancer->optimize_schedule(total_devices, device_times, MPI_WORK_GANG_SIZE, 2.0*(maxwell_time+3.0*maxwell_std), 1.25);
MPI_LoadBalancer->get_sub_group_info(&(MPI_WORK_DEVICE_SIZE[0]));
}
MPI_LoadBalancer->get_sub_group_index(MPI_LoadBalancer_index_set);
// Apply balancing
int current_device_index[total_devices];
int current_device_index_prev_cav[total_devices];
for(int i = 0; i < total_devices; i++)
{
current_device_index[i] = quick_index_totalDevice[i];
current_device_index_prev_cav[i] = quick_index_device_previous_cavity[i];
}
for(int i = 0; i < total_devices; i++)
{
quick_index_totalDevice[i] = current_device_index[MPI_LoadBalancer_index_set[i]];
quick_index_device_previous_cavity[i] = current_device_index_prev_cav[MPI_LoadBalancer_index_set[i]];
}
if (MPI_MY_RANK == 0)
{
MPI_LoadBalancer->file_write_structure("MPI_CONFIG_BALANCED.dat");
}
delete MPI_LoadBalancer;
}
} else {
// No MPI preset found, using density data to esitmate weights and attempt balancing
// Weights for boole: 1.86-2.02
// Weights for hamilton: 2.49-2.72
double est_weights[total_devices];
double max_weight = 1.0;
for(int i = 0; i < total_devices; i++)
{
int index = quick_index_totalDevice[i];
if (modules[index].isDevice())
{
double qw_density_scale = modules[index].getDevice()->getTransverseBackgroundDensityScale();
if (qw_density_scale > 0.75)
{
est_weights[i] = 1.0;
} else
{
est_weights[i] = 1.94; // boole
//est_weights[i] = 2.6; // hamilton, but gives only a minor correction
}
} else
{
double qw_density_scale = modules[index].getTwoArmDevice()->getTransverseBackgroundDensityScale();
if (qw_density_scale > 0.75)
{
est_weights[i] = 1.0;
} else
{
est_weights[i] = 1.94; // boole
//est_weights[i] = 2.6; // hamilton, but gives only a minor correction
}
est_weights[i]*=3.0;
}
if (est_weights[i] > max_weight)
{
max_weight = est_weights[i];
}
}
MPI_LoadBalancer = new parSchedule();
if (1.0/(double)MPI_WORK_GANG_SIZE < 0.05)
{
MPI_LoadBalancer->optimize_schedule(total_devices, est_weights, MPI_WORK_GANG_SIZE-1, 0.0, 1.0);
MPI_WORK_DEVICE_SIZE[0] = 0;
MPI_LoadBalancer->get_sub_group_info(&(MPI_WORK_DEVICE_SIZE[1]));
} else {
MPI_LoadBalancer->optimize_schedule(total_devices, est_weights, MPI_WORK_GANG_SIZE, 2*max_weight, 1.25);
MPI_LoadBalancer->get_sub_group_info(&(MPI_WORK_DEVICE_SIZE[0]));
}
MPI_LoadBalancer->get_sub_group_index(MPI_LoadBalancer_index_set);
if (MPI_MY_RANK == 0)
{
MPI_LoadBalancer->file_write_structure("MPI_CONFIG_BALANCED_est.dat");
}
delete MPI_LoadBalancer;
// Apply balancing
int current_device_index[total_devices];
int current_device_index_prev_cav[total_devices];
for(int i = 0; i < total_devices; i++)
{
current_device_index[i] = quick_index_totalDevice[i];
current_device_index_prev_cav[i] = quick_index_device_previous_cavity[i];
}
for(int i = 0; i < total_devices; i++)
{
quick_index_totalDevice[i] = current_device_index[MPI_LoadBalancer_index_set[i]];
//WTFF-quick_index_device_previous_cavity[i] = current_device_index_prev_cav[MPI_LoadBalancer_index_set[i]];
}
}
#endif
} else {
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DEVICE_SIZE[i] = 0;
}
}
MPI_Barrier(*MPI_WORK_GANG);
/*
*/
//====================================================================
MPI_WORK_DEVICE_TIMING_SIZE = new int[MPI_WORK_GANG_SIZE];
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DEVICE_TIMING_SIZE[i] = 2*MPI_WORK_DEVICE_SIZE[i];
}
MPI_WORK_DEVICE_TIMING_OFFSET = new int[MPI_WORK_GANG_SIZE];
MPI_WORK_DEVICE_TIMING_OFFSET[0] = 0;
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DEVICE_TIMING_OFFSET[i] = MPI_WORK_DEVICE_TIMING_OFFSET[i-1] + MPI_WORK_DEVICE_TIMING_SIZE[i-1];
}
// Transfer size data to workforce
if (MPI_WORK_DEVICE_SIZE[0]>0)
{
MPI_WORK_DIST[0][0] = 1;
MPI_WORK_DIST[0][1] = MPI_WORK_DEVICE_SIZE[0];
} else {
MPI_WORK_DIST[0][0] = 1;
MPI_WORK_DIST[0][1] = 0;
}
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DIST[i][0] = MPI_WORK_DIST[i-1][1] + 1;
MPI_WORK_DIST[i][1] = MPI_WORK_DIST[i-1][1] + MPI_WORK_DEVICE_SIZE[i];
}
/*
// Simple work schedule
MPI_WORK_DIST[0][0] = 1;
MPI_WORK_DIST[0][1] = floor((double)MPI_WORK_DIST_TOTAL/(double)MPI_WORK_GANG_SIZE); // Work of master node, floor
//MPI_WORK_DIST[0][1] = ceil((double)MPI_WORK_DIST_TOTAL/(double)MPI_WORK_GANG_SIZE); // Work of master node, ceil
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
int tmp1 = floor((double)(MPI_WORK_DIST_TOTAL-MPI_WORK_DIST[i-1][1])/(double)(MPI_WORK_GANG_SIZE-i));
MPI_WORK_DIST[i][0] = MPI_WORK_DIST[i-1][1] + 1;
MPI_WORK_DIST[i][1] = MPI_WORK_DIST[i-1][1] + tmp1;
}
*/
// MPI scatterv and gatherv organization arrays
MPI_WORK_DIST_E_OFFSET = new int[MPI_WORK_GANG_SIZE];
MPI_WORK_DIST_E_OFFSET[0] = 0;
MPI_WORK_DIST_E_SIZE = new int[MPI_WORK_GANG_SIZE];
MPI_WORK_DIST_E_SIZE[0] = 8*(MPI_WORK_DIST[0][1] - MPI_WORK_DIST[0][0]+1);
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DIST_E_OFFSET[i] = MPI_WORK_DIST_E_OFFSET[i-1] + MPI_WORK_DIST_E_SIZE[i-1];
MPI_WORK_DIST_E_SIZE[i] = 8*(MPI_WORK_DIST[i][1] - MPI_WORK_DIST[i][0]+1);
}
MPI_WORK_DIST_P_OFFSET = new int[MPI_WORK_GANG_SIZE];
MPI_WORK_DIST_P_OFFSET[0] = 0;
MPI_WORK_DIST_P_SIZE = new int[MPI_WORK_GANG_SIZE];
MPI_WORK_DIST_P_SIZE[0] = 4*(MPI_WORK_DIST[0][1] - MPI_WORK_DIST[0][0]+1);
for(int i = 1; i < MPI_WORK_GANG_SIZE; i++)
{
MPI_WORK_DIST_P_OFFSET[i] = MPI_WORK_DIST_P_OFFSET[i-1] + MPI_WORK_DIST_P_SIZE[i-1];
MPI_WORK_DIST_P_SIZE[i] = 4*(MPI_WORK_DIST[i][1] - MPI_WORK_DIST[i][0]+1);
}
// Find max number of WORK for any worker
int MPI_WORK_DIST_E_SIZE_MAX = 0;
int MPI_WORK_DIST_P_SIZE_MAX = 0;
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
if (MPI_WORK_DIST_E_SIZE[i] > MPI_WORK_DIST_E_SIZE_MAX)
{
MPI_WORK_DIST_E_SIZE_MAX = MPI_WORK_DIST_E_SIZE[i];
}
if (MPI_WORK_DIST_P_SIZE[i] > MPI_WORK_DIST_P_SIZE_MAX)
{
MPI_WORK_DIST_P_SIZE_MAX = MPI_WORK_DIST_P_SIZE[i];
}
}
// Local memory of work
MPI_WORK_DIST_E_LOCAL = new std::complex<double>[MPI_WORK_DIST_E_SIZE_MAX];
MPI_WORK_DIST_P_LOCAL = new std::complex<double>[MPI_WORK_DIST_P_SIZE_MAX];
for(int i =0; i < MPI_WORK_DIST_E_SIZE_MAX; i++)
{
MPI_WORK_DIST_E_LOCAL[i] = 0;
}
for(int i =0; i < MPI_WORK_DIST_P_SIZE_MAX; i++)
{
MPI_WORK_DIST_P_LOCAL[i] = 0;
}
MPI_WORK_DIST_P_GLOBAL = new std::complex<double>*[3];
for(int i =0; i < 3; i++)
{
MPI_WORK_DIST_P_GLOBAL[i] = NULL;
}
if (MPI_MY_RANK == 0)
{
// In the master thread, the polarizations for each QW are all in one array
MPI_WORK_DIST_E_GLOBAL = new std::complex<double>[8*MPI_WORK_DIST_TOTAL];
for(int j = 0; j < 8*MPI_WORK_DIST_TOTAL; j++)
{
MPI_WORK_DIST_E_GLOBAL[j] = 0;
}
for(int i = 0; i < 3; i++)
{
MPI_WORK_DIST_P_GLOBAL[i] = new std::complex<double>[4*MPI_WORK_DIST_TOTAL];
for(int j = 0; j < 4*MPI_WORK_DIST_TOTAL; j++)
{
MPI_WORK_DIST_P_GLOBAL[i][j] = 0;
}
}
MPI_LoadBalancer_P_tmp = new std::complex<double>[4*MPI_WORK_DIST_TOTAL];
MPI_LoadBalancer_E_tmp = new std::complex<double>[8*MPI_WORK_DIST_TOTAL];
cout << "MPI WORK DISTRIBUTED OVER " << MPI_WORK_GANG_SIZE << " NODES" << endl;
cout << "MPI_WORK_DIST[][]: " << endl;
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
cout << "MPI_WORK_DIST[" << i << "] = [" << MPI_WORK_DIST[i][0] << ", " << MPI_WORK_DIST[i][1] << "]" << endl;
}
cout << "MPI_WORK_DIST_E_OFFSET[] = ";
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
cout << MPI_WORK_DIST_E_OFFSET[i] << " ";
}
cout << endl;
cout << "MPI_WORK_DIST_E_SIZE[]: ";
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
cout << MPI_WORK_DIST_E_SIZE[i] << " ";
}
cout << endl;
cout << "MPI_WORK_DIST_P_OFFSET[] = ";
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
cout << MPI_WORK_DIST_P_OFFSET[i] << " ";
}
cout << endl;
cout << "MPI_WORK_DIST_P_SIZE[]: ";
for(int i = 0; i < MPI_WORK_GANG_SIZE; i++)
{
cout << MPI_WORK_DIST_P_SIZE[i] << " ";
}
cout << endl;
}
// SET UP MPI TIMERS
#ifdef USE_MAIN_TIMERS
for(int j = MPI_WORK_DIST[MPI_MY_RANK][0]-1; j < MPI_WORK_DIST[MPI_MY_RANK][1]; j++)
{
std::stringstream oldName;
int indx = quick_index_totalDevice[j]; // Index of device
if(modules[indx].isDevice())
{
oldName << modules[indx].getDevice()->getName();
} else
{
oldName << modules[indx].getTwoArmDevice()->getName();
}
#ifdef USE_DEVICE_TIMERS
MainStat->newSubTimer("VECSEL::compute all QWs",oldName.str());
#endif
}
#endif
}
/* Initialize MPI rank
*/
void VECSEL::mpi_initialize_rank(int my_rank)
{
MPI_MY_RANK = my_rank;
}
/* Set the communication group for MPI workers
*/
void VECSEL::mpi_set_work_gang(MPI_Comm *work_gang)
{
MPI_WORK_GANG = work_gang;
MPI_Comm_size(*MPI_WORK_GANG,&MPI_WORK_GANG_SIZE);
}
| 31.058036 | 322 | 0.676185 | [
"object",
"shape",
"vector",
"model"
] |
00761d01e96f40f105e202c53d0b35e06b48c76e | 8,048 | cpp | C++ | Tempest/Graphics/Dx12/Managers/PipelineManager.cpp | Alekssasho/TempoEngine | 60e23e4ef743f8a9f44f8c576457a5feb27f70b9 | [
"MIT"
] | 7 | 2020-08-02T10:51:09.000Z | 2021-08-03T17:04:56.000Z | Tempest/Graphics/Dx12/Managers/PipelineManager.cpp | Alekssasho/TempoEngine | 60e23e4ef743f8a9f44f8c576457a5feb27f70b9 | [
"MIT"
] | null | null | null | Tempest/Graphics/Dx12/Managers/PipelineManager.cpp | Alekssasho/TempoEngine | 60e23e4ef743f8a9f44f8c576457a5feb27f70b9 | [
"MIT"
] | null | null | null | #include <CommonIncludes.h>
#include <Graphics/Dx12/Managers/PipelineManager.h>
namespace Tempest
{
namespace Dx12
{
template<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE _Type, typename DataType>
struct alignas(void*) PipelineStreamSubobject
{
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type;
DataType Data;
PipelineStreamSubobject(const DataType& input) : Type(_Type), Data(input) {}
};
struct PipelineStreamBuilder
{
template<typename SubobjectType>
void Add(const SubobjectType& type)
{
const size_t offset = size_t(Memory.size());
Memory.resize(Memory.size() + sizeof(SubobjectType));
memcpy(Memory.data() + offset, &type, sizeof(SubobjectType));
}
eastl::vector<uint8_t> Memory;
};
PipelineManager::PipelineManager(Dx12Device& device)
: m_Device(device)
{
// Scene Constant buffer
D3D12_ROOT_PARAMETER sceneConstants;
sceneConstants.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
sceneConstants.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
sceneConstants.Descriptor.ShaderRegister = 0;
sceneConstants.Descriptor.RegisterSpace = 0;
// Geometry constant buffer
D3D12_ROOT_PARAMETER geometryConstants;
geometryConstants.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
geometryConstants.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
geometryConstants.Descriptor.ShaderRegister = 0;
geometryConstants.Descriptor.RegisterSpace = 1;
// TODO: This must be in sync with ShaderParameterType
D3D12_ROOT_PARAMETER params[] = {
sceneConstants,
geometryConstants
};
D3D12_STATIC_SAMPLER_DESC samplers[2];
::ZeroMemory(&samplers[0], sizeof(D3D12_STATIC_SAMPLER_DESC));
samplers[0].Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
samplers[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
samplers[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
samplers[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
samplers[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
::ZeroMemory(&samplers[1], sizeof(D3D12_STATIC_SAMPLER_DESC));
samplers[1].Filter = D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR;
samplers[1].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
samplers[1].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
samplers[1].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
samplers[1].ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
samplers[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
samplers[1].ShaderRegister = 1;
D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc;
// TODO: We don't need input assembler as we are doing bindless
rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED;
rootSignatureDesc.NumParameters = UINT(std::size(params));
rootSignatureDesc.pParameters = params;
rootSignatureDesc.NumStaticSamplers = 2;
rootSignatureDesc.pStaticSamplers = samplers;
ComPtr<ID3DBlob> signature;
ComPtr<ID3DBlob> error;
CHECK_SUCCESS(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
CHECK_SUCCESS(m_Device.GetDevice()->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_Signature)));
}
void PipelineManager::PrepareDefaultPipelineStateDesc(PipelineStreamBuilder& builder, const GraphicsPipelineStateDescription& description)
{
D3D12_RASTERIZER_DESC rasterizerState = {0};
rasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
rasterizerState.CullMode = D3D12_CULL_MODE_BACK;
rasterizerState.FrontCounterClockwise = FALSE;
rasterizerState.DepthClipEnable = TRUE;
rasterizerState.MultisampleEnable = FALSE;
rasterizerState.AntialiasedLineEnable = FALSE;
rasterizerState.ForcedSampleCount = 0;
rasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
if(description.DepthBias != 0.0f)
{
rasterizerState.DepthBias = int(description.DepthBias / (1 / powf(2, 23)));
rasterizerState.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
rasterizerState.SlopeScaledDepthBias = 2.0f;
}
else
{
rasterizerState.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
rasterizerState.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
rasterizerState.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
}
D3D12_BLEND_DESC blendState = {0};
blendState.AlphaToCoverageEnable = FALSE;
blendState.IndependentBlendEnable = FALSE;
const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc =
{
FALSE, FALSE,
D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD,
D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
D3D12_LOGIC_OP_NOOP,
D3D12_COLOR_WRITE_ENABLE_ALL,
};
for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
blendState.RenderTarget[i] = defaultRenderTargetBlendDesc;
D3D12_DEPTH_STENCIL_DESC1 depthStencilState = { 0 };
depthStencilState.DepthEnable = TRUE;
depthStencilState.StencilEnable = FALSE;
depthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
depthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
D3D12_RT_FORMAT_ARRAY rtvFormats = { 0 };
rtvFormats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
rtvFormats.NumRenderTargets = 1;
DXGI_SAMPLE_DESC sampleDesc = {0};
sampleDesc.Count = 1;
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC>(rasterizerState));
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC>(blendState));
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, D3D12_DEPTH_STENCIL_DESC1>(depthStencilState));
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT>(DXGI_FORMAT_D24_UNORM_S8_UINT));
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT>(UINT_MAX));
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY>(rtvFormats));
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC>(sampleDesc));
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE>(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE));
}
PipelineStateHandle PipelineManager::CreateGraphicsPipeline(const GraphicsPipelineStateDescription& description)
{
// TODO: Temp memory
PipelineStreamBuilder builder;
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, ID3D12RootSignature*>(m_Signature.Get()));
if(description.PSCode)
{
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE>(D3D12_SHADER_BYTECODE{
description.PSCode,
description.PSCodeSize
}));
}
if(description.MSCode)
{
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE>(D3D12_SHADER_BYTECODE{
description.MSCode,
description.MSCodeSize
}));
}
else if(description.VSCode)
{
builder.Add(PipelineStreamSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE>(D3D12_SHADER_BYTECODE{
description.VSCode,
description.VSCodeSize
}));
}
else
{
assert(false);
}
PrepareDefaultPipelineStateDesc(builder, description);
D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {0};
streamDesc.SizeInBytes = builder.Memory.size();
streamDesc.pPipelineStateSubobjectStream = builder.Memory.data();
PipelineStateHandle resultHandle = ++m_NextPipelineHandle;
ComPtr<ID3D12PipelineState>& pipeline = m_Pipelines[resultHandle];
CHECK_SUCCESS(m_Device.GetDevice()->CreatePipelineState(&streamDesc, IID_PPV_ARGS(&pipeline)));
return resultHandle;
}
ID3D12PipelineState* PipelineManager::GetPipeline(PipelineStateHandle handle)
{
return m_Pipelines[handle].Get();
}
ID3D12RootSignature* PipelineManager::GetSignature()
{
return m_Signature.Get();
}
}
} | 39.841584 | 166 | 0.81163 | [
"geometry",
"vector"
] |
0a50e0ef85e4b4e7a10aaa9e61c662030e696dfb | 3,154 | cpp | C++ | src/libutils/bitmap/jpeg_formatter.cpp | nkming2/libutils | e044c8f1265aad50092e008d7706142c3029096a | [
"MIT"
] | null | null | null | src/libutils/bitmap/jpeg_formatter.cpp | nkming2/libutils | e044c8f1265aad50092e008d7706142c3029096a | [
"MIT"
] | 1 | 2015-03-10T06:29:14.000Z | 2015-03-10T06:29:14.000Z | src/libutils/bitmap/jpeg_formatter.cpp | nkming2/libutils | e044c8f1265aad50092e008d7706142c3029096a | [
"MIT"
] | null | null | null | /*
* jpeg_formatter.cpp
*
* Author: Ming Tsang
* Copyright (c) 2014 Ming Tsang
* Refer to LICENSE for details
*/
#include <cstring>
#include <vector>
#include <turbojpeg.h>
#include "libutils/log.h"
#include "libutils/bitmap/bitmap.h"
#include "libutils/bitmap/jpeg_formatter.h"
#include "libutils/str/str_utils.h"
#include "libutils/type/misc.h"
#include "libutils/type/size.h"
using namespace std;
using utils::type::Size;
#define LU_NS_TAG "utils::bitmap::"
#define LU_TAG LU_NS_TAG "JpegFormatter::"
namespace utils
{
namespace bitmap
{
struct JpegFormatter::Impl
{
Impl()
: m_handle(nullptr),
m_is_compress_handle(false)
{}
~Impl()
{
if (m_handle)
{
tjDestroy(m_handle);
}
}
void EnsureCompressHandle();
void EnsureDecompressHandle();
tjhandle m_handle;
bool m_is_compress_handle;
};
void JpegFormatter::Impl::EnsureCompressHandle()
{
if (!m_handle)
{
m_handle = tjInitCompress();
}
else if (!m_is_compress_handle)
{
tjDestroy(m_handle);
m_handle = tjInitCompress();
}
m_is_compress_handle = true;
}
void JpegFormatter::Impl::EnsureDecompressHandle()
{
if (!m_handle)
{
m_handle = tjInitDecompress();
}
else if (m_is_compress_handle)
{
tjDestroy(m_handle);
m_handle = tjInitDecompress();
}
m_is_compress_handle = false;
}
JpegFormatter::JpegFormatter()
: m_impl(new Impl),
m_quality(90)
{}
JpegFormatter::~JpegFormatter()
{}
vector<Byte> JpegFormatter::Encode(const Bitmap &bmp) const
{
m_impl->EnsureCompressHandle();
if (!m_impl->m_handle)
{
LU_LOG_E(LU_TAG "Encode", str::StrUtils::Concat(
"Failed while EnsureCompressHandle: ", tjGetErrorStr()));
return {};
}
Byte *jpegBuf = nullptr;
Ulong jpegSize = 0;
if (tjCompress2(m_impl->m_handle, const_cast<Byte*>(bmp.GetData().data()),
bmp.GetW(), bmp.GetRowSize(), bmp.GetH(), TJPF_BGRA, &jpegBuf,
&jpegSize, TJSAMP_444, m_quality, 0) != 0)
{
LU_LOG_E(LU_TAG "Encode", str::StrUtils::Concat(
"Failed while tjCompress2: ", tjGetErrorStr()));
if (jpegBuf)
{
tjFree(jpegBuf);
}
return {};
}
vector<Byte> product(jpegSize);
memcpy(product.data(), jpegBuf, jpegSize);
tjFree(jpegBuf);
return product;
}
Bitmap JpegFormatter::Decode(const vector<Byte> &data) const
{
m_impl->EnsureDecompressHandle();
if (!m_impl->m_handle)
{
LU_LOG_E(LU_TAG "Decode", str::StrUtils::Concat(
"Failed while EnsureDecompressHandle: ", tjGetErrorStr()));
return {};
}
Size sz;
int subsample;
if (tjDecompressHeader2(m_impl->m_handle, const_cast<Byte*>(data.data()),
data.size(), reinterpret_cast<int*>(&sz.w),
reinterpret_cast<int*>(&sz.h), &subsample) != 0)
{
LU_LOG_E(LU_TAG "Decode", str::StrUtils::Concat(
"Failed while tjDecompressHeader2: ", tjGetErrorStr()));
return {};
}
vector<Byte> buffer(sz.GetArea() * 4);
if (tjDecompress2(m_impl->m_handle, const_cast<Byte*>(data.data()),
data.size(), buffer.data(), sz.w, sz.w * 4, sz.h, TJPF_BGRA,
TJFLAG_ACCURATEDCT) != 0)
{
LU_LOG_E(LU_TAG "Decode", str::StrUtils::Concat(
"Failed while tjDecompress2: ", tjGetErrorStr()));
return {};
}
else
{
return {std::move(buffer), sz};
}
}
}
}
| 19.7125 | 75 | 0.685796 | [
"vector"
] |
0a5c045e263d3aee8831e92bac9fe6c422e90eb3 | 4,716 | cpp | C++ | src/bartender_extractor.cpp | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 22 | 2016-08-11T06:16:25.000Z | 2022-02-22T00:06:59.000Z | src/bartender_extractor.cpp | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 9 | 2016-12-08T12:42:38.000Z | 2021-12-28T20:12:15.000Z | src/bartender_extractor.cpp | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 8 | 2017-06-26T13:15:06.000Z | 2021-11-12T18:39:54.000Z |
//
// bartender_extractor.cpp
// barcode_project
//
// Created by luzhao on 1/1/16.
// Copyright © 2016 luzhao. All rights reserved.
//
#include <stdio.h>
#include "barcodeextractor.h"
#include "UmiExtractor.hpp"
#include "filebuf.h"
#include "singlereadsprocessor.hpp"
#include "SingleReadProcessorWithUmi.hpp"
#include "timer.h"
#include <cassert>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <regex>
#include <string>
#include <vector>
using namespace std;
using namespace barcodeSpace;
using std::regex;
file_format FindInputFormat(const string& readsfile) {
ifstream raw_handler(readsfile);
FileBuf handler(&raw_handler);
file_format format = RAWSEQ;
string line;
while (!handler.eof()) {
handler.getline(line);
if (!line.empty() && line[0] == '>') {
format = FASTA;
break;
} else if (!line.empty() && line[0] == '+') {
format = FASTQ;
break;
}
line.clear();
}
if (format == RAWSEQ) {
throw runtime_error("The input reads file does not lookes like fasta or fastq file!\n");
}
return format;
}
void drive(const string& reads_file,
const string& output_prefix,
double quality_threshold,
const std::regex& pattern,
const string& preceeding,
const string& suceeding,
size_t num_sub_regex,
const vector<UmiConfig> umiConfigs,
const StrandDirection direction) {
Timer* time = new realTimer(cout);
file_format format = FindInputFormat(reads_file);
std::shared_ptr<BarcodeExtractor> barcode_extractor(
new BarcodeExtractor(pattern,preceeding, suceeding, num_sub_regex, direction));
std::shared_ptr<UmiExtractor> umiExtractorPtr;
std::shared_ptr<SingleReadsProcessor> readFileProcessor;
const std::string output = output_prefix + "_barcode.txt";
if (!umiConfigs.empty()) {
UmiExtractor* umiExtractor = new UmiExtractor(umiConfigs);
umiExtractorPtr.reset(umiExtractor);
readFileProcessor.reset(new SingleReadProcessorWithUmi(
reads_file, barcode_extractor,format, output, quality_threshold, umiExtractorPtr));
} else {
readFileProcessor.reset(new SingleReadsProcessor(reads_file,
barcode_extractor,
format,
output,
quality_threshold));
}
readFileProcessor->extract();
cout << "Totally there are " << readFileProcessor->TotalReads() << " reads in " << reads_file << " file!" << endl;
cout << "Totally there are " << readFileProcessor->TotalBarcodes() << " valid barcodes from " << reads_file << " file" << endl;
cout << "Totally there are " << readFileProcessor->TotalQualifiedBarcodes() << " valid barcodes whose quality pass the quality condition " << endl;
cout << "The estimated sequence error from the prefix and suffix parts is " << readFileProcessor->errorRate() << endl;
delete time;
}
int main(int argc,char* argv[])
{
assert(argc >= 3);
string input_reads_file(argv[1]);
string output_prefix(argv[2]);
double qual_threshold = 0;
if (argc >= 4) {
qual_threshold = atof(argv[3]);
}
std::regex pattern;
if (argc >= 5) {
pattern.assign(argv[4], std::regex::ECMAScript);
if (strlen(argv[4]) == 0) {
std::cerr << "The given pattern " << argv[4] << " is invalid"<< std::endl;
exit(1);
}
}
string preceeding;
string suceeding;
if (argc >= 6) {
preceeding.assign(argv[5]);
}
if (argc >= 7) {
suceeding.assign(argv[6]);
}
size_t num_sub_regex = 3;
if (argc >= 8) {
num_sub_regex = atoi(argv[7]);
}
StrandDirection direction = FORWARD_DIRECTION;
if (argc >= 9) {
int dir = atoi(argv[8]);
assert(dir == 0 || dir == -1 || dir == 1);
if (dir == 0) {
direction = BOTH_DIRECTION;
} else if (dir == -1) {
direction = REVERSE_DIRECTION;
}
}
vector<UmiConfig> umiConfigs;
int umiPosition = -1;
int umiLength = -1;
if (argc >= 10) {
umiPosition = atoi(argv[9]);
assert(argc >= 11);
umiLength = atoi(argv[10]);
UmiConfig umiConfig(umiPosition, umiLength);
umiConfigs.push_back(umiConfig);
}
drive(input_reads_file,
output_prefix,
qual_threshold,
pattern,
preceeding,
suceeding,
num_sub_regex,
umiConfigs,
direction);
return 0;
}
| 30.230769 | 151 | 0.594996 | [
"vector"
] |
0a616045e0ace959a5c2933adbb9b19d6c6e42a7 | 734 | cc | C++ | Code/2102-find-the-middle-index-in-array.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 2 | 2019-12-06T14:08:57.000Z | 2020-01-15T15:25:32.000Z | Code/2102-find-the-middle-index-in-array.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 1 | 2020-01-15T16:29:16.000Z | 2020-01-26T12:40:13.000Z | Code/2102-find-the-middle-index-in-array.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | null | null | null | class Solution {
public:
int findMiddleIndex(vector<int>& nums) {
if (nums.size() == 1) {
return 0;
}
int n = nums.size();
vector<int> left(n, 0);
vector<int> right(n, 0);
left[0] = nums[0];
right[n - 1] = nums[n - 1];
for (int i = 1; i < n; i++) {
left[i] = left[i - 1] + nums[i];
right[n - 1 - i] = right[n - i] + nums[n - 1 - i];
}
if (right[1] == 0) {
return 0;
}
for (int i = 0; i < n - 1; i++) {
if (left[i] == right[i]) {
return i;
}
}
if (left[n - 2] == 0) {
return n - 1;
}
return -1;
}
}; | 25.310345 | 62 | 0.347411 | [
"vector"
] |
0a65c88017e14f90eec9e7c89c0826523def50d6 | 1,047 | cpp | C++ | practica13_aula18/cl.cpp | ImaMos01/ProgCom2021A | ae1cf91be54fe2f565a5b496575855100e8c5bf3 | [
"BSD-3-Clause"
] | null | null | null | practica13_aula18/cl.cpp | ImaMos01/ProgCom2021A | ae1cf91be54fe2f565a5b496575855100e8c5bf3 | [
"BSD-3-Clause"
] | null | null | null | practica13_aula18/cl.cpp | ImaMos01/ProgCom2021A | ae1cf91be54fe2f565a5b496575855100e8c5bf3 | [
"BSD-3-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int dfs (vector<vector<int>>& image,int r1,int s1){
if(r1<0 || r1>=image.size() || s1<0 || s1>=image[r1].size() ||image[r1][s1]!=0){
return 0;
}
image[r1][s1]=2;
int cont=0;
if(r1<image.size()-1 && image[r1+1][s1]==1){
cont++;
}
if(r1>0 && image[r1-1][s1]==1){
cont++;
}
if(s1<image[r1].size()-1 && image[r1][s1+1]==1){
cont++;
}
if(s1>0 && image[r1][s1-1]==1){
cont++;
}
cont+= dfs(image, r1+1, s1);
cont+= dfs(image, r1-1, s1);
cont+= dfs(image, r1, s1+1);
cont+= dfs(image, r1, s1-1);
return cont;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int m=0,n=0;
char a;
cin>>m>>n;
int cont=0;
vector<vector<int>>cost(m+2,vector<int>(n+2,0));
for(int i=1;i<=m;i++){
for(int j=1; j<=n;j++){
cin>>a;
cost[i][j]=a-'0';
}
}
cout<<dfs(cost,0,0);
}
| 20.94 | 85 | 0.443171 | [
"vector"
] |
0a699e4541a99b9d0c62581c7509f271ca9a91a1 | 190 | hpp | C++ | src/agl/glsl/function/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/glsl/function/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/glsl/function/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | #pragma once
#include "angle_trigonometry/all.hpp"
#include "common/all.hpp"
#include "exponential/all.hpp"
#include "geometric/all.hpp"
#include "matrix/all.hpp"
#include "vector/all.hpp"
| 21.111111 | 37 | 0.757895 | [
"vector"
] |
0a6d64e41125fc6a017312da957f426f867ab8d0 | 1,423 | cxx | C++ | src/Node.cxx | LittleGreyCells/escheme-oops | 61adf2416e1ffe91f205e074d68d72d4ffbf49b9 | [
"MIT"
] | null | null | null | src/Node.cxx | LittleGreyCells/escheme-oops | 61adf2416e1ffe91f205e074d68d72d4ffbf49b9 | [
"MIT"
] | null | null | null | src/Node.cxx | LittleGreyCells/escheme-oops | 61adf2416e1ffe91f205e074d68d72d4ffbf49b9 | [
"MIT"
] | null | null | null | #include "Node.hxx"
namespace scheme
{
Node* Node::getcar() { throw AccessException( "not a list", this ); }
Node* Node::getcdr() { throw AccessException( "not a list", this ); }
void Node::setcar( Node* ) { throw AccessException( "not a list", this ); }
void Node::setcdr( Node* ) { throw AccessException( "not a list", this ); }
unsigned Node::length() { throw AccessException( "not a list", this ); }
Node* Node::getvalue() { throw AccessException( "not a symbol", this ); }
void Node::setvalue( Node* ) { throw AccessException( "not a symbol", this ); }
unsigned Node::vlen() { throw AccessException( "not a vector", this ); }
long Node::getfixnum() { throw AccessException( "not a fixnum", this ); }
double Node::getflonum() { throw AccessException( "not a flonum", this ); }
void Node::apply_dispatch() { throw EvalException( "not a callable", this ); }
size_t Node::hash() { return reinterpret_cast<size_t>( this ); }
Node* guard( Node* n, bool (Node::*pred)() )
{
if ( !(n->*pred)() )
throw SevereException( "incorrect object type", n );
return n;
}
std::string Node::id( const std::string& label )
{
char buffer[80];
snprintf( buffer, sizeof(buffer), "{%s:%p}", label.c_str(), reinterpret_cast<void*>( this ) );
return buffer;
}
Exception::Exception( std::string desc ) : description(desc) {}
}
| 35.575 | 100 | 0.616304 | [
"object",
"vector"
] |
0a93c5e9bceccc7120e6a3158be87c2d9ea961a2 | 5,643 | hxx | C++ | include/pseudo_peripheral_node.hxx | aabbas90/BDD | abab0c746a22ae04e8ca5ceacbec1d8f75b758bb | [
"BSD-2-Clause"
] | 4 | 2021-03-20T11:29:15.000Z | 2022-03-22T10:43:14.000Z | include/pseudo_peripheral_node.hxx | aabbas90/BDD | abab0c746a22ae04e8ca5ceacbec1d8f75b758bb | [
"BSD-2-Clause"
] | null | null | null | include/pseudo_peripheral_node.hxx | aabbas90/BDD | abab0c746a22ae04e8ca5ceacbec1d8f75b758bb | [
"BSD-2-Clause"
] | 3 | 2021-03-31T15:26:20.000Z | 2022-03-24T08:58:01.000Z | #pragma once
#include "union_find.hxx"
#include <queue>
#include <vector>
#include <tuple>
#include <algorithm>
#include "time_measure_util.h"
namespace LPMP {
template <typename ADJACENCY_GRAPH>
std::tuple<size_t, size_t> farthest_node(const ADJACENCY_GRAPH &adjacency, const size_t x)
{
MEASURE_FUNCTION_EXECUTION_TIME;
std::vector<char> visited(adjacency.size(), 0);
return farthest_node(adjacency, x, visited, 0);
}
template <typename ADJACENCY_GRAPH, typename VISITED_VECTOR>
std::tuple<size_t, size_t> farthest_node(const ADJACENCY_GRAPH &adjacency, const size_t x, VISITED_VECTOR &visited, const size_t timestamp)
{
assert(visited.size() == adjacency.size());
assert(*std::max_element(visited.begin(), visited.end()) <= timestamp);
size_t d = 0;
struct queue_elem
{
size_t v;
size_t d;
};
std::queue<queue_elem> Q;
Q.push({x, 0});
visited[x] = timestamp + 1;
size_t farthest_node = x;
size_t max_distance = 0;
while (!Q.empty())
{
const auto [i, d] = Q.front();
Q.pop();
assert(visited[i] == timestamp + 1);
visited[i] = timestamp + 2;
if (d > max_distance)
{
max_distance = d;
farthest_node = x;
}
for (const auto j : adjacency[i])
{
if (visited[j] <= timestamp)
{
Q.push({j, d + 1});
visited[j] = timestamp + 1;
}
}
}
return {farthest_node, max_distance};
}
template<typename ADJACENCY_GRAPH>
size_t find_pseudo_peripheral_node(const ADJACENCY_GRAPH& adjacency)
{
size_t min_degree = adjacency[0].size();
size_t x = 0;
for(size_t i=0; i<adjacency.size(); ++i) {
if(adjacency[i].size() < min_degree) {
min_degree = adjacency[i].size();
x = i;
}
}
assert(x < adjacency.size());
auto [y, d_y] = farthest_node(adjacency, x);
auto [z, d_z] = farthest_node(adjacency, y);
while(d_z > d_y) {
std::swap(y,z);
std::swap(d_z, d_y);
std::tie(z, d_z) = farthest_node(adjacency,y);
}
return y;
}
// return pseudo peripheral node of each connected component
template<typename ADJACENCY_GRAPH>
std::vector<size_t> find_pseudo_peripheral_nodes(const ADJACENCY_GRAPH& adjacency)
{
MEASURE_FUNCTION_EXECUTION_TIME;
// compute connected components of graph and for each connected component determine node of minimum degree
union_find uf(adjacency.size());
for(size_t i=0; i<adjacency.size(); ++i)
for(const size_t j : adjacency[i])
uf.merge(i, j);
struct min_degree_elem
{
size_t degree = std::numeric_limits<size_t>::max();
size_t node = std::numeric_limits<size_t>::max();
};
std::vector<min_degree_elem> min_degree(adjacency.size());
for(size_t i=0; i<adjacency.size(); ++i)
{
const size_t cc_id = uf.find(i);
const size_t d = adjacency[i].size();
if (adjacency[i].size() < min_degree[cc_id].degree)
{
min_degree[cc_id].degree = adjacency[i].size();
min_degree[cc_id].node = i;
}
}
std::vector<size_t> pseudo_peripheral_nodes;
std::vector<size_t> visited(adjacency.size(), 0);
size_t iter = 0;
for (size_t i = 0; i < adjacency.size(); ++i)
{
if(visited[i] != 0)
continue;
const size_t x = min_degree[uf.find(i)].node;
assert(x < adjacency.size());
auto [y, d_y] = farthest_node(adjacency, x, visited, 2*iter++);
auto [z, d_z] = farthest_node(adjacency, y, visited, 2*iter++);
while (d_z > d_y)
{
std::swap(y, z);
std::swap(d_z, d_y);
std::tie(z, d_z) = farthest_node(adjacency, y, visited, 2*iter++);
}
pseudo_peripheral_nodes.push_back(y);
}
return pseudo_peripheral_nodes;
}
template<typename ADJACENCY_GRAPH, typename NODE_ITERATOR>
size_t find_pseudo_peripheral_node(const ADJACENCY_GRAPH& adjacency, NODE_ITERATOR node_begin, NODE_ITERATOR node_end)
{
//assert(std::distance(node_begin, node_end) > 0);
size_t min_degree = adjacency[*node_begin].size();
size_t x = *node_begin;
for(auto node_it=node_begin; node_it!=node_end; ++node_it) {
if(adjacency[*node_it].size() < min_degree) {
min_degree = adjacency[*node_it].size();
x = *node_it;
}
}
assert(x < adjacency.size());
auto [y, d_y] = farthest_node(adjacency, x);
auto [z, d_z] = farthest_node(adjacency, y);
while(d_z > d_y) {
std::swap(y,z);
std::swap(d_z, d_y);
std::tie(z, d_z) = farthest_node(adjacency,y);
}
return y;
}
/*
struct iterator {
size_t i;
size_t operator*() const { return i; }
void operator++() { ++i; }
bool operator!=(const iterator o) { return o.i != this->i; }
size_t operator-(const iterator o) const { return o.i - this->i; }
};
template<typename ADJACENCY_GRAPH>
size_t find_pseudo_peripheral_node(const ADJACENCY_GRAPH& adjacency)
{
return find_pseudo_peripheral_node(adjacency, iterator({0}), iterator({adjacency.size()}));
}
*/
}
| 31.176796 | 139 | 0.564239 | [
"vector"
] |
0a99d70b0005305f9a552e33c3b0a9a5b1577845 | 2,882 | hpp | C++ | tenncor_io/include/creator_vertex.hpp | mingkaic/CNNet | 2e5d0ec94bd38aef6afcd5bdf6ac8dadf45df3b4 | [
"MIT"
] | null | null | null | tenncor_io/include/creator_vertex.hpp | mingkaic/CNNet | 2e5d0ec94bd38aef6afcd5bdf6ac8dadf45df3b4 | [
"MIT"
] | null | null | null | tenncor_io/include/creator_vertex.hpp | mingkaic/CNNet | 2e5d0ec94bd38aef6afcd5bdf6ac8dadf45df3b4 | [
"MIT"
] | null | null | null | //
// Created by Mingkai Chen on 2016-12-27.
//
#include <vector>
#include <string>
#include <unordered_set>
#include <utility>
#include <experimental/optional>
#pragma once
#ifndef creator_vertex_hpp
#define creator_vertex_hpp
// purpose: hide all tenncor implementation
namespace tensorio
{
// connector types
enum CONNECTOR_TYPE
{
// unaries
ABS,
NEG,
SIN,
COS,
TAN,
CSC,
SEC,
COT,
EXP,
// scalar operations
// SQRT, POW, CLIP_VAL, CLIP_NORM, EXTEND, COMPRESS
// binaries
ADD,
SUB,
MUL,
DIV,
// transformations
MATMUL,
TRANS,
FIT,
};
// leaf types
enum LEAF_TYPE
{
PLACE,
CONST, // still uses a variable (sets an initial value)
RAND
};
union var_param
{
double val_;
std::pair<double,double> min2max_;
};
// encapsulate leaf building options
// defaults to random initialization between -1 and 1
struct var_opt
{
LEAF_TYPE type = PLACE;
std::vector<size_t> shape_ = {1};
std::experimental::optional<var_param> parameter_;
};
// from are children, to are parents
struct connection
{
std::string from_id;
std::string to_id;
size_t idx;
};
struct connection_hash
{
size_t operator() (const connection& conn) const
{
std::hash<std::string> hash_fn;
return hash_fn(conn.from_id) * hash_fn(conn.to_id) * (conn.idx + 1);
}
};
inline bool operator == (const connection& lhs, const connection& rhs)
{
connection_hash hash_fn;
return hash_fn(lhs) == hash_fn(rhs);
}
using CONNECTION_SET = std::unordered_set<connection, connection_hash>;
struct metainfo
{
// no value means it's a leaf
std::experimental::optional<CONNECTOR_TYPE> op_type_;
};
// store and retrieve graph information
// builder of graph
class vertex_manager
{
private:
struct node_registry;
node_registry* inst;
public:
vertex_manager (void);
virtual ~vertex_manager (void);
// MODIFIERS
// register nodes
std::string register_op (CONNECTOR_TYPE cm);
std::string register_leaf (std::string label, var_opt opt);
// delete nodes
bool delete_node (std::string id);
// link id1 to id2 if id2 points to a connector.
// index denotes link's index to id2
void link (std::string id1, std::string id2, size_t index = 0);
// delete indexed link to id node
bool delete_link (std::string id, size_t index);
// ACCESSORS
// return no value if id is not found
std::experimental::optional<metainfo> node_info (std::string id) const;
// grab all connections under sub-network flow connected to root (breadth first search)
void get_connections (CONNECTION_SET& conns, std::string root_id) const;
// get forward graph vertices (ids) and edges (conns)
void get_forwards (std::unordered_set<std::string>& ids, CONNECTION_SET& conns) const;
// get backward (gradient) graph vertices (ids) and edges (conns)
void get_backwards (std::unordered_set<std::string>& ids, CONNECTION_SET& conns) const;
};
}
#endif /* creator_vertex_hpp */
| 20.733813 | 89 | 0.719292 | [
"vector"
] |
0aa0ad8aa9378743233f27395bd8b9dc254690cf | 2,029 | cpp | C++ | android-31/android/media/metrics/PlaybackErrorEvent_Builder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/media/metrics/PlaybackErrorEvent_Builder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/media/metrics/PlaybackErrorEvent_Builder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "./PlaybackErrorEvent.hpp"
#include "../../os/Bundle.hpp"
#include "../../../java/lang/Exception.hpp"
#include "./PlaybackErrorEvent_Builder.hpp"
namespace android::media::metrics
{
// Fields
// QJniObject forward
PlaybackErrorEvent_Builder::PlaybackErrorEvent_Builder(QJniObject obj) : JObject(obj) {}
// Constructors
PlaybackErrorEvent_Builder::PlaybackErrorEvent_Builder()
: JObject(
"android.media.metrics.PlaybackErrorEvent$Builder",
"()V"
) {}
// Methods
android::media::metrics::PlaybackErrorEvent PlaybackErrorEvent_Builder::build() const
{
return callObjectMethod(
"build",
"()Landroid/media/metrics/PlaybackErrorEvent;"
);
}
android::media::metrics::PlaybackErrorEvent_Builder PlaybackErrorEvent_Builder::setErrorCode(jint arg0) const
{
return callObjectMethod(
"setErrorCode",
"(I)Landroid/media/metrics/PlaybackErrorEvent$Builder;",
arg0
);
}
android::media::metrics::PlaybackErrorEvent_Builder PlaybackErrorEvent_Builder::setException(java::lang::Exception arg0) const
{
return callObjectMethod(
"setException",
"(Ljava/lang/Exception;)Landroid/media/metrics/PlaybackErrorEvent$Builder;",
arg0.object()
);
}
android::media::metrics::PlaybackErrorEvent_Builder PlaybackErrorEvent_Builder::setMetricsBundle(android::os::Bundle arg0) const
{
return callObjectMethod(
"setMetricsBundle",
"(Landroid/os/Bundle;)Landroid/media/metrics/PlaybackErrorEvent$Builder;",
arg0.object()
);
}
android::media::metrics::PlaybackErrorEvent_Builder PlaybackErrorEvent_Builder::setSubErrorCode(jint arg0) const
{
return callObjectMethod(
"setSubErrorCode",
"(I)Landroid/media/metrics/PlaybackErrorEvent$Builder;",
arg0
);
}
android::media::metrics::PlaybackErrorEvent_Builder PlaybackErrorEvent_Builder::setTimeSinceCreatedMillis(jlong arg0) const
{
return callObjectMethod(
"setTimeSinceCreatedMillis",
"(J)Landroid/media/metrics/PlaybackErrorEvent$Builder;",
arg0
);
}
} // namespace android::media::metrics
| 28.985714 | 129 | 0.755545 | [
"object"
] |
0aa2385c37995db816da93cbfdf0cf45afca0c11 | 2,071 | cpp | C++ | src/096_unique_binary_search_trees.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 1 | 2019-09-01T22:54:39.000Z | 2019-09-01T22:54:39.000Z | src/096_unique_binary_search_trees.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 6 | 2019-07-19T07:16:42.000Z | 2019-07-26T08:21:31.000Z | src/096_unique_binary_search_trees.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | null | null | null | /*
Unique Binary Search Trees
URL: https://leetcode.com/problems/unique-binary-search-trees
Tags: ['dynamic-programming', 'tree']
___
Given n , how many structurally unique BST 's (binary search trees) that store
values 1 ... n?
Example:
Input: 3
Output: 5
Explanation: Given n = 3, there are a total of 5 unique BST 's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
*/
#include "test.h"
using namespace leetcode;
using std::map;
using std::vector;
namespace unique_binary_search_trees {
inline namespace v1 {
/*
想完全照搬 095 unique binary search trees ii 的思路是不行的, 太慢了.
这题考察的是卡特兰数,其递推形式是:
C(n) = 累加[C(i)*C(n-1-i), i from 0 to n - 1], 且 C(0) = 1.
或者卡兰特数也可以是:
C(n) = f(2n) = 累加[f(i-1)*f(2n-1-i), i from 1 to 2n-1], 且 f(0) = 1.
这个形式就是括号配对问题, 栈进出问题的推导结果.
如何将查找二叉树的问题映射成为栈的进出问题呢?
首先要明白一点就是只要BST的形态是确定的, 那每个节点上填入的数字也是确定的
(可以想象将 BST 压扁成一个数组)
所以这题本质上是在问, 由 n 个节点组成的二叉树有多少种可能的形态.
首先将这棵二叉树补满成为一棵满二叉树,
这时我们就一共有(2n+1)个可用的节点(其中一个是根节点).
接下去的逻辑就变成, 从根节点出发, 可以画出多少种不同的**满二叉树**.
记往左一步等价于入栈, 往右一步等价于出栈,
则该问题转换成为了栈进出(或括号匹配)问题了, 可以套上面第二个的公式了.
*/
class Solution {
public:
int numTrees(int n) {
map<int, int> record;
return step(n, record);
}
private:
// 套用上面第一个递推公式,
// record 记录已经计算过的结果, 避免重复计算.
int step(int n, map<int, int>& record) {
if (n == 0) {
return 1;
}
auto iter = record.find(n);
if (iter != record.end()) {
return iter->second;
}
int result = 0;
for (int i = 0; i < n; i++) {
result += step(i, record) * step(n - 1 - i, record);
}
record[n] = result;
return result;
}
};
} // namespace v1
TEST_CASE("Unique Binary Search Trees") {
TEST_SOLUTION(numTrees, v1) {
CHECK(numTrees(3) == 5);
CHECK(numTrees(19) == 1767263190);
BENCHMARK("") { return numTrees(19); };
};
}
} // namespace unique_binary_search_trees
| 23.269663 | 78 | 0.564462 | [
"vector"
] |
0aa6aa155b90047593ac53b7297706319ebe1fcb | 1,150 | cc | C++ | test/src/Geometry.cc | uspgamedev/ugdk | 95885a70df282a8e8e6e5c72b28a7f2f21bf7e99 | [
"Zlib"
] | 11 | 2015-03-06T13:14:32.000Z | 2020-06-09T23:34:28.000Z | test/src/Geometry.cc | uspgamedev/ugdk | 95885a70df282a8e8e6e5c72b28a7f2f21bf7e99 | [
"Zlib"
] | 62 | 2015-01-04T05:47:40.000Z | 2018-06-15T17:00:25.000Z | test/src/Geometry.cc | uspgamedev/ugdk | 95885a70df282a8e8e6e5c72b28a7f2f21bf7e99 | [
"Zlib"
] | 2 | 2017-04-05T20:35:49.000Z | 2017-07-30T03:44:02.000Z | #include "gtest/gtest.h"
#include <glm/glm.hpp>
#include <ugdk/math/geometry.h>
using ugdk::math::Vector2D;
using ugdk::math::Geometry;
#define PI 3.1415926535897932384626433832795
TEST(Geometry, Constructors) {
Geometry m;
EXPECT_EQ(glm::mat4(), m.AsMat4());
{ Geometry m2(Vector2D(15.0, -10.0), Vector2D(0.5, 0.4), -17.8);
Geometry copy(m2);
EXPECT_EQ(m2.AsMat4(), copy.AsMat4());
}
}
TEST(Geometry, Compose) {
Geometry id;
{ Geometry m1(Vector2D(10, 50));
Geometry comp = id * m1;
EXPECT_EQ(m1.AsMat4(), comp.AsMat4());
}
{
Geometry mx(Vector2D(10.0, 0.0));
Geometry rot(Vector2D(), Vector2D(1.0, 1.0), PI/4.0);
Geometry result1 = rot * mx;
glm::mat4 result1_mat = result1.AsMat4();
EXPECT_EQ(7.0710678118654755f, result1_mat[3].x);
EXPECT_EQ(7.0710678118654746f, result1_mat[3].y);
Geometry result2 = rot * mx * mx;
glm::mat4 result2_mat = result2.AsMat4();
EXPECT_EQ(14.142135623730951f, result2_mat[3].x);
EXPECT_EQ(14.142135623730949f, result2_mat[3].y);
}
// TODO: more tests
} | 26.744186 | 70 | 0.613043 | [
"geometry"
] |
0aaab0d791ca7f08eab1044fd3b29324e653ef8b | 4,328 | cpp | C++ | Duet Editor/Entity_TreeType.cpp | mvandevander/duetgame | 6fd083d22b0eab9e7988e0ba46a6ec10757b7720 | [
"MIT"
] | 9 | 2016-03-18T23:59:24.000Z | 2022-02-09T01:09:56.000Z | Duet Editor/Entity_TreeType.cpp | mvandevander/duetgame | 6fd083d22b0eab9e7988e0ba46a6ec10757b7720 | [
"MIT"
] | null | null | null | Duet Editor/Entity_TreeType.cpp | mvandevander/duetgame | 6fd083d22b0eab9e7988e0ba46a6ec10757b7720 | [
"MIT"
] | null | null | null | #include "Entity_TreeType.hpp"
#include "trig_functions_degrees.hpp"
#include "GL_DrawingPrimitives.hpp"
Entity_TreeType::Entity_TreeType(int origin_x, int origin_y, int first_pt_width)
{
x = origin_x;
y = origin_y;
type = 't';
branches.push_back(Tree_Branch(0,0,first_pt_width));
bounds.x = x-40;
bounds.y = y-40;
w = 80;
h = 80;
bounds.w = w;
bounds.h = h;
}
Entity_TreeType::~Entity_TreeType()
{
}
void Entity_TreeType::update()
{
}
void Entity_TreeType::add_node_in_treespace(int new_node_x, int new_node_y) //assumes that input coordinates are in tree-space, with the origin being the coordinates of the first point of the tree.
{
point_2d checking_point(new_node_x,new_node_y);
TreeInfo Info = find_tree_info(new_node_x,new_node_y);
Tree_Node New_Node(new_node_x,new_node_y, Info.Closest_Branch->nodes[Info.index_of_second_node_in_closest_vector].width);
if(unsigned (Info.index_of_closest_node)==Info.Closest_Branch->nodes.size()-1){
Info.Closest_Branch->nodes.push_back(New_Node);
}
else Info.Closest_Branch->nodes.insert(Info.Closest_Branch->nodes.begin()+Info.index_of_second_node_in_closest_vector,New_Node);
}
TreeInfo Entity_TreeType::find_tree_info(int tree_space_x, int tree_space_y)
{
point_2d checking_point(tree_space_x,tree_space_y);
int index_of_second_node_in_closest_vector = 0,index_of_closest_branch = 0,index_of_closest_node = 0;
float shortest_distance = -1;
for(unsigned int i = 0; i<branches.size(); i++) //need to find the closest branch, so we can attach the new node to that branch.
{
if(branches[i].nodes.size()==1){
float dist_to_single_noded_branch = GetDistance(tree_space_x,tree_space_y,(int)branches[i].nodes[0].x,(int)branches[i].nodes[0].y);
if(dist_to_single_noded_branch<shortest_distance||shortest_distance==-1){
shortest_distance = dist_to_single_noded_branch;
index_of_second_node_in_closest_vector = 0;
index_of_closest_branch = i;
index_of_closest_node = 0;
}
}
else{
for(unsigned int a = 0; a<branches[i].nodes.size()-1; a++) //also need to find the closest vector (line between nodes) on that branch, and insert the new node in-between those.
{
vec_2d this_segment((int)branches[i].nodes[a].x,(int)branches[i].nodes[a].y,(int)branches[i].nodes[a+1].x,(int)branches[i].nodes[a+1].y);
vec_2d shortest_vector = find_shortest_vector_from_point_to_line(checking_point,this_segment);
if(shortest_vector.len<shortest_distance||shortest_distance==-1)
{
shortest_distance = shortest_vector.len;
index_of_second_node_in_closest_vector = a+1;
index_of_closest_branch = i;
if(GetDistanceSquared(tree_space_x,tree_space_y,(int)branches[i].nodes[a].x,(int)branches[i].nodes[a].y)<=GetDistanceSquared(tree_space_x,tree_space_y,(int)branches[i].nodes[a+1].x,(int)branches[i].nodes[a+1].y)){
index_of_closest_node = a;
}
else index_of_closest_node = a+1;
}
}
}
}
TreeInfo Info_From_Search;
Info_From_Search.Closest_Branch = &branches[index_of_closest_branch];
Info_From_Search.Closest_Node = &(Info_From_Search.Closest_Branch->nodes[index_of_closest_node]);
Info_From_Search.index_of_closest_branch = index_of_closest_branch;
Info_From_Search.is_real = true;
Info_From_Search.index_of_second_node_in_closest_vector = index_of_second_node_in_closest_vector;
Info_From_Search.index_of_closest_node = index_of_closest_node;
return Info_From_Search;
}
void Entity_TreeType::draw(GLuint displaylist,float r, float g, float b, float a)
{
for(unsigned int i = 0; i<branches.size();i++)
{
branches[i].draw(displaylist,r,g,b,a);
}
DrawGLRectSolidFromCurrentMatrix(displaylist,-5,-5,10,10,0.0,0.0,0.0,0.8);
}
bool Entity_TreeType::serialize(fstream& file)
{
return true;
}
bool Entity_TreeType::unserialize(ifstream& file)
{
return true;
}
| 40.074074 | 234 | 0.673983 | [
"vector"
] |
0ab0c309f32e3a55970dcff303c4145c17a012a0 | 33,149 | cpp | C++ | blades/xbmc/xbmc/cores/DllLoader/exports/emu_kernel32.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/cores/DllLoader/exports/emu_kernel32.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/cores/DllLoader/exports/emu_kernel32.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "emu_kernel32.h"
#include "emu_dummy.h"
#include "CompileInfo.h"
#include "utils/log.h"
#include "storage/IoSupport.h"
#ifndef TARGET_POSIX
#include <process.h>
#include "utils/CharsetConverter.h"
#endif
#include "../dll_tracker.h"
#include "filesystem/SpecialProtocol.h"
#ifdef TARGET_POSIX
#include "../../../linux/PlatformInclude.h"
#define __except catch
#endif
#include <string.h>
#include <vector>
#include <stdlib.h>
std::vector<std::string> m_vecAtoms;
//#define API_DEBUG
extern "C" HANDLE xboxopendvdrom()
{
return CIoSupport::OpenCDROM();
}
extern "C" UINT WINAPI dllGetAtomNameA( ATOM nAtom, LPTSTR lpBuffer, int nSize)
{
if (nAtom < 1 || nAtom > m_vecAtoms.size() ) return 0;
nAtom--;
std::string& strAtom = m_vecAtoms[nAtom];
strcpy(lpBuffer, strAtom.c_str());
return strAtom.size();
}
extern "C" ATOM WINAPI dllFindAtomA( LPCTSTR lpString)
{
for (int i = 0; i < (int)m_vecAtoms.size(); ++i)
{
std::string& strAtom = m_vecAtoms[i];
if (strAtom == lpString) return i + 1;
}
return 0;
}
extern "C" ATOM WINAPI dllAddAtomA( LPCTSTR lpString)
{
m_vecAtoms.push_back(lpString);
return m_vecAtoms.size();
}
/*
extern "C" ATOM WINAPI dllDeleteAtomA(ATOM nAtom)
{
}*/
extern "C" BOOL WINAPI dllFindClose(HANDLE hFile)
{
return FindClose(hFile);
}
#ifdef TARGET_WINDOWS
#define CORRECT_SEP_STR(str) \
if (strstr(str, "://") == NULL) \
{ \
int iSize_##str = strlen(str); \
for (int pos = 0; pos < iSize_##str; pos++) \
if (str[pos] == '/') str[pos] = '\\'; \
} \
else \
{ \
int iSize_##str = strlen(str); \
for (int pos = 0; pos < iSize_##str; pos++) \
if (str[pos] == '\\') str[pos] = '/'; \
}
#else
#define CORRECT_SEP_STR(str)
#endif
#ifdef TARGET_WINDOWS
static void to_WIN32_FIND_DATA(LPWIN32_FIND_DATAW wdata, LPWIN32_FIND_DATA data)
{
std::string strname;
g_charsetConverter.wToUTF8(wdata->cFileName, strname);
size_t size = sizeof(data->cFileName) / sizeof(char);
strncpy(data->cFileName, strname.c_str(), size);
if (size)
data->cFileName[size - 1] = '\0';
g_charsetConverter.wToUTF8(wdata->cAlternateFileName, strname);
size = sizeof(data->cAlternateFileName) / sizeof(char);
strncpy(data->cAlternateFileName, strname.c_str(), size);
if (size)
data->cAlternateFileName[size - 1] = '\0';
data->dwFileAttributes = wdata->dwFileAttributes;
data->ftCreationTime = wdata->ftCreationTime;
data->ftLastAccessTime = wdata->ftLastAccessTime;
data->ftLastWriteTime = wdata->ftLastWriteTime;
data->nFileSizeHigh = wdata->nFileSizeHigh;
data->nFileSizeLow = wdata->nFileSizeLow;
data->dwReserved0 = wdata->dwReserved0;
data->dwReserved1 = wdata->dwReserved1;
}
static void to_WIN32_FIND_DATAW(LPWIN32_FIND_DATA data, LPWIN32_FIND_DATAW wdata)
{
std::wstring strwname;
g_charsetConverter.utf8ToW(data->cFileName, strwname, false);
size_t size = sizeof(wdata->cFileName) / sizeof(wchar_t);
wcsncpy(wdata->cFileName, strwname.c_str(), size);
if (size)
wdata->cFileName[size - 1] = '\0';
g_charsetConverter.utf8ToW(data->cAlternateFileName, strwname, false);
size = sizeof(wdata->cAlternateFileName) / sizeof(wchar_t);
wcsncpy(wdata->cAlternateFileName, strwname.c_str(), size);
if (size)
data->cAlternateFileName[size - 1] = '\0';
wdata->dwFileAttributes = data->dwFileAttributes;
wdata->ftCreationTime = data->ftCreationTime;
wdata->ftLastAccessTime = data->ftLastAccessTime;
wdata->ftLastWriteTime = data->ftLastWriteTime;
wdata->nFileSizeHigh = data->nFileSizeHigh;
wdata->nFileSizeLow = data->nFileSizeLow;
wdata->dwReserved0 = data->dwReserved0;
wdata->dwReserved1 = data->dwReserved1;
}
#endif
extern "C" HANDLE WINAPI dllFindFirstFileA(LPCTSTR lpFileName, LPWIN32_FIND_DATA lpFindFileData)
{
char* p = strdup(lpFileName);
CORRECT_SEP_STR(p);
// change default \\*.* into \\* which the xbox is using
char* e = strrchr(p, '.');
if (e != NULL && strlen(e) > 1 && e[1] == '*')
{
e[0] = '\0';
}
#ifdef TARGET_WINDOWS
struct _WIN32_FIND_DATAW FindFileDataW;
std::wstring strwfile;
g_charsetConverter.utf8ToW(CSpecialProtocol::TranslatePath(p), strwfile, false);
HANDLE res = FindFirstFileW(strwfile.c_str(), &FindFileDataW);
if (res != INVALID_HANDLE_VALUE)
to_WIN32_FIND_DATA(&FindFileDataW, lpFindFileData);
#else
HANDLE res = FindFirstFile(CSpecialProtocol::TranslatePath(p).c_str(), lpFindFileData);
#endif
free(p);
return res;
}
extern "C" BOOL WINAPI dllFindNextFileA(HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData)
{
#ifdef TARGET_WINDOWS
struct _WIN32_FIND_DATAW FindFileDataW;
to_WIN32_FIND_DATAW(lpFindFileData, &FindFileDataW);
BOOL res = FindNextFileW(hFindFile, &FindFileDataW);
if (res)
to_WIN32_FIND_DATA(&FindFileDataW, lpFindFileData);
return res;
#else
return FindNextFile(hFindFile, lpFindFileData);
#endif
}
// should be moved to CFile! or use CFile::stat
extern "C" DWORD WINAPI dllGetFileAttributesA(LPCSTR lpFileName)
{
char str[1024];
if (!strcmp(lpFileName, "\\Device\\Cdrom0")) return (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY);
// move to CFile classes
if (strncmp(lpFileName, "\\Device\\Cdrom0", 14) == 0)
{
// replace "\\Device\\Cdrom0" with "D:"
strcpy(str, "D:");
strcat(str, lpFileName + 14);
}
else strcpy(str, lpFileName);
#ifndef TARGET_POSIX
// convert '/' to '\\'
char *p = str;
while (p = strchr(p, '/')) * p = '\\';
return GetFileAttributesA(str);
#else
return GetFileAttributes(str);
#endif
}
extern "C" void WINAPI dllSleep(DWORD dwTime)
{
return ::Sleep(dwTime);
}
extern "C" DWORD WINAPI dllGetCurrentProcessId(void)
{
#ifdef TARGET_POSIX
return (DWORD)getppid();
#else
return GetCurrentProcessId();
#endif
}
extern "C" int WINAPI dllDuplicateHandle(HANDLE hSourceProcessHandle, // handle to source process
HANDLE hSourceHandle, // handle to duplicate
HANDLE hTargetProcessHandle, // handle to target process
HANDLE* lpTargetHandle, // duplicate handle
DWORD dwDesiredAccess, // requested access
int bInheritHandle, // handle inheritance option
DWORD dwOptions // optional actions
)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "DuplicateHandle(%p, %p, %p, %p, 0x%x, %d, %d) called\n",
hSourceProcessHandle, hSourceHandle, hTargetProcessHandle,
lpTargetHandle, dwDesiredAccess, bInheritHandle, dwOptions);
#endif
#if defined (TARGET_POSIX)
*lpTargetHandle = hSourceHandle;
return 1;
#else
return DuplicateHandle(hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, lpTargetHandle, dwDesiredAccess, bInheritHandle, dwOptions);
#endif
}
extern "C" BOOL WINAPI dllDisableThreadLibraryCalls(HMODULE h)
{
#ifdef TARGET_WINDOWS
return DisableThreadLibraryCalls(h);
#else
not_implement("kernel32.dll fake function DisableThreadLibraryCalls called\n"); //warning
return TRUE;
#endif
}
#ifndef TARGET_POSIX
static void DumpSystemInfo(const SYSTEM_INFO* si)
{
CLog::Log(LOGDEBUG, " Processor architecture %d\n", si->wProcessorArchitecture);
CLog::Log(LOGDEBUG, " Page size: %d\n", si->dwPageSize);
CLog::Log(LOGDEBUG, " Minimum app address: %d\n", si->lpMinimumApplicationAddress);
CLog::Log(LOGDEBUG, " Maximum app address: %d\n", si->lpMaximumApplicationAddress);
CLog::Log(LOGDEBUG, " Active processor mask: 0x%x\n", si->dwActiveProcessorMask);
CLog::Log(LOGDEBUG, " Number of processors: %d\n", si->dwNumberOfProcessors);
CLog::Log(LOGDEBUG, " Processor type: 0x%x\n", si->dwProcessorType);
CLog::Log(LOGDEBUG, " Allocation granularity: 0x%x\n", si->dwAllocationGranularity);
CLog::Log(LOGDEBUG, " Processor level: 0x%x\n", si->wProcessorLevel);
CLog::Log(LOGDEBUG, " Processor revision: 0x%x\n", si->wProcessorRevision);
}
#endif
extern "C" UINT WINAPI dllGetPrivateProfileIntA(
LPCSTR lpAppName,
LPCSTR lpKeyName,
INT nDefault,
LPCSTR lpFileName)
{
not_implement("kernel32.dll fake function GetPrivateProfileIntA called\n"); //warning
return nDefault;
}
extern "C" DWORD WINAPI dllGetVersion()
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetVersion() => 0xC0000004 (Windows 95)\n");
#endif
//return 0x0a280105; //Windows XP
return 0xC0000004; //Windows 95
}
extern "C" BOOL WINAPI dllGetVersionExA(LPOSVERSIONINFO lpVersionInfo)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetVersionExA()\n");
#endif
lpVersionInfo->dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
lpVersionInfo->dwMajorVersion = 4;
lpVersionInfo->dwMinorVersion = 0;
lpVersionInfo->dwBuildNumber = 0x4000457;
// leave it here for testing win9x-only codecs
lpVersionInfo->dwPlatformId = 1; //VER_PLATFORM_WIN32_WINDOWS
lpVersionInfo->szCSDVersion[0] = 0;
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, " Major version: %d\n Minor version: %d\n Build number: %x\n"
" Platform Id: %d\n Version string: '%s'\n",
lpVersionInfo->dwMajorVersion, lpVersionInfo->dwMinorVersion,
lpVersionInfo->dwBuildNumber, lpVersionInfo->dwPlatformId, lpVersionInfo->szCSDVersion);
#endif
return TRUE;
}
extern "C" BOOL WINAPI dllGetVersionExW(LPOSVERSIONINFOW lpVersionInfo)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetVersionExW()\n");
#endif
if(!dllGetVersionExA((LPOSVERSIONINFO)lpVersionInfo))
return FALSE;
lpVersionInfo->szCSDVersion[0] = 0;
lpVersionInfo->szCSDVersion[1] = 0;
return TRUE;
}
extern "C" UINT WINAPI dllGetProfileIntA(LPCTSTR lpAppName, LPCTSTR lpKeyName, INT nDefault)
{
// CLog::Log(LOGDEBUG,"GetProfileIntA:%s %s %i", lpAppName,lpKeyName,nDefault);
not_implement("kernel32.dll fake function GetProfileIntA called\n"); //warning
return nDefault;
}
extern "C" BOOL WINAPI dllFreeEnvironmentStringsW(LPWSTR lpString)
{
// we don't have anything to clean up here, just return.
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "FreeEnvironmentStringsA(0x%x) => 1", lpString);
#endif
return true;
}
extern "C" HMODULE WINAPI dllGetOEMCP()
{
not_implement("kernel32.dll fake function GetOEMCP called\n"); //warning
return NULL;
}
extern "C" HMODULE WINAPI dllRtlUnwind(PVOID TargetFrame OPTIONAL, PVOID TargetIp OPTIONAL, PEXCEPTION_RECORD ExceptionRecord OPTIONAL, PVOID ReturnValue)
{
not_implement("kernel32.dll fake function RtlUnwind called\n"); //warning
return NULL;
}
extern "C" LPTSTR WINAPI dllGetCommandLineA()
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetCommandLineA() => \"c:\\xbmc.xbe\"\n");
#endif
return (LPTSTR)"c:\\xbmc.xbe";
}
extern "C" HMODULE WINAPI dllExitProcess(UINT uExitCode)
{
not_implement("kernel32.dll fake function ExitProcess called\n"); //warning
return NULL;
}
extern "C" HMODULE WINAPI dllTerminateProcess(HANDLE hProcess, UINT uExitCode)
{
not_implement("kernel32.dll fake function TerminateProcess called\n"); //warning
return NULL;
}
extern "C" HANDLE WINAPI dllGetCurrentProcess()
{
#ifdef TARGET_WINDOWS
return GetCurrentProcess();
#else
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetCurrentProcess(void) => 9375");
#endif
return (HANDLE)9375;
#endif
}
extern "C" UINT WINAPI dllGetACP()
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetACP() => 0");
#endif
return CP_ACP;
}
extern "C" UINT WINAPI dllSetHandleCount(UINT uNumber)
{
//Under Windows NT and Windows 95, this function simply returns the value specified in the uNumber parameter.
//return uNumber;
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "SetHandleCount(0x%x) => 1\n", uNumber);
#endif
return uNumber;
}
extern "C" HANDLE WINAPI dllGetStdHandle(DWORD nStdHandle)
{
switch (nStdHandle)
{
case STD_INPUT_HANDLE: return (HANDLE)0;
case STD_OUTPUT_HANDLE: return (HANDLE)1;
case STD_ERROR_HANDLE: return (HANDLE)2;
}
SetLastError( ERROR_INVALID_PARAMETER );
return INVALID_HANDLE_VALUE;
}
extern "C" DWORD WINAPI dllGetFileType(HANDLE hFile)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetFileType(0x%x) => 0x3 = pipe", hFile);
#endif
return 3;
}
extern "C" int WINAPI dllGetStartupInfoA(LPSTARTUPINFOA lpStartupInfo)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetStartupInfoA(0x%x) => 1\n");
#endif
lpStartupInfo->cb = sizeof(_STARTUPINFOA);
lpStartupInfo->cbReserved2 = 0;
lpStartupInfo->dwFillAttribute = 0;
lpStartupInfo->dwFlags = 0;
lpStartupInfo->dwX = 50; //
lpStartupInfo->dwXCountChars = 0;
lpStartupInfo->dwXSize = 0;
lpStartupInfo->dwY = 50; //
lpStartupInfo->dwYCountChars = 0;
lpStartupInfo->dwYSize = 0;
lpStartupInfo->hStdError = (HANDLE)2;
lpStartupInfo->hStdInput = (HANDLE)0;
lpStartupInfo->hStdOutput = (HANDLE)1;
lpStartupInfo->lpDesktop = NULL;
lpStartupInfo->lpReserved = NULL;
lpStartupInfo->lpReserved2 = 0;
lpStartupInfo->lpTitle = (LPTSTR)CCompileInfo::GetAppName();
lpStartupInfo->wShowWindow = 0;
return 1;
}
extern "C" BOOL WINAPI dllFreeEnvironmentStringsA(LPSTR lpString)
{
// we don't have anything to clean up here, just return.
return true;
}
static const char ch_envs[] =
"__MSVCRT_HEAP_SELECT=__GLOBAL_HEAP_SELETED,1\r\n"
"PATH=C:\\;C:\\windows\\;C:\\windows\\system\r\n";
extern "C" LPVOID WINAPI dllGetEnvironmentStrings()
{
#ifdef TARGET_WINDOWS
return GetEnvironmentStrings();
#else
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetEnvironmentStrings() => 0x%x = %p", ch_envs, ch_envs);
#endif
return (LPVOID)ch_envs;
#endif
}
extern "C" LPVOID WINAPI dllGetEnvironmentStringsW()
{
#ifdef TARGET_WINDOWS
return GetEnvironmentStringsW();
#else
return 0;
#endif
}
extern "C" int WINAPI dllGetEnvironmentVariableA(LPCSTR lpName, LPSTR lpBuffer, DWORD nSize)
{
#ifdef TARGET_WINDOWS
return GetEnvironmentVariableA(lpName, lpBuffer, nSize);
#else
if (lpBuffer)
{
lpBuffer[0] = 0;
if (strcmp(lpName, "__MSVCRT_HEAP_SELECT") == 0)
strcpy(lpBuffer, "__GLOBAL_HEAP_SELECTED,1");
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetEnvironmentVariableA('%s', 0x%x, %d) => %d", lpName, lpBuffer, nSize, strlen(lpBuffer));
#endif
return strlen(lpBuffer);
}
return 0;
#endif
}
extern "C" HMODULE WINAPI dllLCMapStringA(LCID Locale, DWORD dwMapFlags, LPCSTR lpSrcStr, int cchSrc, LPSTR lpDestStr, int cchDest)
{
not_implement("kernel32.dll fake function LCMapStringA called\n"); //warning
return NULL;
}
extern "C" HMODULE WINAPI dllLCMapStringW(LCID Locale, DWORD dwMapFlags, LPCWSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest)
{
not_implement("kernel32.dll fake function LCMapStringW called\n"); //warning
return NULL;
}
extern "C" HMODULE WINAPI dllSetStdHandle(DWORD nStdHandle, HANDLE hHandle)
{
not_implement("kernel32.dll fake function SetStdHandle called\n"); //warning
return NULL;
}
extern "C" HMODULE WINAPI dllGetStringTypeA(LCID Locale, DWORD dwInfoType, LPCSTR lpSrcStr, int cchSrc, LPWORD lpCharType)
{
not_implement("kernel32.dll fake function GetStringTypeA called\n"); //warning
return NULL;
}
extern "C" HMODULE WINAPI dllGetStringTypeW(DWORD dwInfoType, LPCWSTR lpSrcStr, int cchSrc, LPWORD lpCharType)
{
not_implement("kernel32.dll fake function GetStringTypeW called\n"); //warning
return NULL;
}
extern "C" HMODULE WINAPI dllGetCPInfo(UINT CodePage, LPCPINFO lpCPInfo)
{
not_implement("kernel32.dll fake function GetCPInfo called\n"); //warning
return NULL;
}
extern "C" LCID WINAPI dllGetThreadLocale(void)
{
// primary language identifier, sublanguage identifier, sorting identifier
return MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT);
}
extern "C" BOOL WINAPI dllSetPriorityClass(HANDLE hProcess, DWORD dwPriorityClass)
{
not_implement("kernel32.dll fake function SetPriorityClass called\n"); //warning
return false;
}
extern "C" DWORD WINAPI dllFormatMessageA(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPTSTR lpBuffer, DWORD nSize, va_list* Arguments)
{
#ifdef TARGET_WINDOWS
return FormatMessageA(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments);
#else
not_implement("kernel32.dll fake function FormatMessage called\n"); //warning
return 0;
#endif
}
extern "C" DWORD WINAPI dllGetFullPathNameA(LPCTSTR lpFileName, DWORD nBufferLength, LPTSTR lpBuffer, LPTSTR* lpFilePart)
{
#ifdef TARGET_WINDOWS
if (!lpFileName) return 0;
if(strstr(lpFileName, "://"))
{
unsigned int length = strlen(lpFileName);
if (nBufferLength < (length + 1))
return length + 1;
else
{
strcpy(lpBuffer, lpFileName);
if(lpFilePart)
{
char* s1 = strrchr(lpBuffer, '\\');
char* s2 = strrchr(lpBuffer, '/');
if(s2 && s1 > s2)
*lpFilePart = s1 + 1;
else if(s1 && s2 > s1)
*lpFilePart = s2 + 1;
else
*lpFilePart = lpBuffer;
}
return length;
}
}
return GetFullPathNameA(lpFileName, nBufferLength, lpBuffer, lpFilePart);
#else
not_implement("kernel32.dll fake function GetFullPathNameW called\n"); //warning
return 0;
#endif
}
extern "C" DWORD WINAPI dllGetFullPathNameW(LPCWSTR lpFileName, DWORD nBufferLength, LPWSTR lpBuffer, LPWSTR* lpFilePart)
{
#ifdef TARGET_WINDOWS
if (!lpFileName) return 0;
if(wcsstr(lpFileName, L"://"))
{
size_t length = wcslen(lpFileName);
if (nBufferLength < (length + 1))
return length + 1;
else
{
wcscpy(lpBuffer, lpFileName);
if(lpFilePart)
{
wchar_t* s1 = wcsrchr(lpBuffer, '\\');
wchar_t* s2 = wcsrchr(lpBuffer, '/');
if(s2 && s1 > s2)
*lpFilePart = s1 + 1;
else if(s1 && s2 > s1)
*lpFilePart = s2 + 1;
else
*lpFilePart = lpBuffer;
}
return length;
}
}
return GetFullPathNameW(lpFileName, nBufferLength, lpBuffer, lpFilePart);
#else
not_implement("kernel32.dll fake function GetFullPathNameW called\n"); //warning
return 0;
#endif
}
extern "C" DWORD WINAPI dllExpandEnvironmentStringsA(LPCTSTR lpSrc, LPTSTR lpDst, DWORD nSize)
{
#ifdef TARGET_WINDOWS
return ExpandEnvironmentStringsA(lpSrc, lpDst, nSize);
#else
not_implement("kernel32.dll fake function ExpandEnvironmentStringsA called\n"); //warning
return 0;
#endif
}
extern "C" UINT WINAPI dllGetWindowsDirectoryA(LPTSTR lpBuffer, UINT uSize)
{
not_implement("kernel32.dll fake function dllGetWindowsDirectory called\n"); //warning
return 0;
}
extern "C" UINT WINAPI dllGetSystemDirectoryA(LPTSTR lpBuffer, UINT uSize)
{
//char* systemdir = "special://xbmc/system/mplayer/codecs";
//unsigned int len = strlen(systemdir);
//if (len > uSize) return 0;
//strcpy(lpBuffer, systemdir);
//not_implement("kernel32.dll incompete function dllGetSystemDirectory called\n"); //warning
//CLog::Log(LOGDEBUG,"KERNEL32!GetSystemDirectoryA(0x%x, %d) => %s", lpBuffer, uSize, systemdir);
//return len;
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetSystemDirectoryA(%p,%d)\n", lpBuffer, uSize);
#endif
if (lpBuffer) strcpy(lpBuffer, ".");
return 1;
}
extern "C" UINT WINAPI dllGetShortPathName(LPTSTR lpszLongPath, LPTSTR lpszShortPath, UINT cchBuffer)
{
if (!lpszLongPath) return 0;
if (strlen(lpszLongPath) == 0)
{
//strcpy(lpszLongPath, "special://xbmc/system/mplayer/codecs/QuickTime.qts");
}
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "KERNEL32!GetShortPathNameA('%s',%p,%d)\n", lpszLongPath, lpszShortPath, cchBuffer);
#endif
strcpy(lpszShortPath, lpszLongPath);
return strlen(lpszShortPath);
}
extern "C" HANDLE WINAPI dllGetProcessHeap()
{
#ifdef TARGET_POSIX
CLog::Log(LOGWARNING, "KERNEL32!GetProcessHeap() linux cant provide this service!");
return 0;
#else
HANDLE hHeap;
hHeap = GetProcessHeap();
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "KERNEL32!GetProcessHeap() => 0x%x", hHeap);
#endif
return hHeap;
#endif
}
extern "C" UINT WINAPI dllSetErrorMode(UINT i)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "SetErrorMode(%d) => 0\n", i);
#endif
return 0;
}
extern "C" BOOL WINAPI dllIsProcessorFeaturePresent(DWORD ProcessorFeature)
{
BOOL result = 0;
switch (ProcessorFeature)
{
case PF_3DNOW_INSTRUCTIONS_AVAILABLE:
result = false;
break;
case PF_COMPARE_EXCHANGE_DOUBLE:
result = true;
break;
case PF_FLOATING_POINT_EMULATED:
result = true;
break;
case PF_FLOATING_POINT_PRECISION_ERRATA:
result = false;
break;
case PF_MMX_INSTRUCTIONS_AVAILABLE:
result = true;
break;
case PF_PAE_ENABLED:
result = false;
break;
case PF_RDTSC_INSTRUCTION_AVAILABLE:
result = true;
break;
case PF_XMMI_INSTRUCTIONS_AVAILABLE:
result = true;
break;
case 10: //PF_XMMI64_INSTRUCTIONS_AVAILABLE
result = false;
break;
}
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "IsProcessorFeaturePresent(0x%x) => 0x%x\n", ProcessorFeature, result);
#endif
return result;
}
extern "C" UINT WINAPI dllGetCurrentDirectoryA(UINT c, LPSTR s)
{
char curdir[] = "special://xbmc/";
int result;
strncpy(s, curdir, c);
result = 1 + ((c < strlen(curdir)) ? c : strlen(curdir));
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "GetCurrentDirectoryA(0x%x, %d) => %d\n", s, c, result);
#endif
return result;
}
extern "C" UINT WINAPI dllSetCurrentDirectoryA(const char *pathname)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "SetCurrentDirectoryA(0x%x = %s) => 1\n", pathname, pathname);
#endif
return 1;
}
extern "C" int WINAPI dllSetUnhandledExceptionFilter(void* filter)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "SetUnhandledExceptionFilter(0x%x) => 1\n", filter);
#endif
return 1; //unsupported and probably won't ever be supported
}
extern "C" int WINAPI dllSetEnvironmentVariableA(const char *name, const char *value)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "SetEnvironmentVariableA(%s, %s)\n", name, value);
#endif
return 0;
}
extern "C" int WINAPI dllCreateDirectoryA(const char *pathname, void *sa)
{
#ifdef API_DEBUG
CLog::Log(LOGDEBUG, "CreateDirectory(0x%x = %s, 0x%x) => 1\n", pathname, pathname, sa);
#endif
return 1;
}
extern "C" BOOL WINAPI dllGetProcessAffinityMask(HANDLE hProcess, LPDWORD lpProcessAffinityMask, LPDWORD lpSystemAffinityMask)
{
CLog::Log(LOGDEBUG, "GetProcessAffinityMask(%p, %p, %p) => 1\n",
(void*)hProcess, (void*)lpProcessAffinityMask, (void*)lpSystemAffinityMask);
if (lpProcessAffinityMask)*lpProcessAffinityMask = 1;
if (lpSystemAffinityMask)*lpSystemAffinityMask = 1;
return 1;
}
extern "C" int WINAPI dllGetLocaleInfoA(LCID Locale, LCTYPE LCType, LPTSTR lpLCData, int cchData)
{
if (Locale == LOCALE_SYSTEM_DEFAULT || Locale == LOCALE_USER_DEFAULT)
{
if (LCType == LOCALE_SISO639LANGNAME)
{
if (cchData > 3)
{
strcpy(lpLCData, "eng");
return 4;
}
}
else if (LCType == LOCALE_SISO3166CTRYNAME)
{
if (cchData > 2)
{
strcpy(lpLCData, "US");
return 3;
}
}
else if (LCType == LOCALE_IDEFAULTLANGUAGE)
{
if (cchData > 5)
{
strcpy(lpLCData, "en-US");
return 6;
}
}
}
not_implement("kernel32.dll incomplete function GetLocaleInfoA called\n"); //warning
SetLastError(ERROR_INVALID_FUNCTION);
return 0;
}
extern "C" UINT WINAPI dllGetConsoleCP()
{
return 437; // OEM - United States
}
extern "C" UINT WINAPI dllGetConsoleOutputCP()
{
return 437; // OEM - United States
}
// emulated because windows expects different behaviour
// the xbox calculates always 1 character extra for 0 termination
// however, this is only desired when cbMultiByte has the value -1
extern "C" int WINAPI dllMultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar)
{
// first fix, on windows cchWideChar and cbMultiByte may be the same.
// xbox fails, because it expects cbMultiByte to be at least one character bigger
// solution, create a new buffer to can hold the new data and copy it (without the 0 termination)
// to lpMultiByteStr. This is needed because we cannot be sure that lpMultiByteStr is big enough
int destinationBufferSize = cchWideChar;
LPWSTR destinationBuffer = lpWideCharStr;
if (cbMultiByte > 0 && cbMultiByte == cchWideChar) {
destinationBufferSize++;
destinationBuffer = (LPWSTR)malloc(destinationBufferSize * sizeof(WCHAR));
}
#ifdef TARGET_WINDOWS
int ret = MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, destinationBuffer, destinationBufferSize);
#else
int ret = 0;
#endif
if (ret > 0)
{
// second fix, but only if cchWideChar == 0, and ofcours ret > 0 indicating the function
// returned the number of bytes needed, otherwise ret would be 0, meaning a successfull conversion
if (cchWideChar == 0) {
ret--;
}
// revert the first fix again
if (cbMultiByte > 0 && cbMultiByte == cchWideChar) {
// the 0 termination character could never have been written on a windows machine
// because of cchWideChar == cbMultiByte, again xbox added one for it.
ret--;
memcpy(lpWideCharStr, destinationBuffer, ret * sizeof(WCHAR));
}
}
if (cbMultiByte > 0 && cbMultiByte == cchWideChar)
free(destinationBuffer);
return ret;
}
// same reason as above
extern "C" int WINAPI dllWideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, LPBOOL lpUsedDefaultChar)
{
// first fix, on windows cchWideChar and cbMultiByte may be the same.
// xbox fails, because it expects cbMultiByte to be at least one character bigger
// solution, create a new buffer to can hold the new data and copy it (without the 0 termination)
// to lpMultiByteStr. This is needed because we cannot be sure that lpMultiByteStr is big enough
int destinationBufferSize = cbMultiByte;
LPSTR destinationBuffer = lpMultiByteStr;
if (cchWideChar > 0 && cchWideChar == cbMultiByte) {
destinationBufferSize++;
destinationBuffer = (LPSTR)malloc(destinationBufferSize * sizeof(char));
}
#ifdef TARGET_WINDOWS
int ret = WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, destinationBuffer, destinationBufferSize, lpDefaultChar, lpUsedDefaultChar);
#else
int ret = 0;
#endif
if (ret > 0)
{
// second fix, but only if cbMultiByte == 0, and ofcours ret > 0 indicating the function
// returned the number of bytes needed, otherwise ret would be 0, meaning a successfull conversion
if (cbMultiByte == 0) {
ret--;
}
// revert the first fix again
if (cchWideChar > 0 && cchWideChar == cbMultiByte) {
// the 0 termination character could never have been written on a windows machine
// because of cchWideChar == cbMultiByte, again xbox added one for it.
ret--;
memcpy(lpMultiByteStr, destinationBuffer, ret);
}
}
if (cchWideChar > 0 && cchWideChar == cbMultiByte)
free(destinationBuffer);
return ret;
}
extern "C" UINT WINAPI dllSetConsoleCtrlHandler(PHANDLER_ROUTINE HandlerRoutine, BOOL Add)
{
#ifdef TARGET_WINDOWS
return SetConsoleCtrlHandler(HandlerRoutine, Add);
#else
// no consoles exists on the xbox, do nothing
not_implement("kernel32.dll fake function SetConsoleCtrlHandler called\n"); //warning
SetLastError(ERROR_INVALID_FUNCTION);
return 0;
#endif
}
extern "C" PVOID WINAPI dllEncodePointer(PVOID ptr)
{
return ptr;
}
extern "C" PVOID WINAPI dllDecodePointer(PVOID ptr)
{
return ptr;
}
extern "C" HANDLE WINAPI dllCreateFileA(
IN LPCSTR lpFileName,
IN DWORD dwDesiredAccess,
IN DWORD dwShareMode,
IN LPSECURITY_ATTRIBUTES lpSecurityAttributes,
IN DWORD dwCreationDisposition,
IN DWORD dwFlagsAndAttributes,
IN HANDLE hTemplateFile
)
{
return CreateFileA(CSpecialProtocol::TranslatePath(lpFileName).c_str(), dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
}
extern "C" BOOL WINAPI dllLockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOffBytesToLockLow, DWORD nNumberOffBytesToLockHigh)
{
//return LockFile(hFile, dwFileOffsetLow, dwFileOffsetHigh, nNumberOffBytesToLockLow, nNumberOffBytesToLockHigh);
return TRUE;
}
extern "C" BOOL WINAPI dllLockFileEx(HANDLE hFile, DWORD dwFlags, DWORD dwReserved, DWORD nNumberOffBytesToLockLow, DWORD nNumberOffBytesToLockHigh, LPOVERLAPPED lpOverlapped)
{
//return LockFileEx(hFile, dwFlags, nNumberOffBytesToLockLow, nNumberOffBytesToLockHigh, lpOverlapped);
return TRUE;
}
extern "C" BOOL WINAPI dllUnlockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh)
{
//return UnlockFile(hFile, dwFileOffsetLow, dwFileOffsetHigh, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
return TRUE;
}
extern "C" DWORD WINAPI dllGetTempPathA(DWORD nBufferLength, LPTSTR lpBuffer)
{
// If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpBuffer,
// not including the terminating null character. If the return value is greater than nBufferLength,
// the return value is the size of the buffer required to hold the path.
const char* tempPath = "special://temp/temp/";
unsigned int len = strlen(tempPath);
if (nBufferLength > len)
{
strcpy(lpBuffer, tempPath);
}
return len;
}
extern "C" HGLOBAL WINAPI dllLoadResource(HMODULE hModule, HRSRC hResInfo)
{
not_implement("kernel32.dll fake function LoadResource called\n");
return NULL;
}
extern "C" HRSRC WINAPI dllFindResourceA(HMODULE hModule, LPCTSTR lpName, LPCTSTR lpType)
{
not_implement("kernel32.dll fake function FindResource called\n");
return NULL;
}
/*
The following routine was hacked up by JM while looking at why the DVD player was failing
in the middle of the movie. The symptoms were:
1. DVD player returned error about expecting a NAV packet but none found.
2. Resulted in DVD player closing.
3. Always occured in the same place.
4. Occured on every DVD I tried (originals)
5. Approximately where I would expect the layer change to be (ie just over half way
through the movie)
6. Resulted in the last chunk of the requested data to be NULL'd out completely. ReadFile()
returns correctly, but the last chunk is completely zero'd out.
This routine checks the last chunk for zeros, and re-reads if necessary.
*/
#define DVD_CHUNK_SIZE 2048
extern "C" BOOL WINAPI dllDVDReadFileLayerChangeHack(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
BOOL ret = ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
if (!ret || !lpNumberOfBytesRead || *lpNumberOfBytesRead < DVD_CHUNK_SIZE) return ret;
DWORD numChecked = *lpNumberOfBytesRead;
while (numChecked >= DVD_CHUNK_SIZE)
{
BYTE *p = (BYTE *)lpBuffer + numChecked - DVD_CHUNK_SIZE;
// test for a NULL block
while (*p == 0 && p < (BYTE *)lpBuffer + numChecked)
p++;
if (p == (BYTE *)lpBuffer + numChecked)
{ // fully NULL block - reread
#ifdef TARGET_WINDOWS
LONG low = 0;
LONG high = 0;
#else
int32_t low = 0;
int32_t high = 0;
#endif
low = SetFilePointer(hFile, low, &high, FILE_CURRENT);
CLog::Log(LOGWARNING,
"DVDReadFile() warning - "
"invalid data read from block at %i (%i) - rereading",
low, high);
SetFilePointer(hFile, (int)numChecked - (int)*lpNumberOfBytesRead - DVD_CHUNK_SIZE, NULL, FILE_CURRENT);
DWORD numRead;
ret = ReadFile(hFile, (BYTE *)lpBuffer + numChecked - DVD_CHUNK_SIZE, DVD_CHUNK_SIZE, &numRead, lpOverlapped);
if (!ret) return FALSE;
SetFilePointer(hFile, low, &high, FILE_BEGIN);
}
numChecked -= DVD_CHUNK_SIZE;
}
return ret;
}
extern "C" LPVOID WINAPI dllLockResource(HGLOBAL hResData)
{
#ifdef TARGET_WINDOWS
return LockResource(hResData);
#else
not_implement("kernel32.dll fake function LockResource called\n"); //warning
return 0;
#endif
}
extern "C" SIZE_T WINAPI dllGlobalSize(HGLOBAL hMem)
{
#ifdef TARGET_WINDOWS
return GlobalSize(hMem);
#else
not_implement("kernel32.dll fake function GlobalSize called\n"); //warning
return 0;
#endif
}
extern "C" DWORD WINAPI dllSizeofResource(HMODULE hModule, HRSRC hResInfo)
{
#ifdef TARGET_WINDOWS
return SizeofResource(hModule, hResInfo);
#else
not_implement("kernel32.dll fake function SizeofResource called\n"); //warning
return 0;
#endif
}
| 30.190346 | 201 | 0.718061 | [
"vector"
] |
0ab19dc9d2a621deed7912a69826cd11cf28ee56 | 23,881 | cpp | C++ | src/mongo/client/server_discovery_monitor_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/client/server_discovery_monitor_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/client/server_discovery_monitor_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <memory>
#include <boost/optional/optional_io.hpp>
#include "mongo/client/replica_set_monitor.h"
#include "mongo/client/replica_set_monitor_protocol_test_util.h"
#include "mongo/client/sdam/sdam.h"
#include "mongo/client/sdam/sdam_configuration_parameters_gen.h"
#include "mongo/client/sdam/topology_description.h"
#include "mongo/client/sdam/topology_listener_mock.h"
#include "mongo/client/server_discovery_monitor.h"
#include "mongo/dbtests/mock/mock_replica_set.h"
#include "mongo/executor/network_interface_mock.h"
#include "mongo/executor/thread_pool_mock.h"
#include "mongo/executor/thread_pool_task_executor.h"
#include "mongo/executor/thread_pool_task_executor_test_fixture.h"
#include "mongo/logv2/log.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/duration.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
namespace mongo {
namespace {
using executor::NetworkInterfaceMock;
using executor::RemoteCommandResponse;
using executor::ThreadPoolExecutorTest;
using InNetworkGuard = NetworkInterfaceMock::InNetworkGuard;
class ServerDiscoveryMonitorTestFixture : public unittest::Test {
protected:
/**
* Sets up the task executor as well as a TopologyListenerMock for each unit test.
*/
void setUp() override {
auto serviceContext = ServiceContext::make();
setGlobalServiceContext(std::move(serviceContext));
ReplicaSetMonitorProtocolTestUtil::setRSMProtocol(ReplicaSetMonitorProtocol::kSdam);
ReplicaSetMonitor::cleanup();
auto network = std::make_unique<executor::NetworkInterfaceMock>();
_net = network.get();
_executor = makeSharedThreadPoolTestExecutor(std::move(network));
_executor->startup();
_startDate = _net->now();
_eventsPublisher = std::make_shared<sdam::TopologyEventsPublisher>(_executor);
_topologyListener.reset(new sdam::TopologyListenerMock());
_eventsPublisher->registerListener(_topologyListener);
}
void tearDown() override {
_eventsPublisher.reset();
_topologyListener.reset();
_executor->shutdown();
_executor->join();
_executor.reset();
ReplicaSetMonitor::cleanup();
ReplicaSetMonitorProtocolTestUtil::resetRSMProtocol();
}
sdam::TopologyListenerMock* getTopologyListener() {
return _topologyListener.get();
}
std::shared_ptr<sdam::TopologyEventsPublisher> getEventsPublisher() {
return _eventsPublisher;
}
executor::NetworkInterfaceMock* getNet() {
return _net;
}
std::shared_ptr<executor::ThreadPoolTaskExecutor> getExecutor() {
return _executor;
}
Date_t getStartDate() {
return _startDate;
}
bool hasReadyRequests() {
NetworkInterfaceMock::InNetworkGuard ing(_net);
return _net->hasReadyRequests();
}
Milliseconds elapsed() {
return _net->now() - _startDate;
}
/**
* Sets up a SingleServerDiscoveryMonitor that starts sending isMasters to the server.
*/
std::shared_ptr<SingleServerDiscoveryMonitor> initSingleServerDiscoveryMonitor(
const sdam::SdamConfiguration& sdamConfiguration,
const HostAndPort& hostAndPort,
MockReplicaSet* replSet) {
auto ssIsMasterMonitor = std::make_shared<SingleServerDiscoveryMonitor>(replSet->getURI(),
hostAndPort,
boost::none,
sdamConfiguration,
_eventsPublisher,
_executor,
_stats);
ssIsMasterMonitor->init();
// Ensure that the clock has not advanced since setUp() and _startDate is representative
// of when the first isMaster request was sent.
ASSERT_EQ(getStartDate(), getNet()->now());
return ssIsMasterMonitor;
}
std::shared_ptr<ServerDiscoveryMonitor> initServerDiscoveryMonitor(
const MongoURI& setUri,
const sdam::SdamConfiguration& sdamConfiguration,
const sdam::TopologyDescriptionPtr topologyDescription) {
auto serverIsMasterMonitor = std::make_shared<ServerDiscoveryMonitor>(
setUri, sdamConfiguration, _eventsPublisher, topologyDescription, _stats, _executor);
// Ensure that the clock has not advanced since setUp() and _startDate is representative
// of when the first isMaster request was sent.
ASSERT_EQ(getStartDate(), getNet()->now());
return serverIsMasterMonitor;
}
/**
* Checks that an isMaster request has been sent to some server and schedules a response. If
* assertHostCheck is true, asserts that the isMaster was sent to the server at hostAndPort.
*/
void processIsMasterRequest(MockReplicaSet* replSet,
boost::optional<HostAndPort> hostAndPort = boost::none) {
ASSERT(hasReadyRequests());
InNetworkGuard guard(_net);
_net->runReadyNetworkOperations();
auto noi = _net->getNextReadyRequest();
auto request = noi->getRequest();
executor::TaskExecutorTest::assertRemoteCommandNameEquals("isMaster", request);
auto requestHost = request.target.toString();
if (hostAndPort) {
ASSERT_EQ(request.target, hostAndPort);
}
LOGV2(457991,
"Got mock network operation",
"elapsed"_attr = elapsed(),
"request"_attr = request.toString());
const auto node = replSet->getNode(requestHost);
if (node->isRunning()) {
const auto opmsg = OpMsgRequest::fromDBAndBody(request.dbname, request.cmdObj);
const auto reply = node->runCommand(request.id, opmsg)->getCommandReply();
_net->scheduleSuccessfulResponse(noi, RemoteCommandResponse(reply, Milliseconds(0)));
} else {
_net->scheduleErrorResponse(noi, Status(ErrorCodes::HostUnreachable, ""));
}
}
template <typename Duration>
void advanceTime(Duration d) {
InNetworkGuard guard(_net);
// Operations can happen inline with advanceTime(), so log before and after the call.
LOGV2_DEBUG(457992,
1,
"Advancing time",
"elpasedStart"_attr = elapsed(),
"elapsedEnd"_attr = (elapsed() + d));
_net->advanceTime(_net->now() + d);
LOGV2_DEBUG(457993, 1, "Advanced time", "timeElapsed"_attr = elapsed());
}
/**
* Checks that exactly one successful isMaster occurs within a time interval of
* heartbeatFrequency.
*/
void checkSingleIsMaster(Milliseconds heartbeatFrequency,
const HostAndPort& hostAndPort,
MockReplicaSet* replSet) {
auto deadline = elapsed() + heartbeatFrequency;
processIsMasterRequest(replSet, hostAndPort);
while (elapsed() < deadline && !_topologyListener->hasIsMasterResponse(hostAndPort)) {
advanceTime(Milliseconds(1));
}
validateIsMasterResponse(hostAndPort, deadline);
checkNoActivityBefore(deadline, hostAndPort);
}
void validateIsMasterResponse(const HostAndPort& hostAndPort, Milliseconds deadline) {
ASSERT_TRUE(_topologyListener->hasIsMasterResponse(hostAndPort));
ASSERT_LT(elapsed(), deadline);
auto isMasterResponse = _topologyListener->getIsMasterResponse(hostAndPort);
// There should only be one isMaster response queued up.
ASSERT_EQ(isMasterResponse.size(), 1);
ASSERT(isMasterResponse[0].isOK());
}
/**
* Confirms no more isMaster requests are sent between elapsed() and deadline. Confirms no more
* isMaster responses are received between elapsed() and deadline when hostAndPort is specified.
*/
void checkNoActivityBefore(Milliseconds deadline,
boost::optional<HostAndPort> hostAndPort = boost::none) {
while (elapsed() < deadline) {
ASSERT_FALSE(hasReadyRequests());
if (hostAndPort) {
ASSERT_FALSE(_topologyListener->hasIsMasterResponse(hostAndPort.get()));
}
advanceTime(Milliseconds(1));
}
}
/**
* Waits up to timeoutMS for the next isMaster request to go out.
* Causes the test to fail if timeoutMS time passes and no request is ready.
*
* NOTE: The time between each isMaster request is the heartbeatFrequency compounded by response
* time.
*/
void waitForNextIsMaster(Milliseconds timeoutMS) {
auto deadline = elapsed() + timeoutMS;
while (!hasReadyRequests() && elapsed() < deadline) {
advanceTime(Milliseconds(1));
}
ASSERT_LT(elapsed(), deadline);
}
private:
Date_t _startDate;
std::shared_ptr<sdam::TopologyEventsPublisher> _eventsPublisher;
std::shared_ptr<sdam::TopologyListenerMock> _topologyListener;
std::shared_ptr<executor::ThreadPoolTaskExecutor> _executor;
executor::NetworkInterfaceMock* _net;
std::shared_ptr<ReplicaSetMonitorManagerStats> _managerStats =
std::make_shared<ReplicaSetMonitorManagerStats>();
std::shared_ptr<ReplicaSetMonitorStats> _stats =
std::make_shared<ReplicaSetMonitorStats>(_managerStats);
};
/**
* Checks that a SingleServerDiscoveryMonitor sends isMaster requests at least heartbeatFrequency
* apart.
*/
TEST_F(ServerDiscoveryMonitorTestFixture, heartbeatFrequencyCheck) {
auto replSet = std::make_unique<MockReplicaSet>(
"test", 1, /* hasPrimary = */ false, /* dollarPrefixHosts = */ false);
auto hostAndPort = HostAndPort(replSet->getSecondaries()[0]);
const auto config = SdamConfiguration(std::vector<HostAndPort>{hostAndPort});
auto ssIsMasterMonitor = initSingleServerDiscoveryMonitor(config, hostAndPort, replSet.get());
ssIsMasterMonitor->disableExpeditedChecking();
// An isMaster command fails if it takes as long or longer than timeoutMS.
auto timeoutMS = config.getConnectionTimeout();
auto heartbeatFrequency = config.getHeartBeatFrequency();
checkSingleIsMaster(heartbeatFrequency, hostAndPort, replSet.get());
waitForNextIsMaster(timeoutMS);
checkSingleIsMaster(heartbeatFrequency, hostAndPort, replSet.get());
waitForNextIsMaster(timeoutMS);
checkSingleIsMaster(heartbeatFrequency, hostAndPort, replSet.get());
waitForNextIsMaster(timeoutMS);
checkSingleIsMaster(heartbeatFrequency, hostAndPort, replSet.get());
waitForNextIsMaster(timeoutMS);
}
/**
* Confirms that a SingleServerDiscoveryMonitor reports to the TopologyListener when an isMaster
* command generates an error.
*/
TEST_F(ServerDiscoveryMonitorTestFixture, singleServerDiscoveryMonitorReportsFailure) {
auto replSet = std::make_unique<MockReplicaSet>(
"test", 1, /* hasPrimary = */ false, /* dollarPrefixHosts = */ false);
// Kill the server before starting up the SingleServerDiscoveryMonitor.
auto hostAndPort = HostAndPort(replSet->getSecondaries()[0]);
{
NetworkInterfaceMock::InNetworkGuard ing(getNet());
replSet->kill(hostAndPort.toString());
}
const auto config = SdamConfiguration(std::vector<HostAndPort>{hostAndPort});
auto ssIsMasterMonitor = initSingleServerDiscoveryMonitor(config, hostAndPort, replSet.get());
ssIsMasterMonitor->disableExpeditedChecking();
processIsMasterRequest(replSet.get(), hostAndPort);
auto topologyListener = getTopologyListener();
auto timeoutMS = config.getConnectionTimeout();
while (elapsed() < timeoutMS && !topologyListener->hasIsMasterResponse(hostAndPort)) {
// Advance time in small increments to ensure we stop before another isMaster is sent.
advanceTime(Milliseconds(1));
}
ASSERT_TRUE(topologyListener->hasIsMasterResponse(hostAndPort));
auto response = topologyListener->getIsMasterResponse(hostAndPort);
ASSERT_EQ(response.size(), 1);
ASSERT_EQ(response[0], ErrorCodes::HostUnreachable);
}
TEST_F(ServerDiscoveryMonitorTestFixture, serverIsMasterMonitorOnTopologyDescriptionChangeAddHost) {
auto replSet = std::make_unique<MockReplicaSet>(
"test", 2, /* hasPrimary = */ false, /* dollarPrefixHosts = */ false);
auto hostAndPortList = replSet->getHosts();
auto host0 = hostAndPortList[0];
std::vector<HostAndPort> host0Vec{host0};
// Start up the ServerDiscoveryMonitor to monitor host0 only.
auto sdamConfig0 = sdam::SdamConfiguration(host0Vec);
auto topologyDescription0 = std::make_shared<sdam::TopologyDescription>(sdamConfig0);
auto uri = replSet->getURI();
auto isMasterMonitor = initServerDiscoveryMonitor(uri, sdamConfig0, topologyDescription0);
isMasterMonitor->disableExpeditedChecking();
auto host1Delay = Milliseconds(100);
checkSingleIsMaster(host1Delay, host0, replSet.get());
ASSERT_FALSE(hasReadyRequests());
// Start monitoring host1.
auto host1 = hostAndPortList[1];
std::vector<HostAndPort> allHostsVec{host0, host1};
auto sdamConfigAllHosts = sdam::SdamConfiguration(allHostsVec);
auto topologyDescriptionAllHosts =
std::make_shared<sdam::TopologyDescription>(sdamConfigAllHosts);
isMasterMonitor->onTopologyDescriptionChangedEvent(topologyDescription0,
topologyDescriptionAllHosts);
// Ensure expedited checking is disabled for the SingleServerDiscoveryMonitor corresponding to
// host1 as well.
isMasterMonitor->disableExpeditedChecking();
// Confirm host0 and host1 are monitored.
auto heartbeatFrequency = sdamConfigAllHosts.getHeartBeatFrequency();
checkSingleIsMaster(heartbeatFrequency - host1Delay, host1, replSet.get());
waitForNextIsMaster(sdamConfigAllHosts.getConnectionTimeout());
checkSingleIsMaster(host1Delay, host0, replSet.get());
}
TEST_F(ServerDiscoveryMonitorTestFixture,
serverIsMasterMonitorOnTopologyDescriptionChangeRemoveHost) {
auto replSet = std::make_unique<MockReplicaSet>(
"test", 2, /* hasPrimary = */ false, /* dollarPrefixHosts = */ false);
auto hostAndPortList = replSet->getHosts();
auto host0 = hostAndPortList[0];
auto host1 = hostAndPortList[1];
std::vector<HostAndPort> allHostsVec{host0, host1};
// Start up the ServerDiscoveryMonitor to monitor both hosts.
auto sdamConfigAllHosts = sdam::SdamConfiguration(allHostsVec);
auto topologyDescriptionAllHosts =
std::make_shared<sdam::TopologyDescription>(sdamConfigAllHosts);
auto uri = replSet->getURI();
auto isMasterMonitor =
initServerDiscoveryMonitor(uri, sdamConfigAllHosts, topologyDescriptionAllHosts);
isMasterMonitor->disableExpeditedChecking();
// Confirm that both hosts are monitored.
auto heartbeatFrequency = sdamConfigAllHosts.getHeartBeatFrequency();
while (hasReadyRequests()) {
processIsMasterRequest(replSet.get());
}
auto deadline = elapsed() + heartbeatFrequency;
auto topologyListener = getTopologyListener();
auto hasResponses = [&]() {
return topologyListener->hasIsMasterResponse(host0) &&
topologyListener->hasIsMasterResponse(host1);
};
while (elapsed() < heartbeatFrequency && !hasResponses()) {
advanceTime(Milliseconds(1));
}
validateIsMasterResponse(host0, deadline);
validateIsMasterResponse(host1, deadline);
// Remove host1 from the TopologyDescription to stop monitoring it.
std::vector<HostAndPort> host0Vec{host0};
auto sdamConfig0 = sdam::SdamConfiguration(host0Vec);
auto topologyDescription0 = std::make_shared<sdam::TopologyDescription>(sdamConfig0);
isMasterMonitor->onTopologyDescriptionChangedEvent(topologyDescriptionAllHosts,
topologyDescription0);
checkNoActivityBefore(deadline);
waitForNextIsMaster(sdamConfig0.getConnectionTimeout());
checkSingleIsMaster(heartbeatFrequency, host0, replSet.get());
waitForNextIsMaster(sdamConfig0.getConnectionTimeout());
// Confirm the next isMaster request is sent to host0 and not host1.
checkSingleIsMaster(heartbeatFrequency, host0, replSet.get());
}
TEST_F(ServerDiscoveryMonitorTestFixture, serverIsMasterMonitorShutdownStopsIsMasterRequests) {
auto replSet = std::make_unique<MockReplicaSet>(
"test", 1, /* hasPrimary = */ false, /* dollarPrefixHosts = */ false);
std::vector<HostAndPort> hostVec{replSet->getHosts()[0]};
auto sdamConfig = sdam::SdamConfiguration(hostVec);
auto topologyDescription = std::make_shared<sdam::TopologyDescription>(sdamConfig);
auto uri = replSet->getURI();
auto isMasterMonitor = initServerDiscoveryMonitor(uri, sdamConfig, topologyDescription);
isMasterMonitor->disableExpeditedChecking();
auto heartbeatFrequency = sdamConfig.getHeartBeatFrequency();
checkSingleIsMaster(heartbeatFrequency - Milliseconds(200), hostVec[0], replSet.get());
isMasterMonitor->shutdown();
// After the ServerDiscoveryMonitor shuts down, the TopologyListener may have responses until
// heartbeatFrequency has passed, but none of them should indicate Status::OK.
auto deadline = elapsed() + heartbeatFrequency;
auto topologyListener = getTopologyListener();
// Drain any requests already scheduled.
while (elapsed() < deadline) {
while (hasReadyRequests()) {
processIsMasterRequest(replSet.get(), hostVec[0]);
}
if (topologyListener->hasIsMasterResponse(hostVec[0])) {
auto isMasterResponses = topologyListener->getIsMasterResponse(hostVec[0]);
for (auto& response : isMasterResponses) {
ASSERT_FALSE(response.isOK());
}
}
advanceTime(Milliseconds(1));
}
ASSERT_FALSE(topologyListener->hasIsMasterResponse(hostVec[0]));
}
/**
* Tests that the ServerDiscoveryMonitor waits until SdamConfiguration::kMinHeartbeatFrequency has
* passed since the last isMaster was received if requestImmediateCheck() is called before enough
* time has passed.
*/
TEST_F(ServerDiscoveryMonitorTestFixture,
serverIsMasterMonitorRequestImmediateCheckWaitMinHeartbeat) {
auto replSet = std::make_unique<MockReplicaSet>(
"test", 1, /* hasPrimary = */ false, /* dollarPrefixHosts = */ false);
std::vector<HostAndPort> hostVec{replSet->getHosts()[0]};
// Start up the ServerDiscoveryMonitor to monitor host0 only.
auto sdamConfig0 = sdam::SdamConfiguration(hostVec);
auto topologyDescription0 = std::make_shared<sdam::TopologyDescription>(sdamConfig0);
auto uri = replSet->getURI();
auto isMasterMonitor = initServerDiscoveryMonitor(uri, sdamConfig0, topologyDescription0);
// Ensure the server is not in expedited mode *before* requestImmediateCheck().
isMasterMonitor->disableExpeditedChecking();
// Check that there is only one isMaster request at time t=0 up until
// timeAdvanceFromFirstIsMaster.
auto minHeartbeatFrequency = SdamConfiguration::kMinHeartbeatFrequency;
auto timeAdvanceFromFirstIsMaster = Milliseconds(10);
ASSERT_LT(timeAdvanceFromFirstIsMaster, minHeartbeatFrequency);
checkSingleIsMaster(timeAdvanceFromFirstIsMaster, hostVec[0], replSet.get());
// It's been less than SdamConfiguration::kMinHeartbeatFrequency since the last isMaster was
// received. The next isMaster should be sent SdamConfiguration::kMinHeartbeatFrequency since
// the last isMaster was recieved rather than immediately.
auto timeRequestImmediateSent = elapsed();
isMasterMonitor->requestImmediateCheck();
waitForNextIsMaster(minHeartbeatFrequency);
auto timeIsMasterSent = elapsed();
ASSERT_LT(timeRequestImmediateSent, timeIsMasterSent);
ASSERT_LT(timeIsMasterSent, timeRequestImmediateSent + minHeartbeatFrequency);
checkSingleIsMaster(minHeartbeatFrequency, hostVec[0], replSet.get());
// Confirm expedited requests continue since there is no primary.
waitForNextIsMaster(sdamConfig0.getConnectionTimeout());
checkSingleIsMaster(minHeartbeatFrequency, hostVec[0], replSet.get());
}
/**
* Tests that if more than SdamConfiguration::kMinHeartbeatFrequency has passed since the last
* isMaster response was received, the ServerDiscoveryMonitor sends an isMaster immediately after
* requestImmediateCheck() is called.
*/
TEST_F(ServerDiscoveryMonitorTestFixture, serverIsMasterMonitorRequestImmediateCheckNoWait) {
auto replSet = std::make_unique<MockReplicaSet>(
"test", 1, /* hasPrimary = */ false, /* dollarPrefixHosts = */ false);
std::vector<HostAndPort> hostVec{replSet->getHosts()[0]};
// Start up the ServerDiscoveryMonitor to monitor host0 only.
auto sdamConfig0 = sdam::SdamConfiguration(hostVec);
auto topologyDescription0 = std::make_shared<sdam::TopologyDescription>(sdamConfig0);
auto uri = replSet->getURI();
auto isMasterMonitor = initServerDiscoveryMonitor(uri, sdamConfig0, topologyDescription0);
// Ensure the server is not in expedited mode *before* requestImmediateCheck().
isMasterMonitor->disableExpeditedChecking();
// No less than SdamConfiguration::kMinHeartbeatFrequency must pass before
// requestImmediateCheck() is called in order to ensure the server reschedules for an immediate
// check.
auto minHeartbeatFrequency = SdamConfiguration::kMinHeartbeatFrequency;
checkSingleIsMaster(minHeartbeatFrequency + Milliseconds(10), hostVec[0], replSet.get());
isMasterMonitor->requestImmediateCheck();
checkSingleIsMaster(minHeartbeatFrequency, hostVec[0], replSet.get());
// Confirm expedited requests continue since there is no primary.
waitForNextIsMaster(sdamConfig0.getConnectionTimeout());
checkSingleIsMaster(minHeartbeatFrequency, hostVec[0], replSet.get());
}
} // namespace
} // namespace mongo
| 43.578467 | 100 | 0.703069 | [
"vector"
] |
0ab420332b103395b007a8355f5adf242172bcc5 | 4,392 | cpp | C++ | src/adtfUser/katana_mission_control/src/mission_control/maneuver.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | src/adtfUser/katana_mission_control/src/mission_control/maneuver.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | src/adtfUser/katana_mission_control/src/mission_control/maneuver.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Christoph Rist <rist@fzi.de>
* \date 2014-11-29
*
*/
//----------------------------------------------------------------------
#include "mission_control/maneuver.h"
#ifdef KATANA_MC_IMPORTANT_DEBUG_MSG
#include <iostream>
#endif
using namespace tinyxml2;
namespace katana
{
const char* Maneuver::XML_ACTION_STRINGS[] =
{
"left",
"straight",
"right",
"parallel_parking",
"cross_parking",
"pull_out_left",
"pull_out_right"
};
Maneuver::Maneuver()
: m_ready(false)
, m_current_sector(0)
, m_current_maneuver(0)
{
}
void Maneuver::readManeuver(const std::string& file)
{
XMLDocument doc;
doc.LoadFile(file.c_str());
XMLElement* titleElement = doc.FirstChildElement(XML_AADC_LIST);
_maneuver_id_type maneuver_id_counter = 0;
for (XMLElement* sector = titleElement->FirstChildElement(XML_AADC_SECTOR); sector != nullptr; sector = sector->NextSiblingElement(XML_AADC_SECTOR))
{
//Add this new sector
m_data.push_back(Sector(std::vector<AADCManeuver>(), sector->IntAttribute(XML_ATTRIBUTE_ID)));
//Read maneuver
for (XMLElement* m = sector->FirstChildElement(XML_AADC_MANEUVER); m != nullptr; m = m->NextSiblingElement(XML_AADC_MANEUVER))
{
AADCManeuver element(getActionFromXMLString(m->Attribute(XML_ATTRIBUTE_ACTION)), m->IntAttribute(XML_ATTRIBUTE_ID));
if (element.first == Action::UNKNOWN)
{
#ifdef KATANA_MC_IMPORTANT_DEBUG_MSG
std::cout <<"WARNING: Unknown maneuver list entry " <<m->Attribute(XML_ATTRIBUTE_ACTION) <<" - skipping" <<std::endl;
#endif
++maneuver_id_counter;
continue;
}
// add new maneuver
m_data.back().first.push_back(element);
#ifdef KATANA_MC_IMPORTANT_DEBUG_MSG
if (element.second != maneuver_id_counter)
std::cout <<"WARNING: IDs of maneuver entries not in ascending order (at id " <<element.second <<"). This may result in undefined conditions!" <<std::endl;
#endif
// increase id counter
++maneuver_id_counter;
}
//if empty sector -> remove sector
if (m_data.back().first.empty())
m_data.erase(m_data.end() - 1);
}
resetPosition();
m_ready = true;
}
Action Maneuver::getActionFromXMLString(const char *str)
{
Action i;
for (i = Action::First; i != Action::UNKNOWN; i = next(i) )
{
if (strcmp(XML_ACTION_STRINGS[(int8_t)i], str) == 0)
break;
}
return i;
}
void Maneuver::resetPosition()
{
#ifdef KATANA_MC_MANEUVER_DEBUG
std::cout << "MC maneuver: Resetting position." << std::endl;
#endif
m_current_maneuver = 0;
m_current_sector = 0;
}
void Maneuver::resetSector()
{
#ifdef KATANA_MC_MANEUVER_DEBUG
std::cout << "MC maneuver: Resetting sector." << std::endl;
#endif
m_current_maneuver = 0;
}
bool Maneuver::advanceManeuver()
{
#ifdef KATANA_MC_MANEUVER_DEBUG
std::cout << "MC maneuver: Going to next maneuver." << std::endl;
#endif
if (isLastManeuverInSector())
return false;
++m_current_maneuver;
return true;
}
bool Maneuver::nextSector()
{
if (isLastSector())
return false;
#ifdef KATANA_MC_MANEUVER_DEBUG
std::cout << "MC maneuver: Going to next sector." << std::endl;
#endif
m_current_maneuver = 0;
++m_current_sector;
return true;
}
void Maneuver::setManeuver(Maneuver::_maneuver_id_type maneuver_id)
{
for(uint32_t sectorId = 0; sectorId < m_data.size(); ++sectorId) {
for(uint32_t i = 0; i < m_data.at(sectorId).first.size(); ++i) {
if(m_data.at(sectorId).first.at(i).second == maneuver_id) {
m_current_sector = sectorId;
m_current_maneuver = i;
#ifdef KATANA_MC_MANEUVER_DEBUG
std::cout << "MC maneuver: set maneuver to " <<m_data.at(sectorId).first.at(i).second << " (position " << m_current_maneuver << ") and sector to " << m_current_sector << std::endl;
#endif
return;
}
}
}
}
bool Maneuver::increaseManeuver()
{
// If external actions are available use them
if(!m_external_actions.empty()) {
m_external_actions.pop();
return true;
}
if (!advanceManeuver())
return nextSector();
return true;
}
} // ns
| 25.097143 | 183 | 0.64276 | [
"vector"
] |
0ab4c1ae8b7d9630f8eeac696ae39440d178b2d2 | 872 | cpp | C++ | hackathon/shengdian/MorphoHub_Release/Generator/bouton_fun.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/shengdian/MorphoHub_Release/Generator/bouton_fun.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/shengdian/MorphoHub_Release/Generator/bouton_fun.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include "bouton_fun.h"
void printHelp()
{
/*vaa3d -x <libname> -f Bouton_Generation -i <input-para-list> -o <out-para-list> -p <fun_id> <node-specified> <out_type>
* <fun_id>:
* case 0: get bouton from terafly formatted data. <input_image_terafly> and <input_swc> are needed.
* case 1: get bouton from 3D image block.
* case 2: get the intensity of all the nodes (SWC or ESWC) from terafly formatted data.
* case 3:
* <node-specified>:
* case 0: all nodes in swc will be used.
* case 1: axonal nodes (type=2)
* <out_type>:
* case 0: output bouton data to a point cloud (apo)
* case 1: output bouton data to SWC/ESWC file (radius feature = 2)
* case 2: output bouton data to ESWC file (level feature = 2,keep non-bouton node)
* case 3: output bouton data to ESWC file (remove non-bouton node)
*/
}
| 41.52381 | 125 | 0.650229 | [
"3d"
] |
0ac8bf00b9f700230e41c431f886479713dbf0d3 | 2,746 | cpp | C++ | test/src/project_test.cpp | thvaisa/onetracer | b6567194148a441370dbdb7040631fd43ec50ae2 | [
"MIT"
] | null | null | null | test/src/project_test.cpp | thvaisa/onetracer | b6567194148a441370dbdb7040631fd43ec50ae2 | [
"MIT"
] | null | null | null | test/src/project_test.cpp | thvaisa/onetracer | b6567194148a441370dbdb7040631fd43ec50ae2 | [
"MIT"
] | null | null | null | #include <project.hpp>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <limits.h>
using ::testing::_;
using ::testing::ElementsAre;
class ProjectTest : public ::testing::Test{
protected:
const c_float inf = std::numeric_limits<c_float>::infinity();
const c_float nan0 = std::numeric_limits<c_float>::quiet_NaN();
virtual void SetUp() {
};
virtual void TearDown() {
};
};
TEST_F(ProjectTest, Test_copy_arr) {
c_float vec0[3] = {0,inf,inf};
c_float vec1[3] = {0,0, nan0};
c_float vec2[3] = {1,2,3};
c_float vec3[3];
EXPECT_DEBUG_DEATH(copy_arr<c_float>(vec3,vec0,3),"c");
EXPECT_DEBUG_DEATH(copy_arr<c_float>(vec3,vec1,3),"c");
copy_arr<c_float>(vec3,vec2,3);
ASSERT_THAT(std::vector<c_float>(vec2, vec2+3), testing::ElementsAreArray(vec3,3));
}
TEST_F(ProjectTest, Test_dot_product) {
c_float vec2[2] = {1.0,2.0};
c_float sum = dot_product(vec2,vec2,2);
EXPECT_EQ(vec2[0]*vec2[0]+vec2[1]*vec2[1],sum);
}
TEST_F(ProjectTest, Test_dot_product_diff) {
c_float vec2[2] = {1,2};
c_float vec3[2] = {2,3};
c_float value = 0.0;
for(std::size_t i = 0; i<2; i++){
c_float tmp = (vec2[i]-vec3[i]);
value = value+tmp*tmp;
}
EXPECT_EQ(value,dot_product_diff<c_float>(vec2,vec3,2));
}
TEST_F(ProjectTest, Test_normalized) {
c_float vec2[2] = {1,2};
EXPECT_FALSE(normalized<c_float>(vec2,2));
c_float vec3[2] = {1,0};
EXPECT_TRUE(normalized<c_float>(vec3,2));
c_float vec4[2] = {1.0/sqrt(2.0),1.0/sqrt(2.0)};
EXPECT_TRUE(normalized<c_float>(vec4,2));
c_float vec5[3] = {1.0/sqrt(3.0),1.0/sqrt(3.0),1.0/sqrt(3.0)};
EXPECT_TRUE(normalized<c_float>(vec5));
}
TEST_F(ProjectTest, Test_normalize) {
c_float vec2[2] = {1,2};
EXPECT_FALSE(normalized<c_float>(vec2,2));
normalize<c_float>(vec2,2);
EXPECT_TRUE(normalized<c_float>(vec2,2));
c_float vec3[3] = {1.0,2.0,3.0};
EXPECT_FALSE(normalized<c_float>(vec3));
normalize<c_float>(vec3);
EXPECT_TRUE(normalized<c_float>(vec3));
}
TEST_F(ProjectTest, Test_distance) {
c_float vec2[2] = {1.0,2.0};
c_float vec3[2] = {2.0,2.0};
EXPECT_EQ(distance<c_float>(vec2,vec3,2),1.0);
EXPECT_LT(distance<c_float>(vec2,vec3,2),2.0);
}
TEST_F(ProjectTest, Test_distance_within) {
c_float vec2[2] = {1.0,2.0};
c_float vec3[2] = {2.0,2.0};
EXPECT_FALSE(distance_within<c_float>(vec2,vec3,2,0.5));
EXPECT_TRUE(distance_within<c_float>(vec2,vec3,2,5.0));
c_float vec4[3] = {1.0,2.0,3.9};
c_float vec5[3] = {2.0,2.0,1.0};
EXPECT_FALSE(distance_within<c_float>(vec4,vec5,2,0.5));
EXPECT_TRUE(distance_within<c_float>(vec4,vec5,2,5.0));
} | 24.738739 | 87 | 0.634013 | [
"vector"
] |
0acb0ec5d5b6fb2f067b870ba3c5225c1749fb7b | 9,672 | cpp | C++ | BlackVision/LibBlackVision/Source/Engine/Models/Gizmos/Logics/BoundingBox/BoundingBoxLogic.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | 1 | 2022-01-28T11:43:47.000Z | 2022-01-28T11:43:47.000Z | BlackVision/LibBlackVision/Source/Engine/Models/Gizmos/Logics/BoundingBox/BoundingBoxLogic.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | BlackVision/LibBlackVision/Source/Engine/Models/Gizmos/Logics/BoundingBox/BoundingBoxLogic.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "BoundingBoxLogic.h"
#include "Engine/Models/BasicNode.h"
#include "Engine/Models/Plugins/Descriptor/ModelHelper.h"
#include "Engine/Events/InnerEvents/Nodes/NodeRemovedEvent.h"
#include "Engine/Events/EventManager.h"
#include "Engine/Models/NodeLogics/NodeLogicHelper.h"
#include "Engine/Models/ModelState.h"
#include "Engine/Editors/BVProjectEditor.h"
namespace bv {
namespace nodelogic
{
const std::string BoundingBoxLogic::m_type = "BoundingBoxLogic";
const std::string BoundingBoxLogic::PARAMETERS::BOX_COLOR = "BoxColor";
const std::string BoundingBoxLogic::PARAMETERS::CENTER_COLOR = "CenterColor";
const std::string BoundingBoxLogic::PARAMETERS::CENTER_SIZE = "CenterSize";
const std::string BoundingBoxLogic::PARAMETERS::INCLUDE_CHILDREN = "IncludeChildren";
// ***********************
//
const std::string & BoundingBoxLogic::Type ()
{
return m_type;
}
// ***********************
//
const std::string & BoundingBoxLogic::GetType () const
{
return Type();
}
// ***********************
//
BoundingBoxLogic::BoundingBoxLogic ( model::BasicNodeWeakPtr gizmoRoot, model::BasicNodeWeakPtr gizmoOwner, model::ITimeEvaluatorPtr timeEvaluator )
: GizmoLogicBase( gizmoRoot, gizmoOwner )
{
model::ModelHelper h( timeEvaluator );
h.SetOrCreatePluginModel();
h.AddSimpleParam( PARAMETERS::CENTER_COLOR, glm::vec4( 1.0, 0.0, 0.0, 1.0 ), true, true );
h.AddSimpleParam( PARAMETERS::BOX_COLOR, glm::vec4( 0.0, 1.0, 0.0, 1.0 ), true, true );
h.AddSimpleParam( PARAMETERS::CENTER_SIZE, 3.0f, true, true );
h.AddSimpleParam( PARAMETERS::INCLUDE_CHILDREN, true, true, true );
m_paramValModel = std::static_pointer_cast< model::DefaultParamValModel >( h.GetModel()->GetPluginModel() );
m_boxColor = model::GetValueParamState< glm::vec4 >( m_paramValModel.get(), PARAMETERS::BOX_COLOR );
m_centerColor = model::GetValueParamState< glm::vec4 >( m_paramValModel.get(), PARAMETERS::CENTER_COLOR );
m_centerSize = model::GetValueParamState< float >( m_paramValModel.get(), PARAMETERS::CENTER_SIZE );
m_includeChildren = model::GetValueParamState< bool >( m_paramValModel.get(), PARAMETERS::INCLUDE_CHILDREN );
}
// ***********************
//
BoundingBoxLogic::~BoundingBoxLogic()
{}
// ***********************
//
model::IGizmoLogicPtr BoundingBoxLogic::Create( model::BasicNodeWeakPtr gizmoRoot, model::BasicNodeWeakPtr gizmoOwner, model::ITimeEvaluatorPtr timeEvaluator )
{
return std::make_shared< BoundingBoxLogic >( gizmoRoot, gizmoOwner, timeEvaluator );
}
// ***********************
//
void BoundingBoxLogic::Initialize ()
{
GetDefaultEventManager().AddListener( fastdelegate::MakeDelegate( this, &BoundingBoxLogic::NodeRemovedHandler ), NodeRemovedEvent::Type() );
}
// ***********************
//
void BoundingBoxLogic::Deinitialize ()
{
GetDefaultEventManager().RemoveListener( fastdelegate::MakeDelegate( this, &BoundingBoxLogic::NodeRemovedHandler ), NodeRemovedEvent::Type() );
}
// ***********************
//
void BoundingBoxLogic::Update ( TimeType t )
{
GizmoLogicBase::Update( t );
if( m_centerSize.Changed() )
SetCenterSize( m_centerNode.lock(), m_centerSize.GetValue() );
if( m_centerColor.Changed() )
SetColor( m_centerNode.lock(), m_centerColor.GetValue() );
if( m_boxColor.Changed() )
SetColor( m_bbNode.lock(), m_boxColor.GetValue() );
}
// ***********************
//
void BoundingBoxLogic::PostOwnerUpdate ( TimeType )
{
if( auto ownerNode = m_gizmoOwner.lock() )
{
if( NeedsBoxUpdate( ownerNode ) )
UpdateBox();
if( NeedsCenterUpdate( ownerNode ) )
UpdateCenter();
}
}
// ========================================================================= //
// Gizmo subtree creation
// ========================================================================= //
// ***********************
//
void BoundingBoxLogic::CreateGizmoSubtree ( BVProjectEditor * editor )
{
if( auto gizmoOwner = m_gizmoOwner.lock() )
{
auto gizmoRoot = m_gizmoRoot.lock();
auto scene = editor->GetModelScene( model::ModelState::GetInstance().QueryNodeScene( gizmoOwner.get() )->GetName() );
auto timeEvaluator = m_centerColor.GetParameter().GetTimeEvaluator();
model::BasicNodePtr boxNode = model::BasicNode::Create( "box" );
model::BasicNodePtr centerNode = model::BasicNode::Create( "center" );
m_centerNode = centerNode;
m_bbNode = boxNode;
centerNode->AddPlugin( "DEFAULT_TRANSFORM", timeEvaluator );
centerNode->AddPlugin( "DEFAULT_COLOR", timeEvaluator );
centerNode->AddPlugin( "CENTER_PLUGIN", timeEvaluator );
SetColor( centerNode, m_centerColor.GetValue() );
SetCenterSize( centerNode, m_centerSize.GetValue() );
if( NeedsCenterUpdate( gizmoOwner ) )
UpdateCenter();
boxNode->AddPlugin( "DEFAULT_TRANSFORM", timeEvaluator );
boxNode->AddPlugin( "DEFAULT_COLOR", timeEvaluator );
boxNode->AddPlugin( "BOUNDING_BOX_PLUGIN", timeEvaluator );
UpdateBox();
editor->AddChildNode( scene, gizmoRoot, centerNode, false );
editor->AddChildNode( scene, gizmoRoot, boxNode, false );
// If someone wants to set parameters directly after this function, changes will be visible in next update. Otherwise not.
m_paramValModel->Update();
}
}
// ***********************
//
void BoundingBoxLogic::SetTranslation ( model::BasicNodePtr node, const glm::vec3 & transform, TimeType time )
{
auto nodeTransform = node->GetFinalizePlugin()->GetParamTransform();
nodeTransform->SetTranslation( transform, time );
}
// ***********************
//
void BoundingBoxLogic::SetColor ( model::BasicNodePtr node, const glm::vec4 & color, TimeType time )
{
auto colorPlugin = node->GetPlugin( "solid color" );
auto colorParam = model::QueryTypedParam< model::ParamVec4Ptr >( colorPlugin->GetParameter( "color" ) );
colorParam->SetVal( color, time );
}
// ***********************
//
void BoundingBoxLogic::SetCenterSize ( model::BasicNodePtr node, float size, TimeType time )
{
auto centerPlugin = node->GetPlugin( "center" );
auto sizeParam = model::QueryTypedParam< model::ParamFloatPtr >( centerPlugin->GetParameter( "size" ) );
sizeParam->SetVal( size, time );
}
// ***********************
//
void BoundingBoxLogic::SetBoxSize ( model::BasicNodePtr node, const glm::vec3 & size, TimeType time )
{
auto boxPlugin = node->GetPlugin( "bounding box" );
auto sizeParam = model::QueryTypedParam< model::ParamVec3Ptr >( boxPlugin->GetParameter( "size" ) );
sizeParam->SetVal( size, time );
}
// ***********************
//
BoundingBoxLogic::BoxInfo BoundingBoxLogic::ComputeBox ( model::BasicNodePtr node, bool includeChildren )
{
auto boundingVolume = node->GetBoundingVolume();
if( boundingVolume )
{
BoxInfo info;
const mathematics::Box * box = includeChildren ? boundingVolume->GetChildrenBox() : boundingVolume->GetBoundingBox();
info.Center = box->Center();
info.Size.x = box->Width();
info.Size.y = box->Height();
info.Size.z = box->Depth();
return info;
}
return BoxInfo();
}
// ***********************
//
bool BoundingBoxLogic::NeedsBoxUpdate ( model::BasicNodePtr node )
{
if( m_includeChildren.Changed() )
return true;
auto boundingVolume = node->GetBoundingVolume();
if( boundingVolume )
return boundingVolume->IsUpdated();
return false;
}
// ***********************
//
bool BoundingBoxLogic::NeedsCenterUpdate ( model::BasicNodePtr node )
{
auto transformParam = node->GetFinalizePlugin()->GetParamTransform();
auto center = transformParam->Transform().GetCenter( transformParam->GetLocalEvaluationTime() );
if( m_lastCenter != center )
{
m_lastCenter = center;
return true;
}
return false;
}
// ***********************
//
void BoundingBoxLogic::UpdateBox ()
{
BoxInfo info = ComputeBox( m_gizmoOwner.lock(), m_includeChildren.GetValue() );
auto boxNode = m_bbNode.lock();
SetColor( boxNode, m_boxColor.GetValue() );
SetBoxSize( boxNode, info.Size );
SetTranslation( boxNode, info.Center );
}
// ***********************
//
void BoundingBoxLogic::UpdateCenter ()
{
// m_lastCenter is already updated.
auto centerNode = m_centerNode.lock();
SetTranslation( centerNode, m_lastCenter );
}
// ========================================================================= //
// Handling removing of nodes
// ========================================================================= //
// ***********************
//
void BoundingBoxLogic::NodeRemovedHandler ( IEventPtr evt )
{
if( evt->GetEventType() != NodeRemovedEvent::Type() )
return;
}
} // nodelogic
} // bv
| 33.237113 | 166 | 0.580749 | [
"model",
"transform",
"solid"
] |
bd62112d40c630882cbda6dd18c3021e0fe9060b | 5,530 | cc | C++ | gazebo/gui/model/ModelEditor_TEST.cc | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 887 | 2020-04-18T08:43:06.000Z | 2022-03-31T11:58:50.000Z | gazebo/gui/model/ModelEditor_TEST.cc | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 462 | 2020-04-21T21:59:19.000Z | 2022-03-31T23:23:21.000Z | gazebo/gui/model/ModelEditor_TEST.cc | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 421 | 2020-04-21T09:13:03.000Z | 2022-03-30T02:22:01.000Z | /*
* Copyright (C) 2015 Open Source Robotics Foundation
*
* 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 "gazebo/gui/MainWindow.hh"
#include "gazebo/gui/Actions.hh"
#include "gazebo/gui/model/ModelEditor.hh"
#include "gazebo/gui/model/ModelEditor_TEST.hh"
using namespace gazebo;
/////////////////////////////////////////////////
void ModelEditor_TEST::AddItemToPalette()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world");
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// verify we have a model editor widget
gui::ModelEditor *modelEditor =
dynamic_cast<gui::ModelEditor *>(mainWindow->Editor("model"));
QVERIFY(modelEditor);
// add a custom push button to the model editor palette
QPushButton *testButton = new QPushButton("TEST_BUTTON");
testButton->setObjectName("my_custom_test_button");
modelEditor->AddItemToPalette(testButton, "test_categorty");
QPushButton *retButton =
mainWindow->findChild<QPushButton *>("my_custom_test_button");
// verify that the push button is added.
QVERIFY(retButton);
QVERIFY(retButton->text().toStdString() == "TEST_BUTTON");
mainWindow->close();
delete mainWindow;
mainWindow = NULL;
}
/////////////////////////////////////////////////
void ModelEditor_TEST::OnEdit()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world");
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// verify we have a model editor widget
gui::ModelEditor *modelEditor =
dynamic_cast<gui::ModelEditor *>(mainWindow->Editor("model"));
QVERIFY(modelEditor);
QVERIFY(gui::g_editModelAct != NULL);
// verify simulation is not paused
QVERIFY(!mainWindow->IsPaused());
// switch to editor mode
gui::g_editModelAct->toggle();
// wait for the gui paused state to update
int maxSleep = 50;
int sleep = 0;
while (!mainWindow->IsPaused() && sleep < maxSleep)
{
QCoreApplication::processEvents();
QTest::qWait(50);
sleep++;
}
QVERIFY(sleep < maxSleep);
// verify simulation is paused
QVERIFY(mainWindow->IsPaused());
// swtich back to simulation mode
gui::g_editModelAct->toggle();
// check the gui paused state and it should not change
maxSleep = 50;
sleep = 0;
while (mainWindow->IsPaused() && sleep < maxSleep)
{
QCoreApplication::processEvents();
QTest::qWait(50);
sleep++;
}
QVERIFY(sleep == maxSleep);
// verify simulation is still paused
QVERIFY(mainWindow->IsPaused());
// run the simulation
mainWindow->Play();
// wait for the gui paused state to update
maxSleep = 50;
sleep = 0;
while (mainWindow->IsPaused() && sleep < maxSleep)
{
QCoreApplication::processEvents();
QTest::qWait(50);
sleep++;
}
QVERIFY(sleep < maxSleep);
// verify simulation is now running
QVERIFY(!mainWindow->IsPaused());
mainWindow->close();
delete mainWindow;
mainWindow = NULL;
}
/////////////////////////////////////////////////
void ModelEditor_TEST::InsertTab()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world");
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Get the main tab
auto mainTab = mainWindow->findChild<QTabWidget *>("mainTab");
QVERIFY(mainTab != NULL);
// Get the insert tab
QWidget *insertModel = NULL;
for (int i = 0; i < mainTab->count(); ++i)
{
if (mainTab->tabText(i) == tr("Insert"))
{
insertModel = mainTab->widget(i);
break;
}
}
QVERIFY(insertModel != NULL);
// Switch to editor mode
QVERIFY(gui::g_editModelAct != NULL);
gui::g_editModelAct->toggle();
// Check that the insert tab is not in mainTab anymore
insertModel = NULL;
for (int i = 0; i < mainTab->count(); ++i)
{
if (mainTab->tabText(i) == tr("Insert"))
{
insertModel = mainTab->widget(i);
break;
}
}
QVERIFY(insertModel == NULL);
// Switch back to simulation
gui::g_editModelAct->toggle();
// Check that the insert tab in mainTab again
insertModel = NULL;
for (int i = 0; i < mainTab->count(); ++i)
{
if (mainTab->tabText(i) == tr("Insert"))
{
insertModel = mainTab->widget(i);
break;
}
}
QVERIFY(insertModel != NULL);
mainWindow->close();
delete mainWindow;
mainWindow = NULL;
}
// Generate a main function for the test
QTEST_MAIN(ModelEditor_TEST)
| 25.251142 | 75 | 0.660759 | [
"model"
] |
bd69e3a812dd317c925a4cad7e42c0c094e267e3 | 2,097 | cpp | C++ | core/src/graphics/model.cpp | dsparrow27/spike | dc93f0376d7b9ef983e6325a1d89877638409425 | [
"MIT"
] | null | null | null | core/src/graphics/model.cpp | dsparrow27/spike | dc93f0376d7b9ef983e6325a1d89877638409425 | [
"MIT"
] | null | null | null | core/src/graphics/model.cpp | dsparrow27/spike | dc93f0376d7b9ef983e6325a1d89877638409425 | [
"MIT"
] | null | null | null | #include "model.h"
Model::Model(std::string const & path, bool gamma)
:mDirectory(path), mGammaCorrection(gamma)
{
loadModel(path);
}
void Model::draw()
{
//call draw function for each mesh
for (GLuint i = 0; i < this->mMeshes.size(); i++)
{
this->mMeshes[i].draw();
}
}
void Model::loadModel(std::string path)
{
// read the model file using assimp
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
// check for import error
if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
std::cout << "Error:: ASSIMP:: " << importer.GetErrorString() << std::endl;
return;
}
// retrieve the path of the file
this->mDirectory = path.substr(0, path.find_last_of("/"));
//process root node recursively
this->processNode(scene->mRootNode, scene);
}
void Model::processNode(aiNode* node, const aiScene* scene)
{
// process each mesh located at the current node
for (GLuint i = 0; i < node->mNumMeshes; i++)
{
// the node object only contains indices to index the actual object in the scene.
//the scene contains all the data, node is just to key things organized
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
this->mMeshes.push_back(this->processMesh(mesh, scene));
}
// after we've process all the meshes we then recursively process each child
for (GLuint i = 0; i < node->mNumChildren; i++)
{
this->processNode(node->mChildren[i], scene);
}
}
Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene)
{
std::vector<Vertex> vertices;
std::vector<GLuint> indices;
for (GLuint i = 0; i < mesh->mNumVertices; i++)
{
Vertex vertex;
//positions
vertex.position = Vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
vertices.push_back(vertex);
}
//retrive the vertice indices for each face
for (GLuint i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (GLuint j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j]);
}
}
return Mesh(vertices, indices);
} | 27.96 | 120 | 0.688126 | [
"mesh",
"object",
"vector",
"model"
] |
bd6ba46bb7333263b14b2c8ab8a58587e15a5dbb | 4,309 | hpp | C++ | lib/vector.hpp | bilyanhadzhi/susi | 92ae0e30fe67b544f75fc3581b292ea87f4f078c | [
"MIT"
] | 1 | 2021-03-01T14:14:56.000Z | 2021-03-01T14:14:56.000Z | lib/vector.hpp | bilyanhadzhi/susi | 92ae0e30fe67b544f75fc3581b292ea87f4f078c | [
"MIT"
] | null | null | null | lib/vector.hpp | bilyanhadzhi/susi | 92ae0e30fe67b544f75fc3581b292ea87f4f078c | [
"MIT"
] | null | null | null | #ifndef VECTOR_HPP
#define VECTOR_HPP
#include "../constants.hpp"
#include <cassert>
#include <iostream>
//! A dynamic array of dynamic elements
template<typename T>
class Vector
{
private:
// An array of pointers to T, all 'empty' slots will be nullptr by default
T** elements;
int elements_count;
int elements_capacity;
void copy_from(const Vector<T>& other);
void free_memory();
void increase_capacity();
void init_vector();
// Shift all elements, starting from the i-th, one index to the left
void shift_left_from(int i);
public:
Vector();
Vector(const Vector& other);
Vector<T>& operator=(const Vector& other);
~Vector();
//! Restore vector to initial state
void empty_vector();
//! Add element at the end of the vector
void push(T value);
//! Remove element at index i and shift others left
void remove(int i);
//! Get the (semantical) length of the vector
int get_len() const;
//! Get value of element at i-th index
T& operator[](int i) const;
//! Return index of first occurrence
int get_first_occurrence(T elem) const;
};
template<typename T>
void Vector<T>::free_memory()
{
for (int i = 0; i < this->elements_capacity; ++i)
{
if (this->elements[i] != nullptr)
{
delete this->elements[i];
this->elements[i] = nullptr;
}
}
if (this->elements != nullptr)
{
delete[] this->elements;
this->elements = nullptr;
}
}
template<typename T>
void Vector<T>::copy_from(const Vector<T>& other)
{
T** new_elements = new T*[other.elements_capacity]();
for (int i = 0; i < other.elements_count; ++i)
{
new_elements[i] = new T(*(other.elements[i]));
}
this->elements_capacity = other.elements_capacity;
this->elements_count = other.elements_count;
this->elements = new_elements;
}
template<typename T>
Vector<T>::Vector()
{
this->init_vector();
}
template<typename T>
void Vector<T>::init_vector()
{
this->elements_capacity = VECTOR_DEFAULT_CAPACITY;
this->elements = new T*[this->elements_capacity]();
for (int i = 0; i < this->elements_capacity; ++i)
{
this->elements[i] = nullptr;
}
this->elements_count = 0;
}
template<typename T>
Vector<T>::Vector(const Vector& other)
{
this->copy_from(other);
}
template<typename T>
Vector<T>& Vector<T>::operator=(const Vector& other)
{
if (this == &other)
{
return *this;
}
this->free_memory();
this->copy_from(other);
return *this;
}
template<typename T>
Vector<T>::~Vector()
{
this->free_memory();
}
template<typename T>
void Vector<T>::increase_capacity()
{
T** new_elements = new T*[this->elements_capacity * 2]();
for (int i = 0; i < this->elements_count; ++i)
{
new_elements[i] = new T(*(this->elements[i]));
}
this->free_memory();
this->elements_capacity *= 2;
this->elements = new_elements;
}
template<typename T>
void Vector<T>::push(T value)
{
if (this->elements_count + 1 >= this->elements_capacity)
{
this->increase_capacity();
}
this->elements[this->elements_count++] = new T(value);
}
template<typename T>
int Vector<T>::get_len() const
{
return this->elements_count;
}
template<typename T>
T& Vector<T>::operator[](int i) const
{
assert(i >= 0 && i < this->elements_count);
return *(this->elements[i]);
}
template<typename T>
void Vector<T>::empty_vector()
{
this->free_memory();
this->init_vector();
}
template<typename T>
int Vector<T>::get_first_occurrence(T elem) const
{
for (int i = 0; i < this->elements_count; ++i)
{
if (*this->elements[i] == elem)
{
return i;
}
}
return -1;
}
template<typename T>
void Vector<T>::shift_left_from(int i)
{
for (i; i < this->elements_count - 1; ++i)
{
this->elements[i] = this->elements[i + 1];
}
}
template<typename T>
void Vector<T>::remove(int i)
{
if (this->elements_count < 1)
{
return;
}
assert(i >= 0 && i < this->elements_count);
delete this->elements[i];
this->shift_left_from(i);
this->elements[this->elements_count - 1] = nullptr;
--this->elements_count;
}
#endif // VECTOR_HPP
| 20.421801 | 78 | 0.616616 | [
"vector"
] |
bd6f09b240c25d4663fed78d7a8621e241638119 | 10,549 | cc | C++ | market/src/model/DescribeProductResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | market/src/model/DescribeProductResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | market/src/model/DescribeProductResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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 <alibabacloud/market/model/DescribeProductResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Market;
using namespace AlibabaCloud::Market::Model;
DescribeProductResult::DescribeProductResult() :
ServiceResult()
{}
DescribeProductResult::DescribeProductResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeProductResult::~DescribeProductResult()
{}
void DescribeProductResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allProductSkusNode = value["ProductSkus"]["ProductSku"];
for (auto valueProductSkusProductSku : allProductSkusNode)
{
ProductSku productSkusObject;
if(!valueProductSkusProductSku["Name"].isNull())
productSkusObject.name = valueProductSkusProductSku["Name"].asString();
if(!valueProductSkusProductSku["Code"].isNull())
productSkusObject.code = valueProductSkusProductSku["Code"].asString();
if(!valueProductSkusProductSku["ChargeType"].isNull())
productSkusObject.chargeType = valueProductSkusProductSku["ChargeType"].asString();
if(!valueProductSkusProductSku["Constraints"].isNull())
productSkusObject.constraints = valueProductSkusProductSku["Constraints"].asString();
if(!valueProductSkusProductSku["Hidden"].isNull())
productSkusObject.hidden = valueProductSkusProductSku["Hidden"].asString() == "true";
auto allOrderPeriodsNode = allProductSkusNode["OrderPeriods"]["OrderPeriod"];
for (auto allProductSkusNodeOrderPeriodsOrderPeriod : allOrderPeriodsNode)
{
ProductSku::OrderPeriod orderPeriodsObject;
if(!allProductSkusNodeOrderPeriodsOrderPeriod["Name"].isNull())
orderPeriodsObject.name = allProductSkusNodeOrderPeriodsOrderPeriod["Name"].asString();
if(!allProductSkusNodeOrderPeriodsOrderPeriod["PeriodType"].isNull())
orderPeriodsObject.periodType = allProductSkusNodeOrderPeriodsOrderPeriod["PeriodType"].asString();
productSkusObject.orderPeriods.push_back(orderPeriodsObject);
}
auto allModulesNode = allProductSkusNode["Modules"]["Module"];
for (auto allProductSkusNodeModulesModule : allModulesNode)
{
ProductSku::Module modulesObject;
if(!allProductSkusNodeModulesModule["Id"].isNull())
modulesObject.id = allProductSkusNodeModulesModule["Id"].asString();
if(!allProductSkusNodeModulesModule["Name"].isNull())
modulesObject.name = allProductSkusNodeModulesModule["Name"].asString();
if(!allProductSkusNodeModulesModule["Code"].isNull())
modulesObject.code = allProductSkusNodeModulesModule["Code"].asString();
auto allPropertiesNode = allModulesNode["Properties"]["Property"];
for (auto allModulesNodePropertiesProperty : allPropertiesNode)
{
ProductSku::Module::Property propertiesObject;
if(!allModulesNodePropertiesProperty["Name"].isNull())
propertiesObject.name = allModulesNodePropertiesProperty["Name"].asString();
if(!allModulesNodePropertiesProperty["Key"].isNull())
propertiesObject.key = allModulesNodePropertiesProperty["Key"].asString();
if(!allModulesNodePropertiesProperty["ShowType"].isNull())
propertiesObject.showType = allModulesNodePropertiesProperty["ShowType"].asString();
if(!allModulesNodePropertiesProperty["DisplayUnit"].isNull())
propertiesObject.displayUnit = allModulesNodePropertiesProperty["DisplayUnit"].asString();
auto allPropertyValuesNode = allPropertiesNode["PropertyValues"]["PropertyValue"];
for (auto allPropertiesNodePropertyValuesPropertyValue : allPropertyValuesNode)
{
ProductSku::Module::Property::PropertyValue propertyValuesObject;
if(!allPropertiesNodePropertyValuesPropertyValue["Value"].isNull())
propertyValuesObject.value = allPropertiesNodePropertyValuesPropertyValue["Value"].asString();
if(!allPropertiesNodePropertyValuesPropertyValue["DisplayName"].isNull())
propertyValuesObject.displayName = allPropertiesNodePropertyValuesPropertyValue["DisplayName"].asString();
if(!allPropertiesNodePropertyValuesPropertyValue["Type"].isNull())
propertyValuesObject.type = allPropertiesNodePropertyValuesPropertyValue["Type"].asString();
if(!allPropertiesNodePropertyValuesPropertyValue["Min"].isNull())
propertyValuesObject.min = allPropertiesNodePropertyValuesPropertyValue["Min"].asString();
if(!allPropertiesNodePropertyValuesPropertyValue["Max"].isNull())
propertyValuesObject.max = allPropertiesNodePropertyValuesPropertyValue["Max"].asString();
if(!allPropertiesNodePropertyValuesPropertyValue["Step"].isNull())
propertyValuesObject.step = allPropertiesNodePropertyValuesPropertyValue["Step"].asString();
if(!allPropertiesNodePropertyValuesPropertyValue["Remark"].isNull())
propertyValuesObject.remark = allPropertiesNodePropertyValuesPropertyValue["Remark"].asString();
propertiesObject.propertyValues.push_back(propertyValuesObject);
}
modulesObject.properties.push_back(propertiesObject);
}
productSkusObject.modules.push_back(modulesObject);
}
productSkus_.push_back(productSkusObject);
}
auto allProductExtrasNode = value["ProductExtras"]["ProductExtra"];
for (auto valueProductExtrasProductExtra : allProductExtrasNode)
{
ProductExtra productExtrasObject;
if(!valueProductExtrasProductExtra["Key"].isNull())
productExtrasObject.key = valueProductExtrasProductExtra["Key"].asString();
if(!valueProductExtrasProductExtra["Values"].isNull())
productExtrasObject.values = valueProductExtrasProductExtra["Values"].asString();
if(!valueProductExtrasProductExtra["Label"].isNull())
productExtrasObject.label = valueProductExtrasProductExtra["Label"].asString();
if(!valueProductExtrasProductExtra["Order"].isNull())
productExtrasObject.order = std::stoi(valueProductExtrasProductExtra["Order"].asString());
if(!valueProductExtrasProductExtra["Type"].isNull())
productExtrasObject.type = valueProductExtrasProductExtra["Type"].asString();
productExtras_.push_back(productExtrasObject);
}
auto shopInfoNode = value["ShopInfo"];
if(!shopInfoNode["Id"].isNull())
shopInfo_.id = std::stol(shopInfoNode["Id"].asString());
if(!shopInfoNode["Name"].isNull())
shopInfo_.name = shopInfoNode["Name"].asString();
if(!shopInfoNode["Emails"].isNull())
shopInfo_.emails = shopInfoNode["Emails"].asString();
auto allWangWangsNode = shopInfoNode["WangWangs"]["WangWang"];
for (auto shopInfoNodeWangWangsWangWang : allWangWangsNode)
{
ShopInfo::WangWang wangWangObject;
if(!shopInfoNodeWangWangsWangWang["UserName"].isNull())
wangWangObject.userName = shopInfoNodeWangWangsWangWang["UserName"].asString();
if(!shopInfoNodeWangWangsWangWang["Remark"].isNull())
wangWangObject.remark = shopInfoNodeWangWangsWangWang["Remark"].asString();
shopInfo_.wangWangs.push_back(wangWangObject);
}
auto allTelephones = shopInfoNode["Telephones"]["Telephone"];
for (auto value : allTelephones)
shopInfo_.telephones.push_back(value.asString());
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Name"].isNull())
name_ = value["Name"].asString();
if(!value["Type"].isNull())
type_ = value["Type"].asString();
if(!value["PicUrl"].isNull())
picUrl_ = value["PicUrl"].asString();
if(!value["Description"].isNull())
description_ = value["Description"].asString();
if(!value["ShortDescription"].isNull())
shortDescription_ = value["ShortDescription"].asString();
if(!value["UseCount"].isNull())
useCount_ = std::stol(value["UseCount"].asString());
if(!value["Score"].isNull())
score_ = std::stof(value["Score"].asString());
if(!value["Status"].isNull())
status_ = value["Status"].asString();
if(!value["AuditStatus"].isNull())
auditStatus_ = value["AuditStatus"].asString();
if(!value["AuditFailMsg"].isNull())
auditFailMsg_ = value["AuditFailMsg"].asString();
if(!value["AuditTime"].isNull())
auditTime_ = std::stol(value["AuditTime"].asString());
if(!value["GmtCreated"].isNull())
gmtCreated_ = std::stol(value["GmtCreated"].asString());
if(!value["GmtModified"].isNull())
gmtModified_ = std::stol(value["GmtModified"].asString());
if(!value["SupplierPk"].isNull())
supplierPk_ = std::stol(value["SupplierPk"].asString());
if(!value["FrontCategoryId"].isNull())
frontCategoryId_ = std::stol(value["FrontCategoryId"].asString());
}
std::string DescribeProductResult::getStatus()const
{
return status_;
}
long DescribeProductResult::getFrontCategoryId()const
{
return frontCategoryId_;
}
std::string DescribeProductResult::getDescription()const
{
return description_;
}
DescribeProductResult::ShopInfo DescribeProductResult::getShopInfo()const
{
return shopInfo_;
}
std::vector<DescribeProductResult::ProductSku> DescribeProductResult::getProductSkus()const
{
return productSkus_;
}
long DescribeProductResult::getUseCount()const
{
return useCount_;
}
long DescribeProductResult::getGmtModified()const
{
return gmtModified_;
}
long DescribeProductResult::getGmtCreated()const
{
return gmtCreated_;
}
std::string DescribeProductResult::getCode()const
{
return code_;
}
std::string DescribeProductResult::getName()const
{
return name_;
}
std::string DescribeProductResult::getShortDescription()const
{
return shortDescription_;
}
long DescribeProductResult::getSupplierPk()const
{
return supplierPk_;
}
std::string DescribeProductResult::getType()const
{
return type_;
}
float DescribeProductResult::getScore()const
{
return score_;
}
std::string DescribeProductResult::getAuditStatus()const
{
return auditStatus_;
}
std::string DescribeProductResult::getAuditFailMsg()const
{
return auditFailMsg_;
}
std::vector<DescribeProductResult::ProductExtra> DescribeProductResult::getProductExtras()const
{
return productExtras_;
}
long DescribeProductResult::getAuditTime()const
{
return auditTime_;
}
std::string DescribeProductResult::getPicUrl()const
{
return picUrl_;
}
| 37.675 | 112 | 0.768698 | [
"vector",
"model"
] |
bd719cda58cb216cc687fe05267958810c78aeae | 1,594 | cpp | C++ | Game/Scripts/task_system/drones/GoToBehaviour.cpp | JohnHonkanen/ProjectM | 881171ad749e8fe7db6188ee9486239a37256569 | [
"Unlicense"
] | null | null | null | Game/Scripts/task_system/drones/GoToBehaviour.cpp | JohnHonkanen/ProjectM | 881171ad749e8fe7db6188ee9486239a37256569 | [
"Unlicense"
] | null | null | null | Game/Scripts/task_system/drones/GoToBehaviour.cpp | JohnHonkanen/ProjectM | 881171ad749e8fe7db6188ee9486239a37256569 | [
"Unlicense"
] | null | null | null | #include "GoToBehaviour.h"
#include "DroneController.h"
#include "../../Drone.h"
#include "../Task.h"
#include "CollectBehaviour.h"
#include "DeliverBehaviour.h"
namespace v1
{
namespace TaskSystem {
bool GoToBehaviour::Run(double dt)
{
Drone *drone = info.controller->GetDrone();
Task task = info.controller->GetTask();
vec3 position = drone->transform->GetPosition();
float baseSpeed = info.controller->GetBaseSpeed();
float speedMod = info.controller->GetSpeedMod();
position.y = 0;
//Determmine Destination
vec3 destination = info.to;
destination.y = 0;
//Check if We have reached target
if (distance(position, destination) < 2.0f)
{
//Target Reached
return true;
}
//Move to Target
//Rotate our drone to orient destination
vec3 dir = normalize(destination - position);
float angle = atan2(dir.x, dir.z);
vec3 droneAngle = drone->transform->GetRotation();
droneAngle.y = degrees(angle) - 90.0f;
drone->transform->SetEulerAngle(droneAngle);
//Move to Target
drone->transform->Translate(dir * (baseSpeed * speedMod) * float(dt / 1000.0f));
return false;
}
void GoToBehaviour::Next()
{
Task task = info.controller->GetTask();
if (task.GetType() == TASK_TYPE::COLLECT || task.GetType() == TASK_TYPE::REQUEST)
{
AbstractDroneBehaviour * state;
if (!info.finalStep)
{
state = new CollectBehaviour();
}
else {
state = new DeliverBehaviour();
}
state->info = info;
info.controller->SetState(state);
}
delete this;
}
}
}
| 22.138889 | 84 | 0.647428 | [
"transform"
] |
bd730b3a911a61dadb240f977fa9f1243a2cbced | 3,649 | hpp | C++ | include/pcp/common/points/vertex.hpp | Q-Minh/octree | 0c3fd5a791d660b37461daf968a68ffb1c80b965 | [
"BSL-1.0"
] | 2 | 2021-03-10T09:57:45.000Z | 2021-04-13T21:19:57.000Z | include/pcp/common/points/vertex.hpp | Q-Minh/octree | 0c3fd5a791d660b37461daf968a68ffb1c80b965 | [
"BSL-1.0"
] | 22 | 2020-12-07T20:09:39.000Z | 2021-04-12T20:42:59.000Z | include/pcp/common/points/vertex.hpp | Q-Minh/octree | 0c3fd5a791d660b37461daf968a68ffb1c80b965 | [
"BSL-1.0"
] | null | null | null | #ifndef PCP_COMMON_POINTS_VERTEX_HPP
#define PCP_COMMON_POINTS_VERTEX_HPP
/**
* @file
* @ingroup common
*/
#include "pcp/traits/graph_vertex_traits.hpp"
#include "pcp/traits/point_traits.hpp"
#include "point.hpp"
#include "point_view.hpp"
#include <cstdint>
namespace pcp {
/**
* @ingroup geometric-primitives
* @brief
* The basic_point_view_vertex_t type is a basic_point_view_t. It does not
* hold ownership over the underlying point. It stores an
* identifier, and exposes it through id() and id(id_type).
* basic_point_view_vertex_t should satify the GraphVertex concept.
* Use this type as an adaptor to points so that they are
* useable in graph algorithms without copying.
* @tparam PointView Type satisfying PointView concept
*/
template <class PointView>
class basic_point_view_vertex_t : public basic_point_view_t<PointView>
{
public:
using id_type = std::uint64_t;
using self_type = basic_point_view_vertex_t<PointView>;
using point_type = basic_point_view_t<PointView>;
using parent_type = point_type;
id_type id() const { return id_; }
void id(id_type value) { id_ = value; }
basic_point_view_vertex_t() = default;
basic_point_view_vertex_t(self_type const&) = default;
basic_point_view_vertex_t(self_type&&) = default;
self_type& operator=(self_type const&) = default;
self_type& operator=(self_type&&) = default;
explicit basic_point_view_vertex_t(PointView* point) : parent_type(point), id_(0u) {}
explicit basic_point_view_vertex_t(id_type id) : parent_type(), id_(id) {}
explicit basic_point_view_vertex_t(PointView* point, id_type id) : parent_type(point), id_(id)
{
}
basic_point_view_vertex_t(point_type const& other) : parent_type(&other), id_(0u) {}
/**
* @brief
* Construct from another GraphVertex type. This
* constructor copies only the id from the copied-from
* object.
* @tparam GraphVertex Type satisfying GraphVertex
* @param other GraphVertex to copy from
*/
template <class GraphVertex>
basic_point_view_vertex_t(GraphVertex const& other) : parent_type(), id_(other.id())
{
static_assert(
traits::is_graph_vertex_v<GraphVertex>,
"other must satisfy GraphVertex concept");
}
/**
* @brief
* Assigns id of other GraphVertex to this basic_point_view_vertex_t.
* If other is also a PointView, also assign x,y,z coordinates.
* @tparam GraphVertex Type satisfying GraphVertex concept
* @param other GraphVertex to assign from
* @return
*/
template <class GraphVertex>
self_type& operator=(GraphVertex const& other)
{
static_assert(
traits::is_graph_vertex_v<GraphVertex>,
"GraphVertex must satisfy GraphVertex concept");
id(other.id());
if constexpr (traits::is_point_view_v<GraphVertex>)
{
x(other.x());
y(other.y());
z(other.z());
}
return *this;
}
/**
* @brief Equality comparison based on identifier
* @param other
* @return
*/
bool operator==(self_type const& other) const { return id_ == other.id_; }
/**
* @brief Inequality comparison based on identifier
* @param other
* @return
*/
bool operator!=(self_type const& other) const { return id_ != other.id_; }
private:
id_type id_ = 0u;
};
/**
* @ingroup geometric-primitives
* @brief
* Default vertex type
*/
using vertex_t = basic_point_view_vertex_t<pcp::point_t>;
} // namespace pcp
#endif // PCP_COMMON_POINTS_VERTEX_HPP | 30.157025 | 98 | 0.675802 | [
"object"
] |
bd74a8516c94a0ac836d13e07cd1f8a64f47c8cc | 5,580 | cpp | C++ | libs/numeric/mtl/test/strided_vector_ref_test.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 24 | 2019-03-26T15:25:45.000Z | 2022-03-26T10:00:45.000Z | libs/numeric/mtl/test/strided_vector_ref_test.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 2 | 2020-04-17T12:35:32.000Z | 2021-03-03T15:46:25.000Z | libs/numeric/mtl/test/strided_vector_ref_test.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 10 | 2019-12-01T13:40:30.000Z | 2022-01-14T08:39:54.000Z | // Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
// 2008 Dresden University of Technology and the Trustees of Indiana University.
// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.
#include <iostream>
#include <cmath>
#include <boost/numeric/mtl/mtl.hpp>
using namespace std;
template <typename Vector>
void one_d_iteration(char const* name, const Vector & vector, size_t check_index, typename Vector::value_type check)
{
namespace traits = mtl::traits;
typename traits::index<Vector>::type index(vector);
typename traits::const_value<Vector>::type const_value(vector);
typedef mtl::tag::nz tag;
typedef typename traits::range_generator<tag, Vector>::type cursor_type;
typedef typename traits::range_generator<tag, Vector>::complexity complexity;
cout << name << "\nElements: " << complexity() << '\n';
for (cursor_type cursor = mtl::begin<tag>(vector), cend = mtl::end<tag>(vector); cursor != cend; ++cursor) {
cout << "vector[" << index(*cursor) << "] = "
<< const_value(*cursor) << '\n';
if (index(*cursor) == check_index
&& const_value(*cursor) != check)
throw "wrong check value";
}
}
template <typename Vector>
void test(Vector& v, const char* name)
{
using mtl::sum; using mtl::product;
typedef mtl::tag::iter::all iall;
typedef typename mtl::traits::range_generator<iall, Vector>::type Iter;
std::cout << "\n" << name << " --- v = " << v << "\n"; std::cout.flush();
for (Iter iter(mtl::begin<iall>(v)), iend(mtl::end<iall>(v)); iter != iend; ++iter)
cout << *iter << ", ";
cout << "\n";
one_d_iteration(name, v, 2, 8.0f);
std::cout << "one_norm(v) = " << one_norm(v) << "\n"; std::cout.flush();
MTL_THROW_IF(one_norm(v) != 15.0, mtl::runtime_error("one_norm wrong"));
std::cout << "two_norm(v) = " << two_norm(v) << "\n"; std::cout.flush();
MTL_THROW_IF(two_norm(v) < 9.6436 || two_norm(v) > 9.6437, mtl::runtime_error("two_norm wrong"));
std::cout << "infinity_norm(v) = " << infinity_norm(v) << "\n"; std::cout.flush();
MTL_THROW_IF(infinity_norm(v) != 8.0, mtl::runtime_error("infinity_norm wrong"));
std::cout << "sum(v) = " << sum(v) << "\n"; std::cout.flush();
MTL_THROW_IF(sum(v) != 15.0, mtl::runtime_error("sum wrong"));
std::cout << "product(v) = " << product(v) << "\n"; std::cout.flush();
MTL_THROW_IF(product(v) != 80.0, mtl::runtime_error("product wrong"));
mtl::dense_vector<float> u(3), w(3);
u= 3.0; w= 5.0;
std::cout << "u= v + w:\n"; std::cout.flush();
u= v + w;
cout << "u: " << u << "\n"; std::cout.flush();
MTL_THROW_IF(u[0] != 7.0, mtl::runtime_error("wrong"));
std::cout << "u= v + w + v + w:\n"; std::cout.flush();
u= v + w + v + w;
cout << "u: " << u << "\n"; std::cout.flush();
MTL_THROW_IF(u[0] != 14.0, mtl::runtime_error("wrong"));
std::cout << "u= v + (w= v + v);:\n"; std::cout.flush();
u= v + (w= v + v);
cout << "u: " << u << ", w: " << w << "\n"; std::cout.flush();
MTL_THROW_IF(w[0] != 4.0, mtl::runtime_error("w wrong"));
MTL_THROW_IF(u[0] != 6.0, mtl::runtime_error("u wrong"));
std::cout << name << " --- u+= dot<12>(v, w) * w;:\n"; std::cout.flush();
u+= mtl::dot<12>(v, w) * w;
cout << "u: " << u << ", v: " << v << ", w: " << w << "\n"; std::cout.flush();
MTL_THROW_IF(u[0] != 750.0, mtl::runtime_error("u wrong"));
Vector q(sub_vector(v, 1, 4));
MTL_THROW_IF(q[1] != 8.f, mtl::runtime_error("Wrong value in q"));
MTL_THROW_IF(size(q) != 2, mtl::runtime_error("Wrong size of q"));
std::cout << "sub_vector(v, 1, 4) == " << q << "\n";
using mtl::irange;
Vector r(v[irange(1, 4)]);
MTL_THROW_IF(r[1] != 8.f, mtl::runtime_error("Wrong value in r"));
MTL_THROW_IF(size(r) != 2, mtl::runtime_error("Wrong size of r"));
std::cout << "v[irange(1, 4)] == " << r << "\n";
}
template <typename Vector>
void test2(Vector& v)
{
#if 0
typedef typename mtl::traits::category<Vector>::type cat;
typedef typename mtl::traits::is_vector<Vector>::type isv;
typedef typename mtl::Collection<Vector>::value_type value_type;
typedef typename mtl::traits::category<value_type>::type vcat;
typedef typename mtl::ashape::ashape<value_type>::type ashape;
std::cout << "Category of v is " << typeid(cat).name() << '\n';
std::cout << "is vector " << typeid(isv).name() << '\n';
std::cout << "value type is " << typeid(value_type).name() << '\n';
std::cout << "Category of value is " << typeid(vcat).name() << '\n';
std::cout << "ashape of value is " << typeid(ashape).name() << '\n';
#endif
set_to_zero(v);
}
int main(int, char**)
{
mtl::dense_vector<float> v(3);
v= 2, 5, 8;
test(v, "Reference");
mtl::dense2D<float> A(3, 3);
A= 1, 2, 3,
4, 5, 6,
7, 8, 9;
mtl::vec::strided_vector_ref<float> stref(A[mtl::iall][2]);
test2(v);
test2(stref);
mtl::vec::strided_vector_ref<float> x(3, &A[0][1], 3);
const mtl::dense2D<float> B(A);
mtl::vec::strided_vector_ref<const float> xc(3, &B[0][1], 3);
test(x, "test float");
test(xc, "test const float");
return 0;
}
| 33.413174 | 116 | 0.568459 | [
"vector"
] |
bd79aaa64cc761d105e432710d63d5fac02e261b | 4,223 | cpp | C++ | Events/src/apGDBErrorEvent.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | 1 | 2017-01-28T14:12:29.000Z | 2017-01-28T14:12:29.000Z | Events/src/apGDBErrorEvent.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | null | null | null | Events/src/apGDBErrorEvent.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | 2 | 2016-09-21T12:28:23.000Z | 2019-11-01T23:07:02.000Z | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file apGDBErrorEvent.cpp
///
//==================================================================================
//------------------------------ apGDBErrorEvent.cpp ------------------------------
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTOSWrappers/Include/osOSDefinitions.h>
#include <AMDTOSWrappers/Include/osChannel.h>
#include <AMDTOSWrappers/Include/osChannelOperators.h>
// Local:
#include <AMDTAPIClasses/Include/Events/apGDBErrorEvent.h>
// ---------------------------------------------------------------------------
// Name: apGDBOutputStringEvent::apGDBOutputStringEvent
// Description: Constructor
// Arguments: gdbErrorString - The GDB outputted string.
// Author: AMD Developer Tools Team
// Date: 13/01/2009
// ---------------------------------------------------------------------------
apGDBErrorEvent::apGDBErrorEvent(const gtString& gdbErrorString)
: apEvent(OS_NO_THREAD_ID), _gdbErrorString(gdbErrorString)
{
}
// ---------------------------------------------------------------------------
// Name: apGDBErrorEvent::type
// Description: Returns my transferable object type.
// Author: AMD Developer Tools Team
// Date: 11/8/2009
// ---------------------------------------------------------------------------
osTransferableObjectType apGDBErrorEvent::type() const
{
return OS_TOBJ_ID_GDB_ERROR_EVENT;
}
// ---------------------------------------------------------------------------
// Name: apGDBErrorEvent::writeSelfIntoChannel
// Description: Writes this class data into a communication channel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 11/8/2009
// ---------------------------------------------------------------------------
bool apGDBErrorEvent::writeSelfIntoChannel(osChannel& ipcChannel) const
{
ipcChannel << _gdbErrorString;
// Call my parent class's version of this function:
bool retVal = apEvent::writeSelfIntoChannel(ipcChannel);
return retVal;
}
// ---------------------------------------------------------------------------
// Name: apGDBErrorEvent::readSelfFromChannel
// Description: Reads this class data from a communication channel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 11/8/2009
// ---------------------------------------------------------------------------
bool apGDBErrorEvent::readSelfFromChannel(osChannel& ipcChannel)
{
ipcChannel >> _gdbErrorString;
// Call my parent class's version of this function:
bool retVal = apEvent::readSelfFromChannel(ipcChannel);
return retVal;
}
// ---------------------------------------------------------------------------
// Name: apGDBOutputStringEvent::type
// Description: Returns my debugged process event type.
// Author: AMD Developer Tools Team
// Date: 13/01/2009
// ---------------------------------------------------------------------------
apEvent::EventType apGDBErrorEvent::eventType() const
{
return apEvent::AP_GDB_ERROR;
}
// ---------------------------------------------------------------------------
// Name: apGDBOutputStringEvent::clone
// Description: Creates a new copy of self, and returns it.
// It is the caller responsibility to delete the created copy.
// Author: AMD Developer Tools Team
// Date: 13/01/2009
// ---------------------------------------------------------------------------
apEvent* apGDBErrorEvent::clone() const
{
apGDBErrorEvent* pEventCopy = new apGDBErrorEvent(_gdbErrorString);
return pEventCopy;
}
// ---------------------------------------------------------------------------
// Name: apGDBErrorEvent::apGDBErrorEvent
// Description: Default constructor, only allowed for use by osTransferableObjectCreator
// Author: AMD Developer Tools Team
// Date: 12/8/2009
// ---------------------------------------------------------------------------
apGDBErrorEvent::apGDBErrorEvent()
{
}
| 36.721739 | 88 | 0.497277 | [
"object"
] |
bd7f1265145868052f6c1bbb947e798e268c37da | 1,011 | cpp | C++ | classification/src/svm/svm_predict_class.cpp | utarvl/core | 6720f254e202d2bc4b6a6a02915635a76ab9d7e9 | [
"Apache-2.0"
] | 2 | 2019-06-09T08:27:45.000Z | 2019-09-22T20:55:50.000Z | classification/src/svm/svm_predict_class.cpp | utarvl/core | 6720f254e202d2bc4b6a6a02915635a76ab9d7e9 | [
"Apache-2.0"
] | null | null | null | classification/src/svm/svm_predict_class.cpp | utarvl/core | 6720f254e202d2bc4b6a6a02915635a76ab9d7e9 | [
"Apache-2.0"
] | null | null | null | /*
* Cloud-based Object Recognition Engine (CORE)
*
*/
#include <core/classification/svm/svm_predict_class.h>
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
double
svmCovariancePredictClass (const struct svm_model* model, const Eigen::MatrixXd &covariance_matrix)
{
int k = 0;
struct svm_node* node = Malloc (struct svm_node, (covariance_matrix.rows () + 1) * covariance_matrix.rows () / 2 + 1);
for (int i = 0 ; i < covariance_matrix.rows (); ++i)
{
for (int j = i; j < covariance_matrix.cols (); ++j)
{
// Non-diagonal entries are multiplied by sqrt (2.0)
if (j != i)
{
node[k].index = k + 1;
node[k].value = sqrt (2.0) * covariance_matrix (i, j);
++k;
}
else
{
node[k].index = k + 1;
node[k].value = covariance_matrix (i, j);
++k;
}
}
}
// Terminate the vector
node[k].index = -1;
double label = svm_predict (model, node);
free (node);
return (label);
}
| 24.071429 | 121 | 0.571711 | [
"object",
"vector",
"model"
] |
bd85268a32fced1da4181492e55675415eb458c2 | 1,993 | cc | C++ | seurat/baker/framework/rasterizer.cc | Asteur/vrhelper | 7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53 | [
"Apache-2.0"
] | 819 | 2018-05-04T20:43:55.000Z | 2022-03-22T01:21:24.000Z | seurat/baker/framework/rasterizer.cc | mebalzer/seurat | 78c1293debdd2744cba11395024812f277f613f7 | [
"Apache-2.0"
] | 35 | 2018-05-05T03:50:16.000Z | 2019-11-04T22:56:02.000Z | seurat/baker/framework/rasterizer.cc | mebalzer/seurat | 78c1293debdd2744cba11395024812f277f613f7 | [
"Apache-2.0"
] | 88 | 2018-05-04T20:53:42.000Z | 2022-03-05T03:50:07.000Z | /*
Copyright 2017 Google Inc. All Rights Reserved.
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 "seurat/baker/framework/rasterizer.h"
#include "seurat/base/parallel.h"
#include "seurat/base/progress.h"
#include "seurat/ingest/view_group_loader_util.h"
namespace seurat {
namespace baker {
using base::Camera;
base::Status FrameRasterizer::Run(
absl::Span<const Frame> frames,
absl::Span<const std::shared_ptr<SampleAccumulator>> frame_accumulators)
const {
CHECK_EQ(frames.size(), frame_accumulators.size());
ray_classifier_->Init(frames);
// Loop over all views from all view-groups.
base::ScopedProgressRange progress("Generating textures",
view_loader_->GetNumViewGroups());
return ingest::ForEachViewGroupPrefetching(
*view_loader_, [&](std::vector<std::shared_ptr<Camera>> cameras,
std::vector<image::Ldi4f> ldis) {
ViewGroupRayBundle bundle(std::move(cameras), std::move(ldis));
std::vector<RayClassifier::ClassifiedRays> classified_rays =
ray_classifier_->ClassifyRays(bundle);
base::ParallelFor(thread_count_, frames.size(), [&](int frame_index) {
frame_accumulators[frame_index]->Add(
bundle, classified_rays[frame_index].solid_samples,
classified_rays[frame_index].freespace_rays);
});
progress.IncrementRange(1);
return base::OkStatus();
});
}
} // namespace baker
} // namespace seurat
| 35.589286 | 78 | 0.704967 | [
"vector"
] |
bd899e1f7633d0d5173af65d29374d46dedc2e1d | 5,624 | cpp | C++ | main.cpp | Gira-X/uva-online-1002-crossword-puzzle | 6e36dfa4ce29ff8588f708a86f4f3b59c7f86a63 | [
"MIT"
] | null | null | null | main.cpp | Gira-X/uva-online-1002-crossword-puzzle | 6e36dfa4ce29ff8588f708a86f4f3b59c7f86a63 | [
"MIT"
] | null | null | null | main.cpp | Gira-X/uva-online-1002-crossword-puzzle | 6e36dfa4ce29ff8588f708a86f4f3b59c7f86a63 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <vector>
#include <string.h>
#include <set>
#ifndef ONLINE_JUDGE
# include <fstream>
#endif
using namespace std;
struct slot {
int column;
int row;
bool down;
};
struct node {
unsigned char matrix[10][10];
unsigned int used_words; // a vector seems to be slower
unsigned char last_filled_slot;
};
vector<slot> slots;
vector<string> words;
string output = "";
void print_matrix(const struct node& n) {
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
const auto c = n.matrix[i][j];
if (c == '\0')
cout << ' ';
else
cout << c;
}
cout << "\n";
}
}
// to avoid creating some can_generate_next_node() method
static bool error;
inline struct node generate_next_node(const struct node& n, const int w)
{
error = false;
const auto word = words[w];
const auto slot = slots[n.last_filled_slot];
struct node next = {0};
memcpy(next.matrix, n.matrix, 100);
if (slot.down) {
for (int i = 0; i < word.length(); i++) {
const auto dd = n.matrix[slot.row + i][slot.column];
if (dd != 0 && dd != word[i]) {
error = true;
return next;
}
next.matrix[slot.row + i][slot.column] = word[i];
}
} else {
for (int i = 0; i < word.length(); i++) {
const auto dd = n.matrix[slot.row][slot.column + i];
if (dd != 0 && dd != word[i]) {
error = true;
return next;
}
next.matrix[slot.row][slot.column + i] = word[i];
}
}
next.used_words = n.used_words;
next.used_words |= 1 << w;
next.last_filled_slot = n.last_filled_slot + 1;
return next;
}
inline vector<struct node> get_children(const struct node& n) {
vector<node> result;
for (int i = 0; i < words.size(); ++i) {
const auto b = (n.used_words >> i) & 1;
if (b == 0) {
const auto newn = generate_next_node(n, i);
if (!error) {
result.push_back(newn);
}
}
}
return result;
}
// we can assume that the result will not be empty!
vector<node> get_roots() {
vector<node> result;
const auto slot = slots[0];
for (int i = 0; i < words.size(); ++i) {
struct node n = {0};
const auto word = words[i];
if (slot.down) {
for (int j = 0; j < word.length(); j++) {
n.matrix[slot.row + j][slot.column] = word[j];
}
} else {
for (int j = 0; j < word.length(); j++) {
n.matrix[slot.row][slot.column + j] = word[j];
}
}
n.used_words |= 1 << i;
n.last_filled_slot = 1;
result.push_back(n);
}
return result;
}
void processBacktracking() {
auto stack = get_roots();
set<unsigned int> results;
while (!stack.empty()) {
const auto n = stack.back();
stack.pop_back();
//cout << "\n"; print_matrix(n);
if (n.last_filled_slot == words.size() - 1) {
//cout << "\nResult: \n"; print_matrix(n);
results.insert(n.used_words);
} else {
const auto b = get_children(n);
for (const auto& bb : b) {
stack.push_back(bb);
}
}
}
if (results.empty()) {
output += " Impossible";
} else {
for (const auto& n : results) {
for (int i = 0; i < words.size(); ++i) {
const auto b = (n >> i) & 1;
if (b == 0) {
output += " " + words[i];
break;
}
}
}
}
}
int main() {
#ifndef ONLINE_JUDGE
ifstream cin("test-input.txt");
#endif
int n = 0;
int testCase = 0;
while (cin >> n && n != 0) {
slots.clear();
words.clear();
int row, column;
char direction;
for (int i = 0; i < n; ++i) {
cin >> row >> column >> direction;
slots.push_back(slot{column - 1, row - 1,
direction == 'D'});
}
for (int i = 0; i <= n; i++) {
string word;
cin >> word;
words.push_back(word);
}
output += "Trial " + to_string(++testCase) + ":";
processBacktracking();
output += "\n\n";
}
cout << output;
return 0;
} | 31.954545 | 78 | 0.381935 | [
"vector"
] |
bd93d26bc58de49e118b5143263668978b4028ab | 16,552 | cpp | C++ | tapl/pte/ptEngine.cpp | towardsautonomy/TAPL | 4d065b2250483bf2ea118bafa312ca893a25ca87 | [
"MIT"
] | 1 | 2021-01-05T12:53:17.000Z | 2021-01-05T12:53:17.000Z | tapl/pte/ptEngine.cpp | towardsautonomy/TAPL | 4d065b2250483bf2ea118bafa312ca893a25ca87 | [
"MIT"
] | null | null | null | tapl/pte/ptEngine.cpp | towardsautonomy/TAPL | 4d065b2250483bf2ea118bafa312ca893a25ca87 | [
"MIT"
] | null | null | null | #include "ptEngine.hpp"
#include <Eigen/Dense>
namespace tapl {
namespace pte {
// constructor
template <typename PointT>
Line<PointT>::Line() {}
// de-constructor
template <typename PointT>
Line<PointT>::~Line() {}
template <typename PointT>
std::vector<float> Line<PointT>::fitSVD(std::vector<float> &x, std::vector<float> &y)
{
/*
System of linear equations of the form Ax = 0
SVD method solves the equation Ax = 0 by performing
singular-value decomposition of matrix A
*/
// Form Matrix A
Eigen::MatrixXd A(x.size(), 3);
for(int i = 0; i < x.size(); ++i)
{
A(i, 0) = x[i];
A(i, 1) = y[i];
A(i, 2) = 1.0;
}
// Take SVD of A
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::DecompositionOptions::ComputeThinU | Eigen::DecompositionOptions::ComputeThinV);
Eigen::MatrixXd V = svd.matrixV();
// store in vector
std::vector<float> line_coeffs;
for(auto i = 0; i < V.rows(); ++i)
{
line_coeffs.push_back(V(i, (V.cols() - 1)));
}
// Return coeffs
return line_coeffs;
}
template <typename PointT>
std::vector<float> Line<PointT>::fitLS(std::vector<float> &x, std::vector<float> &y)
{
/*
System of linear equations of the form Y = Hx
least-squares method attempts to minimize
the energy of error, J(x) = ( ||Y - Hx|| )^2
where, ||Y - Hx|| is the Euclidian length of vector (Y - Hx)
*/
// Form Matrix H
Eigen::MatrixXd H(x.size(), 2);
for(int i = 0; i < x.size(); ++i)
{
H(i, 0) = x[i];
H(i, 1) = 1.0;
}
// Form Matrix Y
Eigen::MatrixXd Y(y.size(), 1);
for(int i = 0; i < y.size(); ++i)
{
Y(i, 0) = y[i];
}
// Transpose of H
auto H_transpose = H.transpose();
// get line coefficients
auto coeffs = ((H_transpose*H).inverse()) * (H_transpose*Y);
// Line equation is of the form y = a'x + b'
// let's convert it to the form ax + by + c = 0
// a = a'; b = -1; c = b'
std::vector<float> line_coeffs;
line_coeffs.push_back(coeffs(0, 0));
line_coeffs.push_back(-1.0);
line_coeffs.push_back(coeffs(1, 0));
// Return coefficients
return line_coeffs;
}
template <typename PointT>
float Line<PointT>::distToPoint(std::vector<float> line_coeffs, PointT point)
{
float dist = fabs(line_coeffs[0] * point.x + line_coeffs[1] * point.y + line_coeffs[2]) /
sqrt(pow(line_coeffs[0], 2) + pow(line_coeffs[1], 2));
return dist;
}
template <typename PointT>
std::unordered_set<int> Line<PointT>::Ransac(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distTolerance)
{
// random number seed
srand(time(NULL));
// get the start timestamp
auto t_start = std::chrono::high_resolution_clock::now();
std::unordered_set<int> inliersResult;
// number of random samples to select per iteration
const int n_random_samples = 2;
// number of inliers for each iteration
std::vector<int> n_inliers(maxIterations, 0);
// coefficients for each line
std::vector<std::vector<float>> coeffs(maxIterations);
// iterate 'maxIterations' number of times
for(int i = 0; i < maxIterations; ++i)
{
// x, y, and z points as a vector
std::vector<float> x, y, z;
// select random samples
for(int j = 0; j < n_random_samples; ++j)
{
int idx = rand()%cloud->size();
x.push_back(cloud->at(idx).x);
y.push_back(cloud->at(idx).y);
z.push_back(cloud->at(idx).z);
}
// fit a line
coeffs[i] = this->fitSVD(x, y);
for(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)
{
if(this->distToPoint(coeffs[i], *it) <= distTolerance)
{
n_inliers[i]++;
}
}
}
// find the index for number of inliers
auto inliers_it = std::max_element(n_inliers.begin(), n_inliers.end());
int index_max_n_inlier = std::distance(n_inliers.begin(), inliers_it);
// find inliers with the best fit
int index = 0;
for(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)
{
if(this->distToPoint(coeffs[index_max_n_inlier], *it) <= distTolerance)
{
inliersResult.insert(index);
}
index++;
}
// get the end timestamp
auto t_end = std::chrono::high_resolution_clock::now();
// measure execution time
auto t_duration = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start);
TLOG_INFO << "Time taken by RANSAC: "
<< t_duration.count() << " milliseconds" ;
// Return indicies of inliers from fitted line with most inliers
return inliersResult;
}
// constructor
template <typename PointT>
Plane<PointT>::Plane() {}
// de-constructor
template <typename PointT>
Plane<PointT>::~Plane() {}
template <typename PointT>
std::vector<float> Plane<PointT>::fitSVD(std::vector<float> &x, std::vector<float> &y, std::vector<float> &z)
{
/*
System of linear equations of the form Ax = 0
SVD method solves the equation Ax = 0 by performing
singular-value decomposition of matrix A
*/
// Form Matrix A
Eigen::MatrixXd A(x.size(), 4);
for(int i = 0; i < x.size(); ++i)
{
A(i, 0) = x[i];
A(i, 1) = y[i];
A(i, 2) = z[i];
A(i, 3) = 1.0;
}
// Take SVD of A
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::DecompositionOptions::ComputeThinU | Eigen::DecompositionOptions::ComputeThinV);
Eigen::MatrixXd V = svd.matrixV();
// Plane equation is of the form ax + by + cz + d = 0
std::vector<float> plane_coeffs;
for(auto i = 0; i < V.rows(); ++i)
{
plane_coeffs.push_back(V(i, (V.cols() - 1)));
}
// Return coeffs
return plane_coeffs;
}
template <typename PointT>
std::vector<float> Plane<PointT>::fitLS(std::vector<float> &x, std::vector<float> &y, std::vector<float> &z)
{
/*
System of linear equations of the form Y = Hx
least-squares method attempts to minimize
the energy of error, J(x) = ( ||Y - Hx|| )^2
where, ||Y - Hx|| is the Euclidian length of vector (Y - Hx)
*/
// Form Matrix H
Eigen::MatrixXd H(x.size(), 3);
for(int i = 0; i < x.size(); ++i)
{
H(i, 0) = x[i];
H(i, 1) = y[i];
H(i, 2) = 1.0;
}
// Form Matrix Y
Eigen::MatrixXd Y(z.size(), 1);
for(int i = 0; i < z.size(); ++i)
{
Y(i, 0) = z[i];
}
// Transpose of H
auto H_transpose = H.transpose();
// get plane coefficients
auto coeffs = ((H_transpose*H).inverse()) * (H_transpose*Y);
// Plane equation is of the form z = a'x + b'y + c'
// let's convert it to the form ax + by + cz + d = 0
// a = a'; b = b'; c = -1; d = c'
std::vector<float> plane_coeffs;
plane_coeffs.push_back(coeffs(0, 0));
plane_coeffs.push_back(coeffs(1, 0));
plane_coeffs.push_back(-1.0);
plane_coeffs.push_back(coeffs(2, 0));
// Return coefficients
return plane_coeffs;
}
template <typename PointT>
float Plane<PointT>::distToPoint(std::vector<float> plane_coeffs, PointT point)
{
float dist = fabs(plane_coeffs[0] * point.x + plane_coeffs[1] * point.y + plane_coeffs[2] * point.z + plane_coeffs[3]) /
sqrt(pow(plane_coeffs[0], 2) + pow(plane_coeffs[1], 2) + pow(plane_coeffs[2], 2));
return dist;
}
template <typename PointT>
std::unordered_set<int> Plane<PointT>::Ransac(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceToPlane)
{
// random number seed
srand(time(NULL));
// get the start timestamp
auto t_start = std::chrono::high_resolution_clock::now();
std::unordered_set<int> inliersResult;
// number of random samples to select per iteration
const int n_random_samples = 3;
// number of inliers for each iteration
std::vector<int> n_inliers(maxIterations, 0);
// coefficients for each plane
std::vector<std::vector<float>> coeffs(maxIterations);
// iterate 'maxIterations' number of times
for(int i = 0; i < maxIterations; ++i)
{
// x, y, and z points as a vector
std::vector<float> x, y, z;
// select random samples
for(int j = 0; j < n_random_samples; ++j)
{
int idx = rand()%(cloud->size());
x.push_back(cloud->at(idx).x);
y.push_back(cloud->at(idx).y);
z.push_back(cloud->at(idx).z);
}
// fit a plane
coeffs[i] = this->fitLS(x, y, z);
for(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)
{
// TLOG_INFO << "dist = " << this->distToPoint(coeffs[i], *it) ;
if(this->distToPoint(coeffs[i], *it) <= distanceToPlane)
{
n_inliers[i]++;
}
}
}
// find the index for number of inliers
auto inliers_it = std::max_element(n_inliers.begin(), n_inliers.end());
int index_max_n_inlier = std::distance(n_inliers.begin(), inliers_it);
// find inliers with the best fit
int index = 0;
for(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)
{
if(this->distToPoint(coeffs[index_max_n_inlier], *it) <= distanceToPlane)
{
inliersResult.insert(index);
}
index++;
}
// get the end timestamp
auto t_end = std::chrono::high_resolution_clock::now();
// measure execution time
auto t_duration = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start);
// Return indicies of inliers from fitted line with most inliers
return inliersResult;
}
void KdTree::insertHelper(Node ** node, unsigned depth, std::vector<float> point, int id)
{
if(*node != NULL) {
// x split when (depth % 3) = 0; y split when (depth % 3) = 1; z split when (depth % 3) = 2
// index for accessing point.x is 0; index for accessing point.y is 1; index for accessing point.z is 2
if(point[(depth % 3)] < ((*node)->point[(depth % 3)])) {
node = &((*node)->left);
}
else {
node = &((*node)->right);
}
// call this function recursively until a NULL is hit
insertHelper(node, depth+1, point, id);
}
else {
// create a node and insert the point
*node = new Node(point, id);
}
}
void KdTree::insert(std::vector<float> point, int id)
{
// This function inserts a new point into the tree
// the function creates a new node and places correctly with in the root
insertHelper(&this->root, 0, point, id);
}
// this function returns euclidian distance between two points
float KdTree::dist(std::vector<float> point_a, std::vector<float> point_b)
{
// compute distance
float dist = sqrt(pow((point_a[0] - point_b[0]), 2)
+ pow((point_a[1] - point_b[1]), 2)
+ pow((point_a[2] - point_b[2]), 2));
// Return the euclidian distance between points
return dist;
}
void KdTree::searchHelper(Node * node, std::vector<float> target, float distTolerance, int depth, std::vector<int>& ids)
{
if(node != NULL) {
// add this node id to the list if its distance from target is less than distTolerance
if(dist(node->point, target) <= distTolerance)
ids.push_back(node->id);
// x split when (depth % 3) = 0; y split when (depth % 3) = 1; z split when (depth % 3) = 2
// index for accessing point.x is 0; index for accessing point.y is 1; index for accessing point.z is 2
if((target[depth % 3] - distTolerance) < node->point[(depth % 3)])
searchHelper(node->left, target, distTolerance, depth+1, ids);
if((target[depth % 3] + distTolerance) > node->point[(depth % 3)])
searchHelper(node->right, target, distTolerance, depth+1, ids);
}
}
// return a list of point ids in the tree that are within distance of target
std::vector<int> KdTree::search(std::vector<float> target, float distTolerance)
{
std::vector<int> ids;
searchHelper(this->root, target, distTolerance, 0, ids);
return ids;
}
void EuclideanCluster::proximityPoints( int pointIndex,
std::vector<bool>& checked,
float distTolerance,
std::vector<int>& cluster)
{
std::vector<int> nearby = this->tree->search(this->points[pointIndex], distTolerance);
for(auto it = nearby.begin(); it != nearby.end(); ++it) {
if(! checked[*it]) {
checked[*it] = true;
cluster.push_back(*it);
// call this function recursively to find all the points within proximity (i.e. points within proximity of proximity)
proximityPoints(*it, checked, distTolerance, cluster);
}
}
}
std::vector<std::vector<int>> EuclideanCluster::clustering(float distTolerance)
{
std::vector<std::vector<int>> clusters;
// vector to keep track of checked points
std::vector<bool> checked(points.size(), false);
for(int i = 0; i < this->points.size(); ++i) {
// create a new cluster if this point was not processed already
if(! checked[i]) {
std::vector<int> cluster;
checked[i] = true;
cluster.push_back(i);
// find points within the proximity
proximityPoints(i, checked, distTolerance, cluster);
// add this cluster to the vector of clusters
clusters.push_back(cluster);
}
}
return clusters;
}
/**
* @brief returns world to camera rotation matrix
*
* Camera Coordinate System:
* X -> To the right
* Y -> Down
* Z -> Forward - Direction where the camera is pointing
*
* World Coordinate System:
* X -> Forward - Direction where the camera is pointing
* Y -> To the left
* Z -> Up
* @return rotation matrix
*/
cv::Mat world2CamRotation() {
// camera coordinate to world coordinate rotation matrix
cv::Mat R = cv::Mat::zeros(3, 3, CV_32F);
// Camera rotation
float Rx = degreesToRadians(-90);
float Ry = degreesToRadians(0);
float Rz = degreesToRadians(-90);
// Rz
cv::Mat R_z = cv::Mat::eye(3, 3, CV_32F);
R_z.at<float>(0, 0) = cos(Rz);
R_z.at<float>(0, 1) = -sin(Rz);
R_z.at<float>(1, 0) = sin(Rz);
R_z.at<float>(1, 1) = cos(Rz);
// Ry
cv::Mat R_y = cv::Mat::eye(3, 3, CV_32F);
R_y.at<float>(0, 0) = cos(Ry);
R_y.at<float>(0, 2) = sin(Ry);
R_y.at<float>(2, 0) = -sin(Ry);
R_y.at<float>(2, 2) = cos(Ry);
// Rx
cv::Mat R_x = cv::Mat::eye(3, 3, CV_32F);
R_y.at<float>(1, 1) = cos(Rx);
R_y.at<float>(1, 2) = -sin(Rx);
R_y.at<float>(2, 1) = sin(Rx);
R_y.at<float>(2, 2) = cos(Rx);
// Camera Rotation Correction Matrix
R = R_z * R_y * R_x;
// return rotation matrix
return R;
}
/**
* @brief affine transform on a point
*
* Apply affine transforms on point given in world coordinate
*
*
* Camera Coordinate System:
* X -> To the right
* Y -> Down
* Z -> Forward - Direction where the camera is pointing
*
* World Coordinate System:
* X -> Forward - Direction where the camera is pointing
* Y -> To the left
* Z -> Up
*
* @param[in] point point in world coordinate
*
* @return point in camera coordinate
*/
template <typename PointT>
void world2CamCoordinate(PointT &point) {
// Camera Rotation Correction Matrix
cv::Mat R = world2CamRotation();
cv::Mat xyz = cv::Mat(3, 1, CV_32F);
xyz.at<float>(0, 0) = point.x;
xyz.at<float>(1, 0) = point.y;
xyz.at<float>(2, 0) = point.z;
cv::Mat xyz_w = cv::Mat(3, 1, CV_32F);
xyz_w = R * xyz;
point.x = xyz_w.at<float>(0, 0);
point.y = xyz_w.at<float>(1, 0);
point.z = xyz_w.at<float>(2, 0);
}
}
}
// explicit instantiation to avoid linker error
template class tapl::pte::Line<tapl::Point3d>;
template class tapl::pte::Line<pcl::PointXYZ>;
template class tapl::pte::Line<pcl::PointXYZI>;
template class tapl::pte::Line<pcl::PointXYZRGB>;
template class tapl::pte::Plane<tapl::Point3d>;
template class tapl::pte::Plane<pcl::PointXYZ>;
template class tapl::pte::Plane<pcl::PointXYZI>;
template class tapl::pte::Plane<pcl::PointXYZRGB>; | 30.880597 | 134 | 0.592073 | [
"vector",
"transform"
] |
bd9570c3fd1f6053c82cef89597a724143db4821 | 72,498 | cpp | C++ | toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/DynamicalSystem.cpp | SSV-Group/dsverifier | 1daca4704216edf9a360b4a39e00663d94646ad1 | [
"Apache-2.0"
] | 10 | 2016-08-29T19:23:25.000Z | 2020-10-18T22:27:21.000Z | toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/DynamicalSystem.cpp | SSV-Group/dsverifier | 1daca4704216edf9a360b4a39e00663d94646ad1 | [
"Apache-2.0"
] | 64 | 2016-09-10T16:29:44.000Z | 2019-01-15T14:31:06.000Z | toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/DynamicalSystem.cpp | SSV-Group/dsverifier | 1daca4704216edf9a360b4a39e00663d94646ad1 | [
"Apache-2.0"
] | 5 | 2016-10-09T21:38:41.000Z | 2017-07-05T10:05:32.000Z | //Authors: Dario Cattaruzza, Alessandro Abate, Peter Schrammel, Daniel Kroening
//University of Oxford 2016
//This code is supplied under the BSD license agreement (see license.txt)
#include <fstream>
#include <boost/timer.hpp>
#include "DynamicalSystem.h"
namespace abstract{
template <class scalar>
bool DynamicalSystem<scalar>::ms_fullAnswers=true;
/// Constructs an empty buffer
template <class scalar>
DynamicalSystem<scalar>::DynamicalSystem(const int dimension,const int idimension,const int odimension) :
AbstractMatrix<scalar>(dimension),
m_idimension(idimension),
m_odimension(odimension>0 ? odimension : dimension),
m_fdimension(0),
m_inputs(idimension),
m_reach(dimension),
m_subReach(dimension),
m_initialState("Initial State",dimension),
m_transformedInputs("Transformed Inputs",dimension),
m_transformedStateInputs("Accel Inputs",dimension),
m_pTransformedRoundInputs(NULL),
m_guard("Guard",dimension),
m_safeReachTube("Safe Reach Tube",dimension),
m_outputGuard(odimension),
m_templates(dimension,0),
m_eigenTemplates(dimension,0),
m_sensitivity(dimension,idimension)
{
ms_logger.logData("Loading System: ",false);
if (func::getDefaultPrec()>=128) {
std::stringstream buffer;
buffer << func::getDefaultPrec();
ms_logger.logData(interval_def<scalar>::ms_name,false);
ms_logger.logData(buffer.str());
}
else ms_logger.logData(interval_def<scalar>::ms_name);
m_inputs.setName("Inputs");
m_pReachSet=new EigenPolyhedra<scalar>("Reach Set",dimension);
m_pReachTube=new EigenPolyhedra<scalar>("Reach Tube",dimension);
m_pAbstractReachTube=new EigenPolyhedra<scalar>("Abstract Reach Tube",dimension);
}
/// deletes the array of CalibrationSamples that represent the file
template <class scalar>
DynamicalSystem<scalar>::~DynamicalSystem(void)
{
delete m_pReachSet;
delete m_pReachTube;
delete m_pAbstractReachTube;
}
/// Changes the default dimension of the system
template <class scalar>
void DynamicalSystem<scalar>::changeDimensions(int dimension,int idimension,int odimension,int fdimension)
{
if (dimension!=m_dimension) {
AbstractMatrix<scalar>::changeDimensions(dimension);
m_reach.changeDimension(dimension);
m_guard.changeDimension(dimension);
m_safeReachTube.changeDimension(dimension);
m_initialState.changeDimension(dimension);
m_transformedInputs.changeDimension(dimension);
m_transformedStateInputs.changeDimension(dimension);
m_pReachSet->changeDimension(dimension);
m_pReachTube->changeDimension(dimension);
m_pAbstractReachTube->changeDimension(dimension);
m_templates.resize(dimension,0);
m_eigenTemplates.resize(dimension,0);
m_pTransformedRoundInputs=NULL;
}
if (m_idimension!=idimension) {
m_inputs.changeDimension(idimension);
m_idimension=idimension;
}
if (m_odimension!=odimension) {
m_outputGuard.changeDimension(odimension);
m_odimension=odimension;
}
m_fdimension=fdimension;
}
// Sets the system parameters
template <class scalar>
void DynamicalSystem<scalar>::setParams(ParamMatrix& params)
{
m_paramValues=params;
if (m_paramValues.coeff(eNumBits,0)>0) {
func::setDefaultPrec(m_paramValues.coeff(eNumBits,0));
}
if (m_paramValues.coeff(eNumStates,0)>0) changeDimensions(m_paramValues.coeff(eNumStates,0),m_paramValues.coeff(eNumInputs,0)+m_paramValues.coeff(eNumVarInputs,0),m_paramValues.coeff(eNumOutputs,0),m_paramValues.coeff(eNumFeedbacks,0));
}
/// Loads a full dynamic description
template <class scalar>
int DynamicalSystem<scalar>::load(std::string &data,size_t pos)
{
m_loadTime=-1;
boost::timer timer;
int result=ms_logger.StringToDim(m_paramValues,data,pos);
if (result<0) return result;
if (m_paramValues.coeff(eNumBits,0)>0) {
functions<mpfr::mpreal>::setDefaultPrec(m_paramValues.coeff(eNumBits,0));
}
else func::ms_isImprecise=false;
traceDynamics((traceDynamics_t)m_paramValues.coeff(eTraceLevel,0));
traceSimplex((traceTableau_t)m_paramValues.coeff(eTraceLevel,1),(traceVertices_t)m_paramValues.coeff(eTraceLevel,2));
if (m_paramValues.coeff(eNumStates,0)>0) changeDimensions(m_paramValues.coeff(eNumStates,0),m_paramValues.coeff(eNumInputs,0)+m_paramValues.coeff(eNumVarInputs,0),m_paramValues.coeff(eNumOutputs,0),m_paramValues.coeff(eNumFeedbacks,0));
m_feedback.resize(0,m_odimension);
m_sensitivity.resize(m_paramValues.coeff(eNumStates,0),m_paramValues.coeff(eNumInputs,0)+m_paramValues.coeff(eNumVarInputs,0));
m_inputType=(m_paramValues.coeff(eNumVarInputs,0)>0) ? eVariableInputs : ((m_paramValues.coeff(eNumInputs,0)>0) ? eParametricInputs : eNoInputs);
if (ms_trace_time) {
ms_logger.logData(m_paramValues.coeff(eNumStates,0),"Full load",true);
ms_logger.logData(timer.elapsed()*1000,"Header time:",true);
}
result=loadGuard(data,result);
if (result<0) return result;
result=loadDynamics(data,result);
if (result<0) return result;
result=loadInitialState(data,result);
if (result<0) return result;
commands_t command;
ms_logger.getCommand(command,data,result);
if (command==ePlusCmd) {
result=loadSensitivities(data,result);
if (result<0) return result;
result=loadInputs(data,result);
if (result<0) return result;
}
ms_logger.getCommand(command,data,result);
if (command==eGivenCmd) {
result=ms_logger.getCommand(command,data,result);
result=loadOutputGuard(data,result);
if (result<0) return result;
result=loadOutputSensitivities(data,result);
if (result<0) return result;
}
else m_outputSensitivity=ms_emptyMatrix;
ms_logger.getCommand(command,data,result);
if (command==eEqualsCmd) {
result=loadSafeReachTube(data,result);
if (result<0) return result;
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Safe Tube time:",true);
}
else {
m_templates.resize(m_dimension,0);
m_safeReachTube.clear();
}
m_loadTime=timer.elapsed()*1000;
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Load time:",true);
return result;
}
/// Loads a full dynamic description
template <class scalar>
int DynamicalSystem<scalar>::load(std::string &guard,std::string &dynamics,std::string &init,std::string &sensitivity,std::string &inputs,std::string &templates,bool vertices)
{
m_loadTime=-1;
boost::timer timer;
if (ms_trace_time) ms_logger.logData(m_dimension,"Load",true);
int result=loadGuard(guard,0,vertices);
if (result<0) return result;
result=loadDynamics(dynamics);
if (result<0) return result;
result=loadInitialState(init,0,vertices);
if (result<0) return result;
result=loadSensitivities(sensitivity);
if (result<0) return result;
result=loadInputs(inputs,0,vertices);
if (result<0) return result;
result=loadSafeReachTube(templates);
if (result<0) return result;
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Template time:",true);
m_loadTime=timer.elapsed()*1000;
return result;
}
/// Loads a system from known structures
template <class scalar>
bool DynamicalSystem<scalar>::load(const MatrixS &dynamics,const MatrixS &sensitivity,AbstractPolyhedra<scalar> &guard,AbstractPolyhedra<scalar> &init,AbstractPolyhedra<scalar> &inputs,AbstractPolyhedra<scalar>& safeSpace,AbstractPolyhedra<scalar> *pOutputs)
{
if (JordanMatrix<scalar>::load(dynamics)) setEigenSpace();
m_sensitivity=sensitivity;
m_guard.load(guard);
m_initialState.load(init);
m_inputs.copy(inputs);
processInputs();
m_safeReachTube.load(safeSpace);
if (pOutputs) m_outputGuard.copy(*pOutputs);
return true;
}
/// Saves a description of the analysis onto a file
template <class scalar> bool DynamicalSystem<scalar>::save(displayType_t displayType,space_t space,bool interval,bool append)
{
std::ofstream file;
std::string fileName=m_name+"."+interval_def<scalar>::ms_name;
if (func::getDefaultPrec()>=128) {
std::stringstream buffer;
buffer << func::getDefaultPrec();
fileName+=buffer.str();
}
if (append) file.open(fileName.data(),std::ofstream::app);
else file.open(fileName.data());
if (!file.is_open()) return false;
std::string data=getDescription(displayType,space,interval);
if (append) file << "\n|\n\n";
file.write(data.data(),data.size());
file.close();
return true;
}
/// returns a description of the processed system
template <class scalar>
std::string DynamicalSystem<scalar>::getDescription(displayType_t displayType,space_t space,bool interval,bool useBrackets)
{
std::string result="Axelerator "+version+"\n";
result+=ms_logger.DimToString(&m_paramValues,func::toUpper(this->m_error));
if (func::ms_isImprecise) result+=func::ms_imprecise+"\n";
if (ms_fullAnswers) {
result+=m_guard.getPolyhedra(space).getDescription(displayType,interval,useBrackets);
result+="->\n";
if (getAbstractDynamics(m_inputType).isEmpty()) {
result+=ms_logger.MatToString(this->m_dynamics,interval);
}
else {
if (space==eNormalSpace) result+=ms_logger.MatToString(m_pseudoEigenVectors,interval);
result+=getAbstractDynamics(m_inputType).getDescription(displayType,interval,useBrackets);
if (space==eNormalSpace) result+=ms_logger.MatToString(m_invPseudoEigenVectors,interval);
}
result+=m_initialState.getPolyhedra(space).getDescription(displayType,interval,useBrackets);
if (space>eNormalSpace) result+=ms_logger.MatToString(m_invPseudoEigenVectors,interval);
if (m_inputType>eNoInputs) {
result+="+\n";
result+=ms_logger.MatToString(this->m_sensitivity,interval);
result+=m_inputs.getDescription(displayType,interval,useBrackets);
}
result+="=\n";
}
else m_pAbstractReachTube->getPolyhedra(space).toOuter(true);
if (m_dynamicParams.cols()>0) {
MatrixS row=m_dynamicParams.row(eFinalIterations);
result+="Iterations: "+ms_decoder.MatToString(row);
row=m_dynamicParams.row(eFinalPrecision);
result+="Precision: "+ms_decoder.MatToString(row);
row=m_dynamicParams.row(eFinalLoadTime);
result+="Load Time: "+ms_decoder.MatToString(row);
row=m_dynamicParams.row(eFinalReachTime);
result+="Reach Time: "+ms_decoder.MatToString(row);
}
result+=m_pAbstractReachTube->getPolyhedra(space).getDescription(displayType,interval,useBrackets);
return result;
}
/// Loads a system description from file
template <class scalar>
int DynamicalSystem<scalar>::loadFromFile(std::string &fileName)
{
std::stringstream buffer;
std::ifstream file;
ms_logger.logData("Loading file: ",false);
ms_logger.logData(fileName);
file.open(fileName.data());
if (!file.is_open()) {
ms_logger.logData("Unable to load file: ",false);
ms_logger.logData(fileName);
return -1;
}
buffer << file.rdbuf();
file.close();
m_source=buffer.str();
m_name=fileName;
return load(m_source);
}
template <class scalar>
int DynamicalSystem<scalar>::loadGuard(const std::string &data,size_t pos,bool vertices)
{
boost::timer timer;
commands_t command;
ms_logger.getCommand(command,data,pos);
if (command==eArrowCmd) {
m_guard.clear();
return pos;
}
int result=m_guard.load(data,pos,vertices);
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Guard time:",true);
return result;
}
template <class scalar>
int DynamicalSystem<scalar>::loadOutputGuard(const std::string &data,size_t pos,bool vertices)
{
commands_t command;
ms_logger.getCommand(command,data,pos);
if (command==eArrowCmd) {
m_outputGuard.clear();
return pos;
}
return m_outputGuard.loadData(data,pos,vertices);
}
/// Loads a polyhedral description for the initial state
template <class scalar>
int DynamicalSystem<scalar>::loadInitialState(const std::string &data,size_t pos,bool vertices)
{
boost::timer timer;
int result=m_initialState.load(data,pos,vertices);
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"State time:",true);
return result;
}
/// Processes the transformed inputs
template <class scalar>
void DynamicalSystem<scalar>::processInputs()
{
m_transformedInputs.load(m_inputs,this->m_sensitivity);
m_transformedStateInputs.load(m_transformedInputs.getPolyhedra(),this->m_invIminA,this->m_IminA);
if (m_inputs.ms_trace_tableau>=eTraceTransforms) {
m_inputs.logTableau();
m_transformedInputs.getPolyhedra().logTableau();
m_transformedInputs.getPolyhedra(eEigenSpace).logTableau();
m_transformedStateInputs.getPolyhedra().logTableau();
}
AbstractPolyhedra<scalar>& polyhedra=m_transformedInputs.getPolyhedra(eSingularSpace,m_conjugatePair,m_jordanIndex);
m_pTransformedRoundInputs=&m_transformedStateInputs.getSingularPolyhedraRef();
m_pTransformedRoundInputs=&polyhedra.getTransformedPolyhedra(*m_pTransformedRoundInputs,this->m_invIminF,this->m_IminF);
if (m_inputs.ms_trace_tableau>=eTraceTransforms) {
m_pTransformedRoundInputs->logTableau();
}
}
/// Loads a polyhedral description for the inputs
template <class scalar>
int DynamicalSystem<scalar>::loadInputs(const std::string &data,size_t pos,bool vertices)
{
boost::timer timer;
int result=m_inputs.loadData(data,pos,vertices);
if (result>0) processInputs();
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Inputs time:",true);
return result;
}
template <class scalar>
int DynamicalSystem<scalar>::loadSafeReachTube(const std::string &data,size_t pos,bool vertices)
{
commands_t command;
pos=ms_logger.getCommand(command,data,pos);
if (ms_logger.hasInequalities(data,pos)) return m_safeReachTube.load(data,pos,vertices);
m_safeReachTube.clear();
return loadTemplates(data,pos);
}
/// Sets a number of template directions for polyhedra representation
template <class scalar>
int DynamicalSystem<scalar>::loadTemplates(const std::string &data,size_t pos)
{
commands_t command;
pos=ms_logger.getCommand(command,data,pos);
if (data.compare(pos,7,"[ortho]")==0) {
m_templates=MatrixS::Zero(m_dimension,2*m_dimension);
for (int i=0;i<m_dimension;i++) {
m_templates.coeffRef(i,2*i)=1;
m_templates.coeffRef(i,2*i+1)=-1;
}
m_eigenTemplates=m_pseudoEigenVectors*m_templates;
}
else if (data.compare(pos,7,"[eigen]")==0) {
m_eigenTemplates=MatrixS::Zero(m_dimension,2*m_dimension);
for (int i=0;i<m_dimension;i++) {
m_eigenTemplates.coeffRef(i,2*i)=1;
m_eigenTemplates.coeffRef(i,2*i+1)=-1;
}
m_templates=m_invPseudoEigenVectors*m_eigenTemplates;
}
else if (data.compare(pos,6,"[init]")==0) {
m_templates=m_initialState.getPolyhedra().getDirections();
m_eigenTemplates=m_pseudoEigenVectors*m_templates;
return 6;
}
else {
int lines=ms_logger.lines(data,pos);
MatrixS templates(lines,m_dimension);
int result=ms_logger.StringToMat(templates,data,pos);
if (result<0) return result;
m_templates=templates.transpose();
m_eigenTemplates=m_pseudoEigenVectors*m_templates;
return result;
}
return 7;
}
/// Retrieves the reach set at the given iteration
template <class scalar>
AbstractPolyhedra<scalar>& DynamicalSystem<scalar>::getReachSet(powerS iteration,AbstractPolyhedra<scalar> &init,inputType_t inputType,bool accelerated,bool inEigenSpace,int directions,bool retemplate,bool keep)
{
if (&init==&m_reach) {
m_subReach.copy(init);
return getReachSet(iteration,m_subReach,inputType,accelerated,inEigenSpace,directions,retemplate,keep);
}
if (m_hasMultiplicities) this->calculateBoundedEigenError(calculateMaxIterations(iteration));
space_t space=(inEigenSpace || (accelerated && (iteration>0) && (inputType==eVariableInputs))) ? eEigenSpace : eNormalSpace;
AbstractPolyhedra<scalar>& input=m_transformedInputs.getPolyhedra(space);
int tag=init.getTag();
m_reach.setTag(tag+iteration);
std::stringstream buffer;
if (inEigenSpace) buffer << "Eigen";
buffer << "Reach Set " << m_reach.getTag();
if (tag>0) buffer << "(from " << tag << ")";
m_reach.setName(buffer.str());
m_pReachSet->setName(buffer.str());
if (!accelerated && (inputType>eParametricInputs)) {
m_reach.copy(init);
if (!this->m_hasOnes) {
MatrixS& templates=getTemplates(space,directions);
MatrixS vectors=(templates.cols()>0) ? templates : init.getDirections();//TODO: makeLogahedral?
MatrixS faces=vectors.transpose();
MatrixS supports(vectors.cols(),1);
MatrixS dynamics=(space==eNormalSpace) ? this->m_dynamics.transpose() : m_pseudoEigenValues.transpose();
AbstractPolyhedra<scalar>& input=m_transformedInputs.getPolyhedra(space);
MatrixS inSupports=input.getSupports();
MatrixS accumInSupports=MatrixS::Zero(supports.rows(),1);
for (int i=1;i<=iteration;i++) {
if (!input.maximiseAll(vectors,inSupports)) processError(input.getName());
accumInSupports+=inSupports;
vectors=dynamics*vectors;
if (!init.maximiseAll(vectors,supports)) processError(init.getName());
supports+=accumInSupports;
}
m_reach.load(faces,supports);
}
else if (retemplate) {
MatrixS& templates=getTemplates(space,directions);
MatrixS vectors=templates;
MatrixS supports;
MatrixS inSupports=MatrixS::Zero(vectors.cols(),1);
MatrixS dynamics=getPseudoDynamics(1,false,space).transpose();
for (int i=1;i<=iteration;i++) {
if (!input.maximiseAll(vectors,supports)) processError(input.getName());
inSupports+=supports;
vectors=dynamics*vectors;
}
if (!init.maximiseAll(vectors,supports)) processError(init.getName());
supports+=inSupports;
MatrixS faces=templates.transpose();
m_reach.load(faces,supports);
}
else {
MatrixS matrix=getPseudoDynamics(1,false,space);
for (int i=1;i<=iteration;i++) {
m_reach.transform(matrix);
m_reach.add(input);
}
// MatrixS& templates=getTemplates(space,directions);
// if (retemplate && templates.cols()>0) m_reach.retemplate(templates);
}
if (keep) m_pReachSet->load(m_reach,Polyhedra<scalar>::ms_emptyMatrix,Polyhedra<scalar>::ms_emptyMatrix,space);
if (this->ms_trace_dynamics>=eTraceDynamics) m_reach.logTableau();
return m_reach;
}
MatrixS matrix=getPseudoDynamics(iteration,false,space);
AbstractPolyhedra<scalar>& result=init.getTransformedPolyhedra(m_reach,matrix,Polyhedra<scalar>::ms_emptyMatrix);
if (this->ms_trace_dynamics>=eTraceDynamics) {
buffer << " Dynamics";
ms_logger.logData(matrix,buffer.str());
}
if ((iteration>0) && (inputType>eNoInputs)) {
if (inputType==eParametricInputs) {
matrix=getPseudoDynamics(iteration,true,space);
AbstractPolyhedra<scalar> uPrime(input,matrix);
result.add(uPrime);
if (result.ms_trace_tableau>=eTraceTransforms) {
uPrime.setName("+Inputs");
uPrime.logVertices(true);
result.logVertices(true);
uPrime.logTableau();
result.logTableau();
}
}
else {
AbstractPolyhedra<scalar>& input=m_transformedInputs.getPolyhedra(eSingularSpace,m_conjugatePair,m_jordanIndex);
matrix=getPseudoDynamics(iteration,true,eSingularSpace);
AbstractPolyhedra<scalar> uPrime(input,matrix);
result.addRounded(uPrime,m_conjugatePair,m_jordanIndex);
if (!inEigenSpace) result.transform(m_pseudoEigenVectors,m_invPseudoEigenVectors);
}
}
MatrixS& templates=getTemplates(space);
if (retemplate && templates.cols()>0) result.retemplate(templates);
if (keep) m_pReachSet->load(result,Polyhedra<scalar>::ms_emptyMatrix,Polyhedra<scalar>::ms_emptyMatrix,space);
if (result.ms_trace_tableau>=eTraceTableau) result.logTableau();
return result;
}
/// Creates a combinatorial matrix A-B
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS DynamicalSystem<scalar>::combineAminB(const MatrixS& A,const MatrixS& B,bool isVector)
{
if (isVector) {
if ((A.rows()!=B.rows()) || (A.rows()!=m_dimension)) return A;
int col=0;
MatrixS result(m_dimension,A.cols()*B.cols());
for (int col1=0;col1<A.cols();col1++) {
for (int col2=0;col2<B.cols();col2++) {
result.col(col++)=A.col(col1)-B.col(col2);
}
}
return result;
}
if ((A.cols()!=B.cols()) || (A.cols()!=m_dimension)) return A;
int row=0;
MatrixS result(A.rows()*B.rows(),m_dimension);
for (int row1=0;row1<A.rows();row1++) {
for (int row2=0;row2<B.rows();row2++) {
result.row(row++)=A.row(row1)-B.row(row2);
}
}
return result;
}
/// Creates a combinatorial matrix with rows/cols A_i B_j ordered by templates
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS DynamicalSystem<scalar>::combineAB(const MatrixS& A,const MatrixS& B,const int templateSz,const int AvertexSz,const int BvertexSz,const bool isVector)
{
if (isVector) {
MatrixS result(A.rows()+B.rows(),A.cols()*BvertexSz);
for (int i=0;i<templateSz;i++) {
for (int j=0;j<AvertexSz;j++) {
int col=i*AvertexSz+j;
for (int k=0;k<BvertexSz;k++) {
result.block(0,col*BvertexSz+k,A.rows(),1)=A.col(col);
}
result.block(A.rows(),col*BvertexSz,B.rows(),BvertexSz)=B.block(0,i*BvertexSz,B.rows(),BvertexSz);
}
}
return result;
}
MatrixS result(A.rows()*BvertexSz,A.cols()+B.cols());
for (int i=0;i<templateSz;i++) {
for (int j=0;j<AvertexSz;j++) {
int row=i*AvertexSz+j;
for (int k=0;k<BvertexSz;k++) {
result.block(row*BvertexSz+k,0,1,A.cols())=A.row(row);
}
result.block(row*BvertexSz,A.cols(),BvertexSz,B.cols())=B.block(i*BvertexSz,0,BvertexSz,B.rows());
}
}
return result;
}
/// Creates a combinatorial matrix with rows A_i \cdot B_i
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS DynamicalSystem<scalar>::combineAB(const MatrixS& A,const MatrixS& B)
{
if (A.cols()!=B.cols()) return MatrixS(0,0);
MatrixS result(A.rows()*B.rows(),A.cols());
for (int i=0;i<A.rows();i++) {
for (int j=0;j<B.rows();j++) {
int row=i*B.rows()+j;
for (int col=0;col<A.cols();col++) {
result.coeffRef(row,col)=A.coeff(i,col)*B.coeff(j,col);
}
}
}
return result;
}
/// retrieve the kronecker product of A and B
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS DynamicalSystem<scalar>::kronecker(const MatrixS& A,const MatrixS& B,const bool transA,const bool transB)
{
int arows=transA ? A.cols() : A.rows();
int acols=transA ? A.rows() : A.cols();
int brows=transB ? B.cols() : B.rows();
int bcols=transB ? B.rows() : B.cols();
MatrixS result(arows*brows,acols*bcols);
for (int i=0;i<arows;i++) {
for (int j=0;j<brows;j++) {
int row=i*brows+j;
for (int k=0;k<acols;k++) {
for (int l=0;l<bcols;l++) {
int col=k*bcols+l;
if (transA)
result.coeffRef(row,col)=transB ? A.coeff(k,i)*B.coeff(l,j) : A.coeff(k,i)*B.coeff(j,l);
else
result.coeffRef(row,col)=transB ? A.coeff(i,k)*B.coeff(l,j) : A.coeff(i,k)*B.coeff(j,l);
}
}
}
}
return result;
}
/// Creates a template matrix for the given logahedral dimension
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS& DynamicalSystem<scalar>::makeLogahedralTemplates(int precision,space_t space,int dimension,MatrixS &logTemplates)
{
precision++;
if (precision<=1) logTemplates.resize(dimension,2*dimension+2*precision*(dimension-1)*dimension);
else logTemplates.resize(dimension,2*dimension+(4*precision-2)*(dimension-1)*dimension);
logTemplates.block(0,0,dimension,dimension)=MatrixS::Identity(dimension,dimension);
logTemplates.block(0,dimension,dimension,dimension)=-MatrixS::Identity(dimension,dimension);
if (precision<=0) return logTemplates;
int pos=2*dimension;
for (int row=0;row<dimension-1;row++) {
int size=dimension-row-1;
logTemplates.block(row,pos,1,2*size)=MatrixS::Ones(1,2*size);
logTemplates.block(row+1,pos,size,size)=MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row+1,pos,size,size)=-MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row,pos,1,2*size)=-MatrixS::Ones(1,2*size);
logTemplates.block(row+1,pos,size,size)=MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row+1,pos,size,size)=-MatrixS::Identity(size,size);
pos+=size;
if (pos<logTemplates.cols()) logTemplates.block(row,pos,1,logTemplates.cols()-pos)=MatrixS::Zero(1,logTemplates.cols()-pos);
}
for (int i=2;i<=precision;i++) {
for (int row=0;row<dimension-1;row++) {
int size=dimension-row-1;
logTemplates.block(row,pos,1,2*size)=i*MatrixS::Ones(1,2*size);
logTemplates.block(row+1,pos,size,size)=MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row+1,pos,size,size)=-MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row,pos,1,2*size)=-i*MatrixS::Ones(1,2*size);
logTemplates.block(row+1,pos,size,size)=MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row+1,pos,size,size)=-MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row,pos,1,2*size)=MatrixS::Ones(1,2*size);
logTemplates.block(row+1,pos,size,size)=i*MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row+1,pos,size,size)=-i*MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row,pos,1,2*size)=-MatrixS::Ones(1,2*size);
logTemplates.block(row+1,pos,size,size)=i*MatrixS::Identity(size,size);
pos+=size;
logTemplates.block(row+1,pos,size,size)=-i*MatrixS::Identity(size,size);
pos+=size;
if (pos<logTemplates.cols()) logTemplates.block(row,pos,1,logTemplates.cols()-pos)=MatrixS::Zero(1,logTemplates.cols()-pos);
}
}
if (ms_trace_dynamics>=eTraceAll) ms_logger.logData(logTemplates,"Template base");
if (space==eNormalSpace) {
MatrixS transformedTemplates=m_pseudoEigenVectors.transpose()*logTemplates;
if (ms_trace_dynamics>=eTraceAll) {
ms_logger.logData(m_pseudoEigenVectors,"Template Transform");
ms_logger.logData(transformedTemplates,"Transformed Templates");
}
logTemplates=transformedTemplates;
}
return logTemplates;
}
/// Creates a template matrix for the given logahedral dimension
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS& DynamicalSystem<scalar>::makeSphericalTemplates(int precision,int dimension,MatrixS &logTemplates,bool normalized)
{
if (precision<2) precision=2;
if ((m_dimension==2) && (precision<3)) precision=3;
if (precision>30) precision=30;
precision=(2<<precision);
if (dimension==2) {
logTemplates.resize(dimension,precision);
for (int i=0;i<precision;i++) {
logTemplates.coeffRef(0,i)=func::cosine(i*func::ms_2_pi/precision);
logTemplates.coeffRef(1,i)=func::sine(i*func::ms_2_pi/precision);
}
if (normalized) logTemplates/=func::toLower(func::cosine(func::ms_pi/precision));
}
else if ((dimension>2) && (dimension<6)) {
logTemplates.resize(dimension,130);
std::stringstream fileName;
std::stringstream buffer;
std::ifstream file;
fileName << "SphericalPoints" << dimension << "D.h";
file.open(fileName.str().data());
if (!file.is_open()) return logTemplates;
buffer << file.rdbuf();
file.close();
std::string str=buffer.str();
MatrixS load;
ms_logger.StringToMat(load,str);
logTemplates=load.transpose();
if (normalized) logTemplates/=func::cosine(func::ms_pi/9);//The files have a minimum angle of 20 between points
}
return logTemplates;
}
/// Retrieves the number of non-correlated dimensions in the eigenspace
template <class scalar>
int DynamicalSystem<scalar>::getRoundedDimension()
{
int dimension=m_dimension;
int roundDimension=0;
for (int col=0;col<m_dimension;col++)
{
if ((m_jordanIndex[col+1]>0) || (m_conjugatePair[col]>col)) dimension--;
else if ((m_jordanIndex[col]>0) || (m_conjugatePair[col]>=0)) roundDimension++;
}
return dimension;
}
/// Retrieves the number of radii dimensions in the eigenspace (only one per conjugate pair)
template <class scalar>
int DynamicalSystem<scalar>::getNormedDimension()
{
int dimension=m_dimension;
for (int col=0;col<m_dimension;col++)
{
if (m_conjugatePair[col]>col) dimension--;
}
m_normedJordanIndex.resize(2*dimension);
m_normedOnes.resize(2*dimension);
int pos=0;
for (int col=0;col<m_dimension;col++)
{
if (m_conjugatePair[col]>col) continue;
m_normedJordanIndex[pos]=m_jordanIndex[col];
m_normedJordanIndex[pos+dimension]=m_jordanIndex[col];
m_normedOnes[pos]=m_isOne[col];
m_normedOnes[pos+dimension]=m_isOne[col];
pos++;
}
return dimension;
}
/// Retrieves an abstraction that has circular faces in the rotating axis and jordan blocks
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS& DynamicalSystem<scalar>::getRoundedDirections(MatrixS &result,const MatrixS &vectors,bool transposed)
{
if (transposed) {
result.resize(vectors.rows(),getRoundedDimension());
int pos=0;
for (int col=0;col<vectors.cols();col++)
{
if ((m_conjugatePair[col]<0) && (m_jordanIndex[col+1]<=0)) {
result.col(pos)=vectors.col(col);
}
else {
for (int row=0;row<vectors.rows();row++) {
scalar value=func::squared(vectors.coeff(row,col));//*vectors.coeff(row,col);
for (int col2=col+1;(m_conjugatePair[col2]>=0) || (m_jordanIndex[col2]>0);col2++) {
value+=func::squared(vectors.coeff(row,col2));
// func::madd(value,vectors.coeff(row,col2),vectors.coeff(row,col2));
}
result.coeffRef(row,pos)=sqrt(value);
}
col++;
while ((m_conjugatePair[col]>=0) || (m_jordanIndex[col]>0)) col++;
col--;
}
pos++;
}
return result;
}
result.resize(getRoundedDimension(),vectors.cols());
int pos=0;
for (int row=0;row<vectors.rows();row++)
{
if ((m_conjugatePair[row]<0) && (m_jordanIndex[row+1]<=0)) {
result.row(pos)=vectors.row(row);
}
else {
for (int col=0;col<vectors.cols();col++) {
scalar value=func::squared(vectors.coeff(row,col));//*vectors.coeff(row,col);
for (int row2=row+1;(m_conjugatePair[row2]>=0) || (m_jordanIndex[row2]>0);row2++) {
value+=func::squared(vectors.coeff(row2,col));
// func::madd(value,vectors.coeff(row2,col),vectors.coeff(row2,col));
}
result.coeffRef(pos,col)=sqrt(value);
}
row++;
while ((m_conjugatePair[row]>=0) || (m_jordanIndex[row]>0)) row++;
row--;
}
pos++;
}
return result;
}
/// Retrieves an abstraction that has circular faces in the rotating axis and jordan blocks
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS& DynamicalSystem<scalar>::getNormedDirections(MatrixS &result,const MatrixS &vectors,bool transposed)
{
if (transposed) {
result.resize(vectors.rows(),getNormedDimension());
int pos=0;
for (int col=0;col<vectors.cols();col++)
{
if (m_conjugatePair[col]<0) {
result.col(pos)=vectors.col(col);
}
else {
for (int row=0;row<vectors.rows();row++) {
scalar value=func::squared(vectors.coeff(row,col))+func::squared(vectors.coeff(row,col+1));
result.coeffRef(row,pos)=sqrt(value);
}
col++;
}
pos++;
}
return result;
}
result.resize(getNormedDimension(),vectors.cols());
int pos=0;
for (int row=0;row<vectors.rows();row++)
{
if (m_conjugatePair[row]<0) {
result.row(pos)=vectors.row(row);
}
else {
for (int col=0;col<vectors.cols();col++) {
scalar value=func::squared(vectors.coeff(row,col))+func::squared(vectors.coeff(row+1,col));
result.coeffRef(pos,col)=sqrt(value);
}
row++;
}
pos++;
}
return result;
}
/// Creates a template matrix for the reach set directions at the given iteration
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS& DynamicalSystem<scalar>::makeInverseTemplates(int iteration,space_t space)
{
MatrixS inverse=this->getPoweredPseudoEigenValues(iteration).inverse();
if (space==eNormalSpace) {
inverse=m_invPseudoEigenVectors*(inverse*m_pseudoEigenVectors);
}
m_logTemplates=inverse.transpose()*m_initialState.getPolyhedra(space).getDirections();
return m_logTemplates;
}
/// Retrieves the abstract vector set for a given template set
template <class scalar>
typename JordanMatrix<scalar>::MatrixS DynamicalSystem<scalar>::getCombinedVectors(MatrixS &vectors,const MatrixS& templates,AbstractPolyhedra<scalar> &inputs,const MatrixS &inputVertices)
{
int nV=m_numVertices;
if (m_inputType==eVariableInputs) {
AbstractPolyhedra<scalar> inputCopy(inputs);
AbstractPolyhedra<scalar> roundInputs;
inputCopy.getRounded(m_conjugatePair,m_jordanIndex,roundInputs);
//roundInputs.transform(this->m_invIminF,this->m_IminF);
MatrixS varTemplates=roundInputs.getRoundedDirections(templates,m_conjugatePair,m_jordanIndex);
int numInputVertices=roundInputs.getVertices().rows();
m_numVertices*=numInputVertices;
MatrixS inputVectors=roundInputs.getAbstractVertices(varTemplates);
return combineAB(vectors,inputVectors,templates.cols(),nV,numInputVertices,true);
}
else if (m_hasOnes) {
MatrixS inputVectors=inputs.getAbstractVertices(templates,m_conjugatePair,m_jordanIndex,inputVertices);
int numInputVertices=inputVertices.rows();
m_numVertices*=numInputVertices;
return combineAB(vectors,inputVectors,templates.cols(),nV,numInputVertices,true);
}
return vectors;
}
/// Retrieves the parametric input vertices for the current problem configuration
template <class scalar>
const typename JordanMatrix<scalar>::MatrixS& DynamicalSystem<scalar>::getInputVertices(space_t space,bool fromSource)
{
if (fromSource && (m_inputType==eParametricInputs)) {
MatrixS& trueInputVertices=m_inputs.getVertices();
if (trueInputVertices.rows()<=0) processError(m_inputs.getName());
trueInputVertices*=m_sensitivity.transpose();
if (space>eNormalSpace) trueInputVertices*=m_invPseudoEigenVectors.transpose();
return trueInputVertices;
}
AbstractPolyhedra<scalar> &inputsSource=m_transformedInputs.getPolyhedra(space);
const MatrixS& inputVertices=(m_inputType==eParametricInputs) ? inputsSource.getVertices() : inputsSource.getCentre();
if (inputVertices.rows()<=0) processError(inputsSource.getName());
return inputVertices;
}
/// Retrieves the parametric accelerated input vertices for the current problem configuration
template <class scalar>
typename JordanMatrix<scalar>::MatrixS& DynamicalSystem<scalar>::getAccelVertices()
{
m_accelVertices=getInputVertices()*this->m_pseudoInvIminJ.transpose();
if (m_hasOnes && (m_inputType==eVariableInputs)) {
for (int i=0;i<m_accelVertices.cols();i++) {
if (m_isOne[i]) m_accelVertices.coeffRef(i,0)=0;
}
}
}
/// Retrieves the support set for the inputs
template <class scalar>
typename JordanMatrix<scalar>::MatrixS& DynamicalSystem<scalar>::getAccelInSupports(powerS iteration, int precision,const MatrixS& templates)
{
//getAccelVertices() must be called first (not called here for optimization)
AbstractPolyhedra<scalar> &inputsSource=m_transformedInputs.getPolyhedra(eEigenSpace);
if (m_hasOnes && (m_inputType==eVariableInputs)) {
const MatrixS& inputVertices=getInputVertices();
for (int i=0;i<m_accelVertices.cols();i++) {
if (m_isOne[i]) {
m_accelVertices.coeffRef(0,i)=inputVertices.coeff(0,i);
}
}
m_abstractInputVertices=MatrixS(2*m_dimension,templates.cols());
m_abstractInputVertices.topRows(m_dimension)=MatrixS::Zero(m_dimension,templates.cols());
m_abstractInputVertices.bottomRows(m_dimension)=inputsSource.getAbstractVertices(templates,m_conjugatePair,m_jordanIndex,m_accelVertices);
m_inputType=eParametricInputs;
AbstractPolyhedra<scalar>& inputDynamics=getAbstractDynamics(iteration,precision,eParametricInputs);
m_inputType=eVariableInputs;
MatrixS supports;
inputDynamics.maximiseAll(m_abstractInputVertices,supports);
m_accelInSupports=supports.transpose();
}
else m_accelInSupports=m_accelVertices*templates;
if (this->ms_trace_dynamics>=eTraceAbstraction) ms_logger.logData(m_accelInSupports,"Input Supports",true);
return m_accelInSupports;
}
/// Retrieves the support set for the inputs
template <class scalar>
void DynamicalSystem<scalar>::mergeAccelInSupports(MatrixS &supports,int numTemplates)
{
if (!m_hasOnes || (m_inputType==eVariableInputs)) {
for (int row=0;row<numTemplates;row++) {
int pos=row*m_numVertices;
supports.coeffRef(pos,0)+=m_accelInSupports.coeff(0,row);
for (int point=1;point<m_numVertices;point++) {
supports.coeffRef(pos+point,0)+=m_accelInSupports.coeff(point%m_accelInSupports.rows(),row);
}
}
}
}
/// Retrieves the abstract vector set for a given template set
template <class scalar>
typename JordanMatrix<scalar>::MatrixS& DynamicalSystem<scalar>::getAbstractVertices(const MatrixS& templates,MatrixS &vectors,int &numVertices)
{
AbstractPolyhedra<scalar>& init=m_initialState.getPolyhedra(eEigenSpace);
const MatrixS& vertices=init.getVertices(true);
if (vertices.rows()<=0) processError(init.getName());
switch (m_inputType) {
case eNoInputs:
vectors=init.getAbstractVertices(templates,m_conjugatePair,m_jordanIndex);
numVertices=vertices.rows();
break;
default: {
getAccelVertices();
AbstractPolyhedra<scalar> &inputsSource=m_transformedInputs.getPolyhedra(eEigenSpace);
MatrixS combinedVertices=m_hasOnes ? vertices : combineAminB(vertices,m_accelVertices,false);
MatrixS initVectors=init.getAbstractVertices(templates,m_conjugatePair,m_jordanIndex,combinedVertices);
numVertices=combinedVertices.rows();
vectors=getCombinedVectors(initVectors,templates,inputsSource,m_accelVertices);
if (this->ms_trace_dynamics>=eTraceAbstraction) {
ms_logger.logData(templates,"Templates",true);
ms_logger.logData(vertices,"Init Vertices");
ms_logger.logData(getInputVertices(),"Input Vertices",true);
ms_logger.logData(m_accelVertices,"Accel Vertices");
ms_logger.logData(combinedVertices,"Vertices");
ms_logger.logData(initVectors,"PreVectors",true);
ms_logger.logData(vectors,"FullVectors",true);
}
}
}
return vectors;
}
template <class scalar>
void DynamicalSystem<scalar>::traceSupports(const MatrixS &templates,MatrixS &supports,AbstractPolyhedra<scalar>& dynamics,const MatrixS &vectors)
{
if (m_inputType==eNoInputs) {
ms_logger.logData(vectors,supports,"Combined No Inputs:",true);
return;
}
supports.conservativeResize(supports.rows(),(m_inputType==eParametricInputs) ? 4 : 3);
supports.col(1)=supports.col(0);
MatrixS vertexSupports=dynamics.vertexMaximize(vectors);
if (vertexSupports.rows()==supports.rows()) {
supports.col(2)=vertexSupports;
}
else {
supports.col(2)=MatrixS::Zero(supports.rows(),1);
ms_logger.logData("Failed to find Vertex Supports");
}
if (m_inputType==eParametricInputs) {
for (int row=0;row<templates.cols();row++) {
int pos=row*m_numVertices;
supports.coeffRef(pos,3)+=m_accelInSupports.coeff(0,row);
for (int point=1;point<m_numVertices;point++) {
supports.coeffRef(pos+point,3)+=m_accelInSupports.coeff(point%m_accelInSupports.rows(),row);
}
}
}
}
template <class scalar>
void DynamicalSystem<scalar>::mergeAbstractSupports(const MatrixS &templates,MatrixS &supports)
{
if (m_inputType==eNoInputs) {
for (int row=0;row<templates.cols();row++) {
scalar value=supports.coeff(row*m_numVertices,0);
for (int vRow=1;vRow<m_numVertices;vRow++) {
if (value<supports.coeff(row*m_numVertices+vRow,0)) value=supports.coeff(row*m_numVertices+vRow,0);
}
supports.coeffRef(row,0)=value;
}
}
else {
for (int row=0;row<templates.cols();row++) {
int pos=row*m_numVertices;
for (int point=1;point<m_numVertices;point++) {
if (func::toUpper(supports.coeff(pos+point,0))>func::toUpper(supports.coeff(pos,0))) {
supports.coeffRef(pos,0)=supports.coeff(pos+point,0);
}
}
supports.coeffRef(row,0)=supports.coeff(row*m_numVertices,0);
}
}
supports.conservativeResize(templates.cols(),1);
}
/// Retrieves an abstractreachtube projected across a guard
template <class scalar>
void DynamicalSystem<scalar>::getGuardedReachTube(AbstractPolyhedra<scalar>& reachTube,space_t space)
{
reachTube.intersect(m_guard.getPolyhedra(space));
Polyhedra<scalar> next;
reachTube.getTransformedPolyhedra(next,this->getBaseDynamics(space));
next.add(m_transformedInputs.getPolyhedra(space));
reachTube.merge(next);
}
/// Retrieves the reach tube at the given iteration
template <class scalar>
AbstractPolyhedra<scalar>& DynamicalSystem<scalar>::getAbstractReachTube(powerS iteration,int precision,int directions,inputType_t inputType,space_t space,bool guarded)
{
m_reachTime=-1;
boost::timer timer;
if (m_idimension==0) inputType=eNoInputs;
setInputType(inputType);
if (iteration<0) iteration=-iteration;
if (iteration==0) iteration=calculateIterations(m_initialState.getPolyhedra(eEigenSpace),inputType);
if (m_hasMultiplicities) this->calculateBoundedEigenError(calculateMaxIterations());
if (guarded) iteration--;
if (iteration<=0) {
m_pAbstractReachTube->load(m_initialState.getPolyhedra(),Polyhedra<scalar>::ms_emptyMatrix);
AbstractPolyhedra<scalar>& result=m_pAbstractReachTube->getPolyhedra(space);
if (guarded) getGuardedReachTube(result,space);
m_reachTime=timer.elapsed()*1000;
result.setCalculationTime(m_reachTime);
if (ms_trace_time) ms_logger.logData(m_reachTime,"Abstract Reach Time: ",true);
if (m_outputSensitivity.cols()==0) m_outputs.copy(result);
else result.getTransformedPolyhedra(m_outputs,m_outputSensitivity);
return result;
}
AbstractPolyhedra<scalar>& dynamics=getAbstractDynamics(iteration,precision,inputType);
AbstractPolyhedra<scalar>& init=m_initialState.getPolyhedra(eEigenSpace);
MatrixS& templates=getTemplates(eEigenSpace,directions);
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Abstract Vertices: ",true);
MatrixS supports;
MatrixS &vectors=getAbstractVertices(templates);
if (!dynamics.maximiseAll(vectors,supports)) processError(dynamics.getName());
if (inputType>eNoInputs) getAccelInSupports(iteration,precision,templates);
if (this->ms_trace_dynamics>=eTraceAll) {
traceSupports(templates,supports,dynamics,vectors);
}
if (inputType>eNoInputs) {
mergeAccelInSupports(supports,templates.cols());
if (this->ms_trace_dynamics>=eTraceAll) {
ms_logger.logData(vectors,supports,"Combined",true);
}
}
mergeAbstractSupports(templates,supports);
MatrixS faces=templates.transpose();
m_pAbstractReachTube->mergeLoad(init,faces,supports,eEigenSpace);
AbstractPolyhedra<scalar>& result=m_pAbstractReachTube->getPolyhedra(space);
if (guarded) getGuardedReachTube(result,space);
if (this->ms_trace_dynamics>=eTraceAbstraction) result.logTableau();
m_reachTime=timer.elapsed()*1000;
result.setCalculationTime(m_reachTime);
if (ms_trace_time) ms_logger.logData(m_reachTime,"Abstract Reach Time: ",true);
getOutputReachTube(result, directions);
return result;
}
/// Retrieves the output reach tube given a state-space reach tube
template <class scalar>
AbstractPolyhedra<scalar>& DynamicalSystem<scalar>::getOutputReachTube(AbstractPolyhedra<scalar>& reachTube, int precision)
{
if (m_outputSensitivity.cols()==0) m_outputs.copy(reachTube);
else if (m_outputSensitivity.rows()<m_dimension) {
MatrixS outTemplates;
int outDimension=m_outputSensitivity.rows();
if (outDimension==1) {
outTemplates=MatrixS::Ones(1,2);
outTemplates.coeffRef(0,1)=-ms_one;
}
else makeLogahedralTemplates(precision,eEigenSpace,outDimension,outTemplates);
m_outputs.copy(reachTube);
m_outputs.vertexTransform(m_outputSensitivity,outTemplates);
}
else reachTube.getTransformedPolyhedra(m_outputs,m_outputSensitivity);
return m_outputs;
}
/// Retrieves the reach tube at the given iteration
template <class scalar>
AbstractPolyhedra<scalar>& DynamicalSystem<scalar>::getIterativeReachTube(powerS iteration,inputType_t inputType,space_t space,int directions)
{
m_reachTime=-1;
boost::timer timer;
if (m_hasMultiplicities) this->calculateBoundedEigenError(calculateMaxIterations(iteration));
AbstractPolyhedra<scalar>& init=m_initialState.getPolyhedra(space);
AbstractPolyhedra<scalar>& result=init.getTransformedPolyhedra(Polyhedra<scalar>::ms_emptyMatrix);
result.setName("Reach Tube");
MatrixS& templates=getTemplates(space,directions);
MatrixS vectors=templates.cols()>0 ? templates : init.getDirections();
MatrixS faces=vectors.transpose();
MatrixS supports(vectors.cols(),1);
MatrixS accumSupports;
init.maximiseAll(vectors,accumSupports);
MatrixS dynamics=(space==eNormalSpace) ? this->m_dynamics.transpose() : m_pseudoEigenValues.transpose();
switch (inputType) {
case eNoInputs: {
for (int i=1;i<=iteration;i++) {
vectors=dynamics*vectors;
if (!init.maximiseAll(vectors,supports)) processError(init.getName());
if (this->ms_trace_dynamics>=eTraceAll) {
ms_logger.logData(i,"Iteration",true);
ms_logger.logData(supports);
}
for (int j=0;j<supports.rows();j++) {
if (func::toUpper(supports.coeff(j,0))>func::toUpper(accumSupports.coeff(j,0))) {
accumSupports.coeffRef(j,0)=supports.coeff(j,0);
}
}
}
break;
}
case eVariableInputs: {
AbstractPolyhedra<scalar> &input=m_transformedInputs.getPolyhedra(space);
MatrixS inSupports=input.getSupports();
MatrixS accumInSupports=MatrixS::Zero(supports.rows(),1);
for (int i=1;i<=iteration;i++) {
if (!input.maximiseAll(vectors,inSupports)) processError(input.getName());
accumInSupports+=inSupports;
vectors=dynamics*vectors;
if (!init.maximiseAll(vectors,supports)) processError(init.getName());
supports+=accumInSupports;
for (int j=0;j<supports.rows();j++) {
if (func::toUpper(supports.coeff(j,0))>func::toUpper(accumSupports.coeff(j,0))) {
accumSupports.coeffRef(j,0)=supports.coeff(j,0);
}
}
}
break;
}
case eParametricInputs: {
if (!m_hasOnes) {
AbstractPolyhedra<scalar> &input=m_transformedStateInputs.getPolyhedra(space);
MatrixS inSupports(vectors.cols(),1);
MatrixS origVectors=vectors;
for (int i=1;i<=iteration;i++) {
vectors=dynamics*vectors;
if (!init.maximiseAll(vectors,supports)) processError(init.getName());
MatrixS inVectors=origVectors-vectors;
if (!input.maximiseAll(inVectors,inSupports)) processError(input.getName());
supports+=inSupports;
for (int j=0;j<supports.rows();j++) {
if (func::toUpper(supports.coeff(j,0))>func::toUpper(accumSupports.coeff(j,0))) {
accumSupports.coeffRef(j,0)=supports.coeff(j,0);
}
}
}
break;
}
}
default: {
m_subReach.copy(m_initialState.getPolyhedra(eEigenSpace));
MatrixS& templates=getTemplates(eEigenSpace,directions);
result.retemplate(templates);
for (int i=1;i<=iteration;i++) {
getReachSet(i,m_initialState.getPolyhedra(eEigenSpace),inputType,false,true,directions,true,false);
// getReachSet(1,m_subReach,inputType,false,true,directions,false,false);
m_subReach.copy(m_reach);
result.merge(m_reach,false);
}
if (space==eNormalSpace) {
result.transform(m_pseudoEigenVectors,m_invPseudoEigenVectors);
}
vectors=result.getDirections();
accumSupports=result.getSupports();
}
}
result.load(faces,accumSupports);
AbstractPolyhedra<scalar>& reachTube=m_pReachTube->load(result,Polyhedra<scalar>::ms_emptyMatrix,Polyhedra<scalar>::ms_emptyMatrix,space);
m_reachTime=timer.elapsed()*1000;
reachTube.setCalculationTime(m_reachTime);
if (ms_trace_time) ms_logger.logData(m_reachTime,"LGG Reach Time: ",true);
return reachTube;
}
template <class scalar>
int DynamicalSystem<scalar>::findBrokenOverapproximation()
{
Polyhedra<scalar> &abstract=m_pAbstractReachTube->getPolyhedra();
MatrixS templates=abstract.getDirections();
MatrixS inSupports;
m_pReachTube->getPolyhedra().maximiseAll(templates,inSupports);
MatrixS outSupports=abstract.getSupports();
if (outSupports.rows()<inSupports.rows()) return 0;
for (int i=0;i<inSupports.rows();i++) {
if (func::toUpper(inSupports.coeff(i,0))>func::toUpper(outSupports.coeff(i,0))) {
return i;
}
}
if (outSupports.rows()>inSupports.rows()) return inSupports.rows();
return -1;
}
template <class scalar>
int DynamicalSystem<scalar>::loadSensitivities(std::string &data,size_t pos)
{
boost::timer timer;
commands_t command;
pos=ms_logger.getCommand(command,data,pos);
m_sensitivity.resize(m_dimension,m_idimension);
int result=ms_logger.StringToMat(m_sensitivity,data,pos);
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Sensitivity time:",true);
return result;
}
template <class scalar>
int DynamicalSystem<scalar>::loadOutputSensitivities(std::string &data,size_t pos)
{
boost::timer timer;
commands_t command;
pos=ms_logger.getCommand(command,data,pos);
m_outputSensitivity.resize(m_odimension,m_dimension);
int result=ms_logger.StringToMat(m_outputSensitivity,data,pos);
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Output Sensitivity time:",true);
return result;
}
template <class scalar>
void DynamicalSystem<scalar>::setEigenSpace()
{
m_initialState.setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
m_transformedInputs.setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
m_transformedStateInputs.setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
m_guard.setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
m_safeReachTube.setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
m_pReachSet->setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
m_pReachTube->setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
m_pAbstractReachTube->setEigenSpace(m_pseudoEigenVectors,m_invPseudoEigenVectors);
}
/// Processes a calculation error either executing a throw or tagging an imprecision
template <class scalar>
void DynamicalSystem<scalar>::processError(std::string source)
{
ms_logger.logData("Error processing ",false);
ms_logger.logData(source);
if (func::ms_formal) throw processingError;
func::ms_imprecise=true;
}
template <class scalar>
int DynamicalSystem<scalar>::loadDynamics(const std::string &data,size_t pos)
{
boost::timer timer;
commands_t command;
pos=ms_logger.getCommand(command,data,pos);
int result=JordanMatrix<scalar>::load(data,pos);
if (result>0) setEigenSpace();
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Dynamics time:",true);
return result;
}
/// Loads the LTI dynamics of an armax model
template <class scalar>
int DynamicalSystem<scalar>::loadARMAXModel(std::string &data,size_t pos)
{
commands_t command;
pos=ms_logger.getCommand(command,data,pos);
MatrixS ARMAX(2,m_dimension+1);
bool reverse=(data.at(pos)=='r');
if (reverse) pos++;
int result=ms_logger.StringToMat(ARMAX,data,pos);
if (result<0) return result;
if (reverse) {
ARMAX.row(0).reverseInPlace();
scalar temp;
for (int i=0;i<((m_dimension+1)>>1);i++) {
temp=ARMAX.coeff(1,i);
ARMAX.coeffRef(1,i)=ARMAX.coeff(1,m_dimension-i);
ARMAX.coeffRef(1,m_dimension-i)=temp;
}
}
if (ARMAX.coeff(0,m_dimension)==func::ms_hardZero) ARMAX.coeffRef(0,m_dimension)=ms_one;
else if (ARMAX.coeff(0,m_dimension)!=ms_one) ARMAX/=ARMAX.coeff(0,m_dimension);
m_dynamics.block(0,1,m_dimension-1,m_dimension-1)=MatrixS::Identity(m_dimension-1,m_dimension-1);
m_dynamics.block(m_dimension-1,0,1,m_dimension)=-ARMAX.block(0,0,1,m_dimension);
m_sensitivity=MatrixS::Zero(m_dimension,1);//(m_idimension>0) ? m_idimension : 1);
m_sensitivity.coeffRef(m_dimension-1,0)=ms_one;
m_outputSensitivity.resize(1,m_dimension);
for (int i=0;i<m_dimension;i++) {
m_outputSensitivity.row(0)=ARMAX.block(1,0,1,m_dimension)+m_dynamics.row(m_dimension-1)*ARMAX.coeff(1,0);
}
if (!calculateJordanForm()) return -1;
if (result>0) setEigenSpace();
return result;
}
template <class scalar>
typename DynamicalSystem<scalar>::MatrixS& DynamicalSystem<scalar>::getTemplates(space_t space,int precision)
{
if (m_templates.cols()<=0) {
if (precision>-2) return makeLogahedralTemplates(precision,eNormalSpace);//TODO: check the space
return m_logTemplates;
}
if (space>eNormalSpace) return m_eigenTemplates;
return m_templates;
}
template <class scalar>
void DynamicalSystem<scalar>::processFiles(stringList &files,displayType_t displayType,space_t space,bool interval,optionList_t &options)
{
for (stringList::iterator i=files.begin();i!=files.end();i++) {
int pos=loadFromFile(*i);
if (pos<0) continue;
if (options.size()>0) processOptions(options,displayType,space,interval,false);
process(displayType,space,interval);
while (pos<m_source.length()) {
pos=m_source.find('|',pos);
if (pos<0) break;
pos=load(m_source,pos+1);
if (pos<0) break;
process(displayType,space,interval,true);
}
}
}
// Processes a problem stated by the inut options
template <class scalar>
int DynamicalSystem<scalar>::processOptions(optionList_t &options,displayType_t displayType,space_t space,bool interval,bool run)
{
if (options.size()<=0) return 0;
if (options[eParamStr].size()>0) {
if (ms_logger.StringToDim(m_paramValues,options[eParamStr])<0) return -1;
if (m_paramValues.coeff(eNumBits,0)>0) {
functions<mpfr::mpreal>::setDefaultPrec(m_paramValues.coeff(eNumBits,0));
}
traceDynamics((traceDynamics_t)m_paramValues.coeff(eTraceLevel,0));
traceSimplex((traceTableau_t)m_paramValues.coeff(eTraceLevel,1),(traceVertices_t)m_paramValues.coeff(eTraceLevel,2));
if (m_paramValues.coeff(eNumStates,0)>0) changeDimensions(m_paramValues.coeff(eNumStates,0),m_paramValues.coeff(eNumInputs,0)+m_paramValues.coeff(eNumVarInputs,0),m_paramValues.coeff(eNumOutputs,0),m_paramValues.coeff(eNumFeedbacks,0));
m_sensitivity.conservativeResize(m_paramValues.coeff(eNumStates,0),m_paramValues.coeff(eNumInputs,0)+m_paramValues.coeff(eNumVarInputs,0));
m_inputType=(m_paramValues.coeff(eNumVarInputs,0)>0) ? eVariableInputs : ((m_paramValues.coeff(eNumInputs,0)>0) ? eParametricInputs : eNoInputs);
}
if ((options[eARMAXStr].size()>0) && (loadARMAXModel(options[eARMAXStr])<0)) return -1;
if ((options[eGuardStr].size()>0) && (loadGuard(options[eGuardStr])<0)) return -1;
if ((options[sGuardStr].size()>0) && (loadSafeReachTube(options[sGuardStr])<0)) return -1;
if ((options[oGuardStr].size()>0) && (loadOutputGuard(options[oGuardStr])<0)) return -1;
if ((options[eDynamicsStr].size()>0) && (loadDynamics(options[eDynamicsStr])<0)) return -1;
if ((options[eInitStr].size()>0) && (loadInitialState(options[eInitStr])<0)) return -1;
if ((options[iSenseStr].size()>0) && (loadSensitivities(options[iSenseStr])<0)) return -1;
if ((options[eInputStr].size()>0) && (loadInputs(options[eInputStr])<0)) return -1;
if ((options[eTemplateStr].size()>0) && (loadTemplates(options[eTemplateStr])<0)) return -1;
if (run) process(displayType,space,interval);
return 0;
}
template <class scalar>
bool DynamicalSystem<scalar>::process(const displayType_t displayType,const space_t space,const bool interval,const bool append)
{
try {
int iter=m_paramValues.coeff(eNumSteps,0);
int maxIter=m_paramValues.coeff(eNumSteps,1);
int stepIter=m_paramValues.coeff(eNumSteps,2);
if (maxIter<=0) maxIter=iter+1;
if (stepIter<=0) stepIter=1;
int precision=m_paramValues.coeff(eLogFaces,0);
int maxPrecision=m_paramValues.coeff(eLogFaces,1);
int stepPrecision=m_paramValues.coeff(eLogFaces,2);
if (maxPrecision<=0) maxPrecision=precision;
if (stepPrecision<=0) stepPrecision=1;
int directions=m_paramValues.coeff(eLogDirections,0);
int maxDirections=m_paramValues.coeff(eLogDirections,1);
int stepDirections=m_paramValues.coeff(eLogDirections,2);
if (maxDirections<=0) maxDirections=directions;
if (stepDirections<=0) stepDirections=1;
int width=((maxIter-iter)/stepIter)*((maxPrecision-precision+1)/stepPrecision);
for (;directions<=maxDirections;directions+=stepDirections) {
MatrixS faces=makeLogahedralTemplates(directions,eEigenSpace).transpose();//TODO: the space in makelogahedral looks counterintuitive
MatrixS supports(faces.rows(),width);
//MatrixS dynamicSupports(0,width);
m_dynamicParams.resize(eNumFinalParameters,width);
int col=0;
for (iter=m_paramValues.coeff(eNumSteps,0);iter<maxIter;iter+=stepIter) {
for (precision=m_paramValues.coeff(eLogFaces,0);precision<=maxPrecision;precision+=stepPrecision) {
int iteration=(iter!=0) ? iter : calculateIterations(m_initialState.getPolyhedra(eEigenSpace),m_inputType);
getAbstractReachTube(iteration,precision,directions,m_inputType,space);
m_dynamicParams.coeffRef(eFinalIterations,col)=iteration;
m_dynamicParams.coeffRef(eFinalPrecision,col)=precision;
m_dynamicParams.coeffRef(eFinalLoadTime,col)=scalar(m_loadTime);
m_dynamicParams.coeffRef(eFinalReachTime,col)=scalar(m_reachTime);
supports.col(col++)=m_pAbstractReachTube->getPolyhedra(space).getSupports();
}
}
m_pAbstractReachTube->load(faces,supports,space);
save(displayType,space,interval,(directions>m_paramValues.coeff(eLogDirections,0)) || append);
}
}
catch(std::string error) {
ms_logger.logData("Error processing "+m_name);
ms_logger.logData(error);
}
}
template <class scalar>
void DynamicalSystem<scalar>::setName(const std::string name)
{
m_name=name;
}
/// Calculates the number of iterations necessary to supersede the guard
template <class scalar>
typename DynamicalSystem<scalar>::powerS DynamicalSystem<scalar>::calculateIterations(AbstractPolyhedra<scalar> &init,inputType_t inputType)
{
//Xn=J^nX0 + (J^n-I)U'
//p_Xn(-v)=p_X0(-J^nT v) + p_U'(-(J^n-I)^T v) <-h
//p_X0(-J^nT v) + p_U'(-(J^n-I)^T v) <-h
// \sum l^n (p_X0(-g_l)+p_U'( -g_l )) <-h+p_U'( g_l )
boost::timer timer;
findFrequencies();
if (isDivergent(true)) {
powerS result=calculateDivergentIterations(init,inputType);
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Calculate Iterations, Time",true);
return result;
}
MatrixS limits=m_guard.getPolyhedra(eEigenSpace).getSupports();
if (limits.rows()<=0) {
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Calculate Iterations, Time",true);
return func::ms_infPower;
}
MatrixS templates,roundVertices;
MatrixS faces=m_guard.getPolyhedra(eEigenSpace).getDirections();
getRoundedDirections(templates,faces);
if (templates.cols()==0) {
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Calculate Iterations, Time",true);
return func::ms_infPower;
}
const MatrixS& vertices=init.getVertices();
if (vertices.rows()<=0) processError(init.getName());
powerS low=0,high=func::ms_infPower;
refScalar logSigma=log10(this->m_maxSigma);
MatrixS lambdas=this->m_foldedEigenValues/this->m_maxSigma;
MatrixS poweredLambdas(1,lambdas.rows());
MatrixS supports;
int minPoints[templates.cols()];
if (inputType==eNoInputs) {
getRoundedDirections(roundVertices,vertices,true);
}
else {
AbstractPolyhedra<scalar>& inputs=m_transformedInputs.getPolyhedra(eEigenSpace);
const MatrixS& inputVertices=(inputType==eParametricInputs) ? inputs.getVertices() : inputs.getCentre();
if (inputVertices.rows()<=0) return func::ms_infPower;
MatrixS accelInputVertices=inputVertices*this->m_pseudoInvIminJ.transpose();
MatrixS combinedVertices=combineAminB(vertices,accelInputVertices,false);
getRoundedDirections(roundVertices,combinedVertices,true);
}
supports=roundVertices*templates;
for (int col=0;col<supports.cols();col++) {
refScalar min=func::toLower(limits.coeff(col,0));
minPoints[col]=-1;
for (int row=0;row<supports.rows();row++) {
if (func::toLower(supports.coeff(row,col))<min) {
min=func::toLower(supports.coeff(row,col));
minPoints[col]=row;
}
}
if (min<0) minPoints[col]=-1;
}
MatrixS coefficients(templates.rows(),1);
for (int col=0;col<templates.cols();col++) {
int row=minPoints[col];
if (row<0) continue;
low=0;
while(low<high) {
for (int pos=0;pos<coefficients.rows();pos++) {
coefficients.coeffRef(pos,0)=roundVertices.coeff(row,pos)*templates.coeff(pos,col);
}
ms_logger.logData(roundVertices,"vertices");
ms_logger.logData(templates,"templates");
for (int i=0;i<lambdas.cols();i++) {
poweredLambdas.coeffRef(0,i)=func::pow(lambdas.coeff(i,0),low);
}
supports=poweredLambdas*coefficients;
if (func::isZero(supports.coeff(0,0))) return func::ms_infPower;
refScalar power=func::toLower(limits.coeff(col,0)/supports.coeff(0,0));
refScalar iter=log10(power)/logSigma;
powerS n=func::toInt(iter);
if (n>low+1) low=n;
else break;
}
if (low<high) high=low;
}
int rotations=0;
for (int i=0;i<m_dimension;i++) {
if (this->m_freq[i]>rotations) rotations=this->m_freq[i];
}
if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,"Calculate Iterations, Time",true);
return high+rotations;
}
/// Calculates the number of iterations necessary for a point to supersede a specific guard
template <class scalar>
typename DynamicalSystem<scalar>::powerS DynamicalSystem<scalar>::calculateDivergentIterations(const MatrixS& direction,const MatrixS& point,const MatrixS& inpoint,const scalar &guard,const scalar &inguard,const MatrixS &normedLambdas,const refScalar logSigma,const inputType_t inputType)
{
powerS base=0,power=func::ms_infPower,step=1;
MatrixS baseLambdas=MatrixS::Zero(1,normedLambdas.cols());
MatrixS poweredLambdas=normedLambdas;
MatrixS jordanLambdas=MatrixS::Ones(1,normedLambdas.cols());
for (int col=0;col<poweredLambdas.cols();col++) {
if (m_normedJordanIndex[col]>0) {
jordanLambdas.coeffRef(0,col)=ms_one/normedLambdas.coeff(0,col);
}
}
while(2*step<power) {
scalar sum=inguard;
for (int col=0;col<poweredLambdas.cols();col++) {
poweredLambdas.coeffRef(0,col)*=poweredLambdas.coeffRef(0,col);
scalar mult=ms_one*direction.coeff(col,0);
if (m_normedOnes[col]) {
scalar n=base+step;
scalar multo=mult;
mult*=n;
for (int i=1;i<=m_normedJordanIndex[col];i++) {
multo+=direction.coeff(col-i,0)*binomial(base+step,i);
mult+=direction.coeff(col-i,0)*binomial(base+step,i+1);
}
sum+=multo*point.coeff(0,col)-mult*inpoint.coeff(0,col);
}
else {
for (int i=1;i<=m_normedJordanIndex[col];i++) {
mult+=direction.coeff(col-i,0)*binomial(base+step,i)*func::pow(jordanLambdas.coeff(0,col),i);
}
mult*=baseLambdas.coeffRef(0,col)+poweredLambdas.coeffRef(0,col);
sum+=mult*(point.coeff(0,col)-inpoint.coeff(0,col));
}
}
if (sum>guard) {
if (power<=base+step) return power;
power=base+step;
base+=step/2;
step=1;
for (int col=0;col<baseLambdas.cols();col++) {
baseLambdas.coeffRef(0,col)+=sqrt(poweredLambdas.coeffRef(0,col));
}
poweredLambdas=normedLambdas;
}
else step*=2;
}
return power;
}
/// Calculates the number of iterations necessary to supersede the guard
/// @param pInit initial polyhedra to apply the dynamics on
/// @param inputType type of inputs to use
template <class scalar>
typename DynamicalSystem<scalar>::powerS DynamicalSystem<scalar>::calculateDivergentIterations(AbstractPolyhedra<scalar> &init,inputType_t inputType)
{
MatrixS limits=m_guard.getPolyhedra(eEigenSpace).getSupports();
if (limits.rows()<=0) return func::ms_infPower;
MatrixS faces=-m_guard.getPolyhedra(eEigenSpace).getDirections();
if (faces.cols()==0) return func::ms_infPower;
MatrixS templates,normedVertices,normedInputs=ms_emptyMatrix;
const MatrixS& vertices=init.getVertices();
if (vertices.rows()<=0) processError(init.getName());
int normedDim=getNormedDimension();
getNormedDirections(templates,faces);
getNormedDirections(normedVertices,vertices,true);
MatrixS incoefficients=MatrixS::Zero(1,normedDim);
refScalar logSigma=log10(this->m_maxSigma);
MatrixS normedLambdas(1,normedDim);
int pos=0;
for (int i=0;i<m_dimension;i++) {
if (m_conjugatePair[i]>i) continue;
normedLambdas.coeffRef(0,pos++)=this->m_eigenNorms.coeff(i,0);
}
if (inputType==eParametricInputs) {
const MatrixS& inputVertices=m_transformedInputs.getPolyhedra(eEigenSpace).getVertices();
if (inputVertices.rows()<=0) processError(m_transformedInputs.getPolyhedra(eEigenSpace).getName());
getNormedDirections(normedInputs,inputVertices,true);
MatrixS IminJ=MatrixS::Identity(normedDim,normedDim);
for (int i=0;i<normedDim;i++) {
if (!m_normedOnes[i]) IminJ.coeffRef(i,i)-=normedLambdas.coeff(0,i);
if (m_normedJordanIndex[i]>0) IminJ.coeffRef(i-1,i)=-ms_one;
}
MatrixS invIminJ=IminJ.inverse();
normedInputs*=invIminJ.transpose();
}
powerS finalPower=func::ms_infPower;
for (int i=0;i<templates.cols();i++) {
powerS guardPower=0;
for (int j=0;j<normedVertices.rows();j++) {
if (normedInputs.rows()>0) {
for (int k=0;k<normedInputs.rows();k++) {
scalar inguard=(normedInputs.row(k)*templates.col(i)).coeff(0,0);
powerS power=calculateDivergentIterations(templates.col(i),normedVertices.row(j),normedInputs.row(k),limits.coeff(0,i),inguard,normedLambdas,logSigma,inputType);
if (power>guardPower) guardPower=power;
}
}
else {
powerS power=calculateDivergentIterations(templates.col(i),normedVertices.row(j),incoefficients,limits.coeff(0,i),0,normedLambdas,logSigma,inputType);
if (power>guardPower) guardPower=power;
}
}
if (guardPower<finalPower) finalPower=guardPower;
}
int rotations=0;
for (int i=0;i<m_dimension;i++) {
if (this->m_freq[i]>rotations) rotations=this->m_freq[i];
}
return finalPower+rotations;
}
/// Calculates the number of iterations necessary for a point to supersede a specific guard
template <class scalar>
typename DynamicalSystem<scalar>::powerS DynamicalSystem<scalar>::calculateNormedIterations(const MatrixS& point,const scalar &guard,const scalar &inguard,const MatrixS &normedLambdas,const refScalar logSigma,const inputType_t inputType)
{
powerS power=0;
powerS n=0;
MatrixS poweredLambdas=MatrixS::Ones(1,normedLambdas.cols());
do {
power=n;
scalar sum=0;
for (int col=0;col<normedLambdas.cols();col++) {
poweredLambdas.coeffRef(0,col)=func::pow(normedLambdas.coeff(0,col),power);
if (m_normedJordanIndex[col]>0) poweredLambdas.coeffRef(0,col)*=binomial(power,m_normedJordanIndex[col])/func::pow(normedLambdas.coeff(0,col),m_normedJordanIndex[col]);;
sum+=poweredLambdas.coeffRef(0,col)*point.coeff(0,col);
}
if (func::isZero(sum)) return func::ms_infPower;
refScalar poweredMax=func::toLower((guard+inguard)/sum);
if (poweredMax<logSigma) return func::ms_infPower;
refScalar iter=log10(poweredMax)/logSigma;
n=func::toInt(iter);
} while(abs(power-n)>1);
return power+1;
}
/// Calculates the number of iterations necessary to supersede the guard
template <class scalar>
typename DynamicalSystem<scalar>::powerS DynamicalSystem<scalar>::calculateNormedIterations(AbstractPolyhedra<scalar> &init,inputType_t inputType)
{
if (isDivergent(true)) return calculateDivergentIterations(init,inputType);
if (m_hasMultiplicities) this->calculateBoundedEigenError(calculateMaxIterations());
MatrixS limits=m_guard.getPolyhedra(eEigenSpace).getSupports();
if (limits.rows()<=0) return func::ms_infPower;
MatrixS faces=-m_guard.getPolyhedra(eEigenSpace).getDirections();
if (faces.cols()==0) return func::ms_infPower;
MatrixS templates,normedVertices,normedInputs=ms_emptyMatrix;
const MatrixS& vertices=init.getVertices();
if (vertices.rows()<=0) processError(init.getName());
int normedDim=getNormedDimension();
getNormedDirections(templates,faces);
getNormedDirections(normedVertices,vertices,true);
MatrixS coefficients(1,normedDim);
refScalar logSigma=log10(this->m_maxSigma);
MatrixS normedLambdas(1,normedDim);
int pos=0;
for (int i=0;i<m_dimension;i++) {
if (m_conjugatePair[i]>i) continue;
if (m_isOne[i]) normedLambdas.coeffRef(0,pos++)=ms_one-scalar(2e-6);
else normedLambdas.coeffRef(0,pos++)=func::norm2(m_eigenValues.coeff(i,i));
}
if (inputType==eParametricInputs) {
const MatrixS& inputVertices=m_transformedInputs.getPolyhedra(eEigenSpace).getVertices();
if (inputVertices.rows()<=0) processError(m_transformedInputs.getPolyhedra(eEigenSpace).getName());
getNormedDirections(normedInputs,inputVertices,true);
MatrixS IminJ=MatrixS::Identity(normedDim,normedDim);
for (int i=0;i<normedDim;i++) {
IminJ.coeffRef(i,i)-=normedLambdas.coeff(0,i);
if (m_normedJordanIndex[i]>0) IminJ.coeffRef(i-1,i)=-ms_one;
}
MatrixS invIminJ=IminJ.inverse();
normedInputs*=invIminJ.transpose();
}
powerS finalPower=func::ms_infPower;
for (int i=0;i<templates.cols();i++) {
for (int j=0;j<normedVertices.rows();j++) {
if (normedInputs.rows()>0) {
for (int k=0;k<normedInputs.rows();k++) {
for (int col=0;col<templates.rows();col++) {
coefficients.coeffRef(0,col)=templates.coeff(col,i)*(normedVertices(j,col)-normedInputs.coeff(k,col));
}
powerS power=calculateNormedIterations(coefficients,limits.coeff(0,i),(normedInputs.row(k)*templates.col(i)).coeff(0,0),normedLambdas,logSigma,inputType);
if (power<finalPower) finalPower=power;
}
}
else {
for (int col=0;col<templates.rows();col++) {
coefficients.coeffRef(0,col)=templates.coeff(col,i)*normedVertices(j,col);
}
powerS power=calculateNormedIterations(coefficients,limits.coeff(0,i),0,normedLambdas,logSigma,inputType);
if (power<finalPower) finalPower=power;
}
}
}
int rotations=0;
for (int i=0;i<m_dimension;i++) {
if (this->m_freq[i]>rotations) rotations=this->m_freq[i];
}
return finalPower+rotations;
}
template <class scalar>
void DynamicalSystem<scalar>::traceDynamics(traceDynamics_t traceType)
{
JordanMatrix<scalar>::ms_trace_time=(traceType>=eTraceTime);
Tableau<scalar>::ms_trace_time=(traceType>=eTraceTime);
Polyhedra<scalar>::ms_trace_dynamics=traceType;
JordanMatrix<scalar>::ms_trace_dynamics=traceType;
JordanSolver<refScalar>::ms_trace_dynamics=traceType;
if ((Tableau<scalar>::ms_trace_tableau<eTraceTableau) && (traceType>=eTraceAbstraction)) {
Tableau<scalar>::ms_trace_tableau=eTraceTableau;
}
}
template <class scalar>
void DynamicalSystem<scalar>::traceSimplex(traceTableau_t traceTableau,traceVertices_t traceVertices)
{
Tableau<scalar>::ms_trace_tableau=traceTableau;
Tableau<scalar>::ms_trace_errors=(traceTableau>=eTraceTableau);
Polyhedra<scalar>::ms_trace_vertices=traceVertices;
VertexEnumerator<scalar>::ms_trace_vertices=traceVertices;
VertexEnumerator<scalar>::ms_normalised_rays=(traceVertices>=eTraceEdges);
Set::ms_trace_set=(traceVertices==eTraceSets);
}
#ifdef USE_LDOUBLE
#ifdef USE_SINGLES
template class DynamicalSystem<long double>;
#endif
#ifdef USE_INTERVALS
template class DynamicalSystem<ldinterval>;
#endif
#endif
#ifdef USE_MPREAL
#ifdef USE_SINGLES
template class DynamicalSystem<mpfr::mpreal>;
#endif
#ifdef USE_INTERVALS
template class DynamicalSystem<mpinterval>;
#endif
#endif
}
| 40.843944 | 288 | 0.721841 | [
"vector",
"model",
"transform"
] |
bd9b40693379cc1f6871c2b82df8d7e66766d2df | 2,416 | hpp | C++ | components/homme/src/share/cxx/utilities/VectorUtils.hpp | jingxianwen/E3SM | bced6ba5e9247d6db6c8445b5fb828772a929b1b | [
"zlib-acknowledgement",
"RSA-MD",
"FTL"
] | 3 | 2020-02-24T21:58:57.000Z | 2020-09-29T23:06:45.000Z | components/homme/src/share/cxx/utilities/VectorUtils.hpp | jingxianwen/E3SM | bced6ba5e9247d6db6c8445b5fb828772a929b1b | [
"zlib-acknowledgement",
"RSA-MD",
"FTL"
] | 16 | 2019-09-27T02:16:37.000Z | 2020-08-01T17:51:12.000Z | components/homme/src/share/cxx/utilities/VectorUtils.hpp | jingxianwen/E3SM | bced6ba5e9247d6db6c8445b5fb828772a929b1b | [
"zlib-acknowledgement",
"RSA-MD",
"FTL"
] | 2 | 2020-12-09T07:30:20.000Z | 2022-03-18T04:22:25.000Z | /********************************************************************************
* HOMMEXX 1.0: Copyright of Sandia Corporation
* This software is released under the BSD license
* See the file 'COPYRIGHT' in the HOMMEXX/src/share/cxx directory
*******************************************************************************/
#ifndef HOMMEXX_VECTOR_UTILS_HPP
#define HOMMEXX_VECTOR_UTILS_HPP
#include "vector/vector_pragmas.hpp"
#include "vector/KokkosKernels_Vector.hpp"
#include "utilities/MathUtils.hpp"
namespace KokkosKernels {
namespace Batched {
namespace Experimental {
template <typename SpT>
inline
Vector<VectorTag<AVX<double, SpT>, 4> >
max (const Vector<VectorTag<AVX<double, SpT>, 4> >& a,
const Vector<VectorTag<AVX<double, SpT>, 4> >& b)
{
return _mm256_max_pd (a, b);
}
template <typename SpT>
inline
Vector<VectorTag<AVX<double, SpT>, 4> >
min (const Vector<VectorTag<AVX<double, SpT>, 4> >& a,
const Vector<VectorTag<AVX<double, SpT>, 4> >& b)
{
return _mm256_min_pd (a, b);
}
template <typename SpT>
inline
Vector<VectorTag<AVX<double, SpT>, 8> >
max (const Vector<VectorTag<AVX<double, SpT>, 8> >& a,
const Vector<VectorTag<AVX<double, SpT>, 8> >& b)
{
return _mm512_max_pd (a, b);
}
template <typename SpT>
inline
Vector<VectorTag<AVX<double, SpT>, 8> >
min (const Vector<VectorTag<AVX<double, SpT>, 8> >& a,
const Vector<VectorTag<AVX<double, SpT>, 8> >& b)
{
return _mm512_min_pd (a, b);
}
template <typename SpT, int l>
KOKKOS_INLINE_FUNCTION
Vector<VectorTag<SIMD<double, SpT>, l> >
max (const Vector<VectorTag<SIMD<double, SpT>, l> >& a,
const Vector<VectorTag<SIMD<double, SpT>, l> >& b)
{
Vector<VectorTag<SIMD<double, SpT>, l> > r_val;
VECTOR_SIMD_LOOP
for (int i = 0; i < Vector<VectorTag<SIMD<double, SpT>, l>>::vector_length; i++) {
r_val[i] = Homme::max(a[i],b[i]);
}
return r_val;
}
template <typename SpT, int l>
KOKKOS_INLINE_FUNCTION
Vector<VectorTag<SIMD<double, SpT>, l> >
min (const Vector<VectorTag<SIMD<double, SpT>, l> >& a,
const Vector<VectorTag<SIMD<double, SpT>, l> >& b)
{
Vector<VectorTag<SIMD<double, SpT>, l> > r_val;
VECTOR_SIMD_LOOP
for (int i = 0; i < Vector<VectorTag<SIMD<double, SpT>, l>>::vector_length; i++) {
r_val[i] = Homme::min(a[i],b[i]);
}
return r_val;
}
} // namespace KokkosKernels
} // namespace Batched
} // namespace Experimental
#endif // HOMMEXX_VECTOR_UTILS_HPP
| 27.146067 | 84 | 0.647765 | [
"vector"
] |
bd9e12e1ae38060bd95f4b1792ae8a5c948901db | 1,517 | cc | C++ | shaka/src/js/debug.cc | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 185 | 2018-11-06T06:04:44.000Z | 2022-03-02T22:20:39.000Z | shaka/src/js/debug.cc | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 211 | 2018-11-15T22:52:49.000Z | 2022-03-02T18:46:20.000Z | shaka/src/js/debug.cc | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 52 | 2018-12-12T11:00:46.000Z | 2022-02-23T17:35:02.000Z | // Copyright 2016 Google LLC
//
// 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
//
// https://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 "src/js/debug.h"
#include <chrono>
#include <thread>
namespace shaka {
namespace js {
Debug::Debug() {}
// \cond Doxygen_Skip
Debug::~Debug() {}
// \endcond Doxygen_Skip
std::string Debug::InternalTypeName(RefPtr<BackingObject> object) {
return object->factory()->name();
}
std::string Debug::IndirectBases(RefPtr<BackingObject> object) {
std::string ret;
const BackingObjectFactoryBase* ptr = object->factory();
while (ptr) {
if (!ret.empty())
ret.append(", ");
ret.append(ptr->name());
ptr = ptr->base();
}
return ret;
}
void Debug::Sleep(uint64_t delay_ms) {
std::this_thread::sleep_for(std::chrono::microseconds(delay_ms));
}
DebugFactory::DebugFactory() {
AddStaticFunction("internalTypeName", &Debug::InternalTypeName);
AddStaticFunction("indirectBases", &Debug::IndirectBases);
AddStaticFunction("sleep", &Debug::Sleep);
}
} // namespace js
} // namespace shaka
| 26.155172 | 75 | 0.709954 | [
"object"
] |
bd9f50c462477474d8f1c3fe8e5d530e1c002210 | 5,954 | cc | C++ | examples/seeking_pull_consumer_example.cc | raytheonbbn/tc-ta3-api-bindings-cpp | 98c0646e89de52ac8e65948699450fded402c254 | [
"MIT-0"
] | null | null | null | examples/seeking_pull_consumer_example.cc | raytheonbbn/tc-ta3-api-bindings-cpp | 98c0646e89de52ac8e65948699450fded402c254 | [
"MIT-0"
] | null | null | null | examples/seeking_pull_consumer_example.cc | raytheonbbn/tc-ta3-api-bindings-cpp | 98c0646e89de52ac8e65948699450fded402c254 | [
"MIT-0"
] | 1 | 2020-11-27T20:15:34.000Z | 2020-11-27T20:15:34.000Z | // Copyright (c) 2020 Raytheon BBN Technologies Corp.
// See LICENSE.txt for details.
#include <chrono>
#include <ctime>
#include <iomanip>
#include "avro/ValidSchema.hh"
#include "services/kafka_consumer_impl.h"
#include "services/kafka_client.h"
#include "services/kafka_callbacks.h"
#include "tc_schema/cdm.h"
#include "serialization/utils.h"
#include "records/cdm_record_parser.h"
#include "records/uuid.h"
#include "util/logger.h"
#include "util/timeconvert.h"
#define LOGGING_CONFIG_FILE "../conf/logconfig.ini"
std::string uuidToString(boost::array<uint8_t, UUID_LENGTH> uuid) {
std::stringstream s;
for (int i=0; i<UUID_LENGTH; ++i) {
s << std::to_string(uuid[i]);
}
return s.str();
}
void handleEvent(tc_schema::Event event) {
LOG_INFO << " Event: " << event.type;
LOG_INFO << " uuid: " << uuidToString(event.uuid);
}
void handleSubject(tc_schema::Subject subject) {
LOG_INFO << " Subject: " << subject.type;
LOG_INFO << " uuid: " << uuidToString(subject.uuid);
LOG_INFO << " cid: " << subject.cid;
}
void nextMessage(std::string key, std::unique_ptr<tc_schema::TCCDMDatum> record) {
tc_records::CDMRecordParser cdmParser;
LOG_INFO << "TestConsumer NextMessage called with key " << key;
if (record == nullptr) {
LOG_ERROR << "Record was a null";
return;
}
tc_schema::TCCDMDatum cdmRecord = *record;
LOG_INFO << "Received a record of type: " << cdmParser.getType(cdmRecord);
LOG_INFO << " Record Size: " << sizeof(cdmRecord);
LOG_INFO << " CDM Version: " << cdmRecord.CDMVersion;
LOG_INFO << " Datum idx: " << cdmRecord.datum.idx();
if (cdmParser.isEvent(cdmRecord)) {
handleEvent(cdmParser.getEvent(cdmRecord));
} else if (cdmParser.isSubject(cdmRecord)) {
handleSubject(cdmParser.getSubject(cdmRecord));
} else if (cdmParser.isIpcObject(cdmRecord)) {
LOG_INFO << " IpcObject";
} else if (cdmParser.isNetFlowObject(cdmRecord)) {
LOG_INFO << " NetFlowObject";
} else if (cdmParser.isFileObject(cdmRecord)) {
LOG_INFO << " FileObject";
} else if (cdmParser.isSrcSinkObject(cdmRecord)) {
LOG_INFO << " SrcSinkObject";
} else if (cdmParser.isMemoryObject(cdmRecord)) {
LOG_INFO << " MemoryObject";
} else if (cdmParser.isPrincipal(cdmRecord)) {
LOG_INFO << " Principal";
} else if (cdmParser.isTimeMarker(cdmRecord)) {
LOG_INFO << " TimeMarker";
} else {
LOG_INFO << " Unknown object! " << std::to_string(cdmRecord.datum.idx());
}
}
int main() {
tc_util::Logger::init(LOGGING_CONFIG_FILE);
LOG_INFO << "\n==========================================";
LOG_INFO << "Testing Kafka Consumer initialization";
LOG_INFO << "Run producer_test first to generate data";
LOG_INFO << "==========================================";
srand (time(NULL));
// Reader schema
// When we pass in a single schema (reader only), the writerSchema is set to the readerSchema
// The no-arg constructor will use this DEFAULT_SCHEMA_FILE, so we don't need to build it here
//avro::ValidSchema readerSchema = tc_serialization::utils::loadSchema(DEFAULT_SCHEMA_FILE);
// Consume from a specific offset
int64_t offset = 5;
tc_kafka::KafkaConsumer<tc_schema::TCCDMDatum> consumer1(offset);
std::string randomGroup = "Consumer1" + std::to_string(rand());
consumer1.setConsumerGroupId(randomGroup);
consumer1.setConsumeTimeoutMs(10000);
LOG_INFO << consumer1.dumpConfiguration();
LOG_INFO << "Connecting now...";
consumer1.connect();
LOG_INFO << "Getting message at offset 5";
std::unique_ptr<tc_schema::TCCDMDatum> recordPtr1 = consumer1.getNextMessage();
nextMessage("", std::move(recordPtr1));
LOG_INFO << "Getting message at offset 6 with key";
std::tuple<std::string, std::unique_ptr<tc_schema::TCCDMDatum>> val = consumer1.getNextMessageWithKey();
std::string key = std::get<0>(val);
std::unique_ptr<tc_schema::TCCDMDatum> recordPtr2 = std::move(std::get<1>(val));
nextMessage(key, std::move(recordPtr2));
LOG_INFO << "Getting message at offset 7 with key and timestamp";
std::tuple<std::string, int64_t, std::unique_ptr<tc_schema::TCCDMDatum>> val2 = consumer1.getNextMessageWithKeyAndTs();
std::string key2 = std::get<0>(val2);
int64_t ts = std::get<1>(val2);
std::unique_ptr<tc_schema::TCCDMDatum> recordPtr3 = std::move(std::get<2>(val2));
LOG_INFO << "Timestamp: " << ts;
nextMessage(key2, std::move(recordPtr3));
consumer1.shutdown();
// Consume from a specific offset
offset = -1;
tc_kafka::KafkaConsumer<tc_schema::TCCDMDatum> consumer2(offset);
consumer2.setConsumeTimeoutMs(10000);
randomGroup = "Consumer2" + std::to_string(rand());
consumer2.setConsumerGroupId(randomGroup);
LOG_INFO << consumer2.dumpConfiguration();
consumer2.connect();
val = consumer2.getNextMessageWithKey();
key = std::get<0>(val);
std::unique_ptr<tc_schema::TCCDMDatum> recordPtr4 = std::move(std::get<1>(val));
nextMessage(key, std::move(recordPtr4));
consumer2.shutdown();
// Consume from a sepcific time onward
std::string time1 = tc_util::toIso8601(ts + 1);
//std::string time1 = "2016-12-09T17:41:05.456Z";
std::cout << "Getting record from time: " << time1 << std::endl;
auto startTime = tc_util::toTimePoint(time1);
auto schema = tc_serialization::utils::loadSchema(DEFAULT_SCHEMA_FILE);
randomGroup = "Consumer3" + std::to_string(rand());
tc_kafka::KafkaConsumer<tc_schema::TCCDMDatum> consumer3(DEFAULT_TOPIC, DEFAULT_CONNECTION_STRING, schema, schema, randomGroup, startTime);
consumer3.setConsumeTimeoutMs(10000);
//consumer3.setConfigurationItem("debug", "metadata,protocol");
std::cout << consumer3.dumpConfiguration() << std::endl;
consumer3.connect();
val = consumer3.getNextMessageWithKey();
key = std::get<0>(val);
std::unique_ptr<tc_schema::TCCDMDatum> recordPtr5 = std::move(std::get<1>(val));
nextMessage(key, std::move(recordPtr5));
consumer3.shutdown();
return 0;
}
| 36.084848 | 141 | 0.692644 | [
"object"
] |
bdaafb4a0065877e7797853f20cdf9049e8f64d3 | 227 | cpp | C++ | SpookEngine/DungeonRoom.cpp | Mr-Bones738/SpookEngine | cc7d7a1980c8b30ef80845b46eb904fb3edaf342 | [
"MIT"
] | null | null | null | SpookEngine/DungeonRoom.cpp | Mr-Bones738/SpookEngine | cc7d7a1980c8b30ef80845b46eb904fb3edaf342 | [
"MIT"
] | null | null | null | SpookEngine/DungeonRoom.cpp | Mr-Bones738/SpookEngine | cc7d7a1980c8b30ef80845b46eb904fb3edaf342 | [
"MIT"
] | null | null | null | #include "DungeonRoom.h"
#include <glm/gtc/matrix_transform.hpp>
DungeonRoom::DungeonRoom(Model* initModel, glm::vec3 initPos) : RoomModel(initModel), pos(initPos) {
mmat = glm::mat4(1.0f);
mmat = glm::translate(mmat, pos);
} | 37.833333 | 100 | 0.731278 | [
"model"
] |
bdacd7b71a018f371199d617169084f7074be553 | 6,814 | cpp | C++ | src/dev/hsun/prism_data_test/PrismModel.cpp | haydenhs/NTRTsim | 4289b15652e8f5aa7f280d09a4fa301be0bd99e1 | [
"Apache-2.0"
] | 4 | 2017-12-15T02:51:12.000Z | 2020-06-08T01:40:38.000Z | src/dev/hsun/prism_data_test/PrismModel.cpp | haydenhs/NTRTsim | 4289b15652e8f5aa7f280d09a4fa301be0bd99e1 | [
"Apache-2.0"
] | null | null | null | src/dev/hsun/prism_data_test/PrismModel.cpp | haydenhs/NTRTsim | 4289b15652e8f5aa7f280d09a4fa301be0bd99e1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
*/
/**
* @file PrismModel.cpp
* @brief Contains the implementation of the class PrismModel.
* $Id$
*/
// This module
#include "PrismModel.h"
// This library
#include "core/abstractMarker.h"
#include "core/tgBasicActuator.h"
#include "core/tgRod.h"
#include "sensors/tgDataObserver.h"
#include "tgcreator/tgBuildSpec.h"
#include "tgcreator/tgBasicActuatorInfo.h"
#include "tgcreator/tgRodInfo.h"
#include "tgcreator/tgStructure.h"
#include "tgcreator/tgStructureInfo.h"
// The Bullet Physics library
#include "LinearMath/btVector3.h"
// The C++ Standard Library
#include <stdexcept>
#include <vector>
/**
* Anonomous namespace so we don't have to declare the config in
* the header.
*/
namespace
{
/**
* Configuration parameters so they're easily accessable.
* All parameters must be positive.
*/
const struct Config
{
double density;
double radius;
double stiffness;
double damping;
double pretension;
double triangle_length;
double triangle_height;
double prism_height;
} c =
{
0.2, // density (mass / length^3)
0.31, // radius (length)
1000.0, // stiffness (mass / sec^2)
10.0, // damping (mass / sec)
500.0, // pretension (mass * length / sec^2)
10.0, // triangle_length (length)
10.0, // triangle_height (length)
20.0, // prism_height (length)
};
} // namespace
/*
* helper arrays for node and rod numbering schema
*/
/*returns the number of the rod for a given node */
const int rodNumbersPerNode[6]={0,1,2,2,0,1};
PrismModel::PrismModel() :
tgModel()
{
m_pObserver = NULL;
}
PrismModel::PrismModel(const std::string& fileName) :
tgModel()
{
m_pObserver = new tgDataObserver(fileName);
}
PrismModel::~PrismModel()
{
}
void PrismModel::addNodes(tgStructure& s,
double edge,
double width,
double height)
{
// bottom right
nodePositions.push_back(btVector3(-edge / 2.0, 0, 0)); //1
// bottom left
nodePositions.push_back(btVector3( edge / 2.0, 0, 0)); //2
// bottom front
nodePositions.push_back(btVector3(0, 0, width)); //3
// top right
nodePositions.push_back(btVector3(-edge / 2.0, height, 0)); //4
// top left
nodePositions.push_back(btVector3( edge / 2.0, height, 0)); //5
// top front
nodePositions.push_back(btVector3(0, height, width)); //6
for(int i=0;i<6;i++)
{
s.addNode(nodePositions[i][0],nodePositions[i][1],nodePositions[i][2]);
}
}
void PrismModel::addRods(tgStructure& s)
{
s.addPair( 0, 4, "r1 rod");
s.addPair( 1, 5, "r2 rod");
s.addPair( 2, 3, "r3 rod");
}
void PrismModel::addMuscles(tgStructure& s)
{
// Bottom Triangle
s.addPair(0, 1, "muscle");
s.addPair(1, 2, "muscle");
s.addPair(2, 0, "muscle");
// Top
s.addPair(3, 4, "muscle");
s.addPair(4, 5, "muscle");
s.addPair(5, 3, "muscle");
//Edges
s.addPair(0, 3, "muscle");
s.addPair(1, 4, "muscle");
s.addPair(2, 5, "muscle");
}
void PrismModel::addMarkers(tgStructure &s)
{
std::vector<tgRod *> rods=find<tgRod>("rod");
for(int i=0;i<6;i++)
{
const btRigidBody* bt = rods[rodNumbersPerNode[i]]->getPRigidBody();
btTransform inverseTransform = bt->getWorldTransform().inverse();
btVector3 pos = inverseTransform * (nodePositions[i]);
abstractMarker tmp=abstractMarker(bt,pos,btVector3(0.08*i,1.0 - 0.08*i,.0),i);
this->addMarker(tmp);
}
}
void PrismModel::setup(tgWorld& world)
{
// Define the configurations of the rods and strings
// Note that pretension is defined for this string
const tgRod::Config rodConfig(c.radius, c.density);
const tgSpringCableActuator::Config muscleConfig(c.stiffness, c.damping, c.pretension);
// Create a structure that will hold the details of this model
tgStructure s;
// Add nodes to the structure
addNodes(s, c.triangle_length, c.triangle_height, c.prism_height);
// Add rods to the structure
addRods(s);
// Add muscles to the structure
addMuscles(s);
// Create the build spec that uses tags to turn the structure into a real model
tgBuildSpec spec;
spec.addBuilder("rod", new tgRodInfo(rodConfig));
spec.addBuilder("muscle", new tgBasicActuatorInfo(muscleConfig));
// Create your structureInfo
tgStructureInfo structureInfo(s, spec);
// Use the structureInfo to build ourselves
structureInfo.buildInto(*this, world);
// We could now use tgCast::filter or similar to pull out the
// models (e.g. muscles) that we want to control.
allActuators = tgCast::filter<tgModel, tgSpringCableActuator> (getDescendants());
// Notify controllers that setup has finished.
notifySetup();
// Actually setup the children
tgModel::setup(world);
//map the rods and add the markers to them.
addMarkers(s);
// start an observer
if (m_pObserver != NULL)
{
m_pObserver->onSetup(*this);
}
// Move the structure so it doesn't start in the ground
s.move(btVector3(0, 10, 0));
}
void PrismModel::step(double dt)
{
// Precondition
if (dt <= 0.0)
{
throw std::invalid_argument("dt is not positive");
}
else
{
// Notify observers (controllers) of the step so that they can take action
notifyStep(dt);
tgModel::step(dt); // Step any children
if (m_pObserver != NULL)
{
m_pObserver->onStep(*this, dt);
}
}
}
void PrismModel::onVisit(tgModelVisitor& r)
{
// Example: m_rod->getRigidBody()->dosomething()...
tgModel::onVisit(r);
}
const std::vector<tgSpringCableActuator*>& PrismModel::getAllActuators() const
{
return allActuators;
}
void PrismModel::teardown()
{
notifyTeardown();
tgModel::teardown();
delete m_pObserver;
}
| 27.039683 | 91 | 0.640153 | [
"vector",
"model"
] |
bdb7e0959445b6f75b742e8f01a0af48770a6ad2 | 26,069 | cpp | C++ | source/duke3d/src/d_menu.cpp | bisk89/Raze | 1a2663f7ac84d4e4f472e0796b937447ee6fab6b | [
"RSA-MD"
] | 2 | 2020-03-26T10:11:17.000Z | 2021-01-19T08:16:48.000Z | source/duke3d/src/d_menu.cpp | bisk89/Raze | 1a2663f7ac84d4e4f472e0796b937447ee6fab6b | [
"RSA-MD"
] | null | null | null | source/duke3d/src/d_menu.cpp | bisk89/Raze | 1a2663f7ac84d4e4f472e0796b937447ee6fab6b | [
"RSA-MD"
] | null | null | null | //-------------------------------------------------------------------------
/*
Copyright (C) 2016 EDuke32 developers and contributors
Copyright (C) 2019 Christoph Oelckers
This is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h" // Must come before everything else!
#include "cheats.h"
#include "compat.h"
#include "demo.h"
#include "duke3d.h"
#include "menus.h"
#include "osdcmds.h"
#include "savegame.h"
#include "game.h"
#include "superfasthash.h"
#include "gamecvars.h"
#include "gamecontrol.h"
#include "c_bind.h"
#include "menu/menu.h"
#include "gstrings.h"
#include "version.h"
#include "namesdyn.h"
#include "menus.h"
#include "../../glbackend/glbackend.h"
BEGIN_DUKE_NS
#define MENU_MARGIN_REGULAR 40
#define MENU_MARGIN_WIDE 32
#define MENU_MARGIN_CENTER 160
#define MENU_HEIGHT_CENTER 100
enum MenuTextFlags_t
{
MT_Selected = 1 << 0,
MT_Disabled = 1 << 1,
MT_XCenter = 1 << 2,
MT_XRight = 1 << 3,
MT_YCenter = 1 << 4,
MT_Literal = 1 << 5,
MT_RightSide = 1 << 6,
};
// common font types
// tilenums are set after namesdyn runs.
// These are also modifiable by scripts.
// emptychar x,y between x,y zoom cursorLeft cursorCenter cursorScale textflags
// tilenum shade_deselected shade_disabled pal pal_selected pal_deselected pal_disabled
MenuFont_t MF_Redfont = { { 5<<16, 15<<16 }, { 0, 0 }, 65536, 20<<16, 110<<16, 65536, TEXT_BIGALPHANUM | TEXT_UPPERCASE,
-1, 10, 0, 0, 0, 0, 1,
0, 0, 1 };
MenuFont_t MF_Bluefont = { { 5<<16, 7<<16 }, { 0, 0 }, 65536, 10<<16, 110<<16, 32768, 0,
-1, 10, 0, 0, 10, 10, 16,
0, 0, 16 };
MenuFont_t MF_Minifont = { { 4<<16, 5<<16 }, { 1<<16, 1<<16 }, 65536, 10<<16, 110<<16, 32768, 0,
-1, 10, 0, 0, 2, 2, 0,
0, 0, 16 };
/*
This function prepares data after ART and CON have been processed.
It also initializes some data in loops rather than statically at compile time.
*/
void Menu_Init(void)
{
// prepare menu fonts
// check if tilenum is -1 in case it was set in EVENT_SETDEFAULTS
if ((unsigned)MF_Redfont.tilenum >= MAXTILES) MF_Redfont.tilenum = BIGALPHANUM;
if ((unsigned)MF_Bluefont.tilenum >= MAXTILES) MF_Bluefont.tilenum = STARTALPHANUM;
if ((unsigned)MF_Minifont.tilenum >= MAXTILES) MF_Minifont.tilenum = MINIFONT;
MF_Redfont.emptychar.y = tilesiz[MF_Redfont.tilenum].y << 16;
MF_Bluefont.emptychar.y = tilesiz[MF_Bluefont.tilenum].y << 16;
MF_Minifont.emptychar.y = tilesiz[MF_Minifont.tilenum].y << 16;
if (!minitext_lowercase)
MF_Minifont.textflags |= TEXT_UPPERCASE;
}
static void Menu_DrawBackground(const DVector2 &origin)
{
rotatesprite_fs(int(origin.X * 65536) + (MENU_MARGIN_CENTER << 16), int(origin.Y * 65536) + (100 << 16), 65536L, 0, MENUSCREEN, 16, 0, 10 + 64);
}
static void Menu_DrawTopBar(const DVector2 &origin)
{
if ((G_GetLogoFlags() & LOGO_NOTITLEBAR) == 0)
rotatesprite_fs(int(origin.X*65536) + (MENU_MARGIN_CENTER<<16), int(origin.Y*65536) + (19<<16), MF_Redfont.cursorScale, 0,MENUBAR,16,0,10);
}
static void Menu_DrawTopBarCaption(const char *caption, const DVector2 &origin)
{
static char t[64];
size_t const srclen = strlen(caption);
size_t const dstlen = min(srclen, ARRAY_SIZE(t)-1);
memcpy(t, caption, dstlen);
t[dstlen] = '\0';
char *p = &t[dstlen-1];
if (*p == ':')
*p = '\0';
captionmenutext(int(origin.X*65536) + (MENU_MARGIN_CENTER<<16), int(origin.Y*65536) + (24<<16) + ((15>>1)<<16), t);
}
static void Menu_GetFmt(const MenuFont_t* font, uint8_t const status, int32_t* s, int32_t* z)
{
if (status & MT_Selected)
*s = VM_OnEventWithReturn(EVENT_MENUSHADESELECTED, -1, myconnectindex, sintable[((int32_t)totalclock << 5) & 2047] >> 12);
else
*s = font->shade_deselected;
// sum shade values
if (status & MT_Disabled)
*s += font->shade_disabled;
if (FURY && status & MT_Selected)
*z += (*z >> 4);
}
static vec2_t Menu_Text(int32_t x, int32_t y, const MenuFont_t* font, const char* t, uint8_t status, int32_t ydim_upper, int32_t ydim_lower)
{
int32_t s, p, ybetween = font->between.y;
int32_t f = font->textflags;
if (status & MT_XCenter)
f |= TEXT_XCENTER;
if (status & MT_XRight)
f |= TEXT_XRIGHT;
if (status & MT_YCenter)
{
f |= TEXT_YCENTER | TEXT_YOFFSETZERO;
ybetween = font->emptychar.y; // <^ the battle against 'Q'
}
if (status & MT_Literal)
f |= TEXT_LITERALESCAPE;
int32_t z = font->zoom;
if (status & MT_Disabled)
p = (status & MT_RightSide) ? font->pal_disabled_right : font->pal_disabled;
else if (status & MT_Selected)
p = (status & MT_RightSide) ? font->pal_selected_right : font->pal_selected;
else
p = (status & MT_RightSide) ? font->pal_deselected_right : font->pal_deselected;
Menu_GetFmt(font, status, &s, &z);
return G_ScreenText(font->tilenum, x, y, z, 0, 0, t, s, p, 2 | 8 | 16 | ROTATESPRITE_FULL16, 0, font->emptychar.x, font->emptychar.y, font->between.x, ybetween, f, 0, ydim_upper, xdim - 1, ydim_lower);
}
static vec2_t mgametextcenterat(int32_t x, int32_t y, char const* t, int32_t f = 0)
{
return G_ScreenText(MF_Bluefont.tilenum, x, y, MF_Bluefont.zoom, 0, 0, t, 0, MF_Bluefont.pal, 2 | 8 | 16 | ROTATESPRITE_FULL16, 0, MF_Bluefont.emptychar.x, MF_Bluefont.emptychar.y, MF_Bluefont.between.x, MF_Bluefont.between.y, MF_Bluefont.textflags | f | TEXT_XCENTER, 0, 0, xdim - 1, ydim - 1);
}
static vec2_t mgametextcenter(int32_t x, int32_t y, char const* t, int32_t f = 0)
{
return mgametextcenterat((MENU_MARGIN_CENTER << 16) + x, y, t, f);
}
static int32_t Menu_CursorShade(void)
{
return VM_OnEventWithReturn(EVENT_MENUCURSORSHADE, -1, myconnectindex, 4 - (sintable[((int32_t)totalclock << 4) & 2047] >> 11));
}
static void Menu_DrawCursorCommon(int32_t x, int32_t y, int32_t z, int32_t picnum, int32_t ydim_upper = 0, int32_t ydim_lower = ydim - 1)
{
rotatesprite_(x, y, z, 0, picnum, Menu_CursorShade(), 0, 2 | 8, 0, 0, 0, ydim_upper, xdim - 1, ydim_lower);
}
static void Menu_DrawCursorLeft(int32_t x, int32_t y, int32_t z)
{
if (FURY) return;
Menu_DrawCursorCommon(x, y, z, VM_OnEventWithReturn(EVENT_MENUCURSORLEFT, -1, myconnectindex, SPINNINGNUKEICON + (((int32_t)totalclock >> 3) % 7)));
}
static void Menu_DrawCursorRight(int32_t x, int32_t y, int32_t z)
{
if (FURY) return;
Menu_DrawCursorCommon(x, y, z, VM_OnEventWithReturn(EVENT_MENUCURSORRIGHT, -1, myconnectindex, SPINNINGNUKEICON + 6 - ((6 + ((int32_t)totalclock >> 3)) % 7)));
}
static int Menu_GetFontHeight(int fontnum)
{
auto& font = fontnum == NIT_BigFont ? MF_Redfont : fontnum == NIT_SmallFont ? MF_Bluefont : MF_Minifont;
return font.get_yline();
}
//----------------------------------------------------------------------------
//
// Implements the native looking menu used for the main menu
// and the episode/skill selection screens, i.e. the parts
// that need to look authentic
//
//----------------------------------------------------------------------------
class DukeListMenu : public DListMenu
{
using Super = DListMenu;
protected:
void SelectionChanged() override
{
if (mDesc->mScriptId == 110)
{
// Hack alert: Ion Fury depends on the skill getting set globally when the selection changes because the script cannot detect actual selection changes.
// Yuck!
ud.m_player_skill = mDesc->mSelectedItem+1;
}
}
virtual void CallScript(int event, bool getorigin = false)
{
ud.returnvar[0] = int(origin.X * 65536);
ud.returnvar[1] = int(origin.Y * 65536);
ud.returnvar[2] = mDesc->mSelectedItem;
VM_OnEventWithReturn(event, g_player[screenpeek].ps->i, screenpeek, mDesc->mScriptId);
if (getorigin)
{
origin.X = ud.returnvar[0] / 65536.;
origin.Y = ud.returnvar[1] / 65536.;
}
}
void Ticker() override
{
auto lf = G_GetLogoFlags();
help_disabled = (lf & LOGO_NOHELP);
credits_disabled = (lf & LOGO_NOCREDITS);
// Lay out the menu. Since scripts are allowed to mess around with the font this needs to be redone each frame.
int32_t y_upper = mDesc->mYpos;
int32_t y_lower = y_upper + mDesc->mYbotton;
int32_t y = 0;
int32_t calculatedentryspacing = 0;
int32_t const height = Menu_GetFontHeight(mDesc->mNativeFontNum) >> 16;
int32_t totalheight = 0, numvalidentries = mDesc->mItems.Size();
for (unsigned e = 0; e < mDesc->mItems.Size(); ++e)
{
auto entry = mDesc->mItems[e];
entry->mHidden = false;
if (entry->GetAction(nullptr) == NAME_HelpMenu && help_disabled)
{
entry->mHidden = true;
numvalidentries--;
continue;
}
else if (entry->GetAction(nullptr) == NAME_CreditsMenu && credits_disabled)
{
entry->mHidden = true;
numvalidentries--;
continue;
}
entry->SetHeight(height);
totalheight += height;
}
if (mDesc->mSpacing <= 0) calculatedentryspacing = std::max(0, (y_lower - y_upper - totalheight) / (numvalidentries > 1 ? numvalidentries - 1 : 1));
if (calculatedentryspacing <= 0) calculatedentryspacing = mDesc->mSpacing;
// totalHeight calculating pass
int totalHeight;
for (unsigned e = 0; e < mDesc->mItems.Size(); ++e)
{
auto entry = mDesc->mItems[e];
if (!entry->mHidden)
{
entry->SetY(y_upper + y);
y += height;
totalHeight = y;
y += calculatedentryspacing;
}
}
}
void PreDraw() override
{
CallScript(CurrentMenu == this ? EVENT_DISPLAYMENU : EVENT_DISPLAYINACTIVEMENU, true);
Super::PreDraw();
}
void PostDraw() override
{
CallScript(CurrentMenu == this ? EVENT_DISPLAYMENUREST : EVENT_DISPLAYINACTIVEMENUREST, false);
}
};
class DukeNewGameCustomSubMenu : public DukeListMenu
{
virtual void CallScript(int event, bool getorigin) override
{
// This needs to get the secondary ID to the script.
ud.returnvar[3] = mDesc->mSecondaryId;
DukeListMenu::CallScript(event, getorigin);
}
};
class DukeMainMenu : public DukeListMenu
{
void PreDraw() override
{
DukeListMenu::PreDraw();
if ((G_GetLogoFlags() & LOGO_NOGAMETITLE) == 0)
{
rotatesprite_fs(int(origin.X * 65536) + (MENU_MARGIN_CENTER<<16), int(origin.Y * 65536) + ((28)<<16), 65536L,0,INGAMEDUKETHREEDEE,0,0,10);
if (PLUTOPAK) // JBF 20030804
rotatesprite_fs(int(origin.X * 65536) + ((MENU_MARGIN_CENTER+100)<<16), int(origin.Y * 65536) + (36<<16), 65536L,0,PLUTOPAKSPRITE+2,(sintable[((int32_t) totalclock<<4)&2047]>>11),0,2+8);
}
}
};
//----------------------------------------------------------------------------
//
// Hack to display Ion Fury's credits screens
//
//----------------------------------------------------------------------------
class DukeImageScreen : public ImageScreen
{
public:
DukeImageScreen(FImageScrollerDescriptor::ScrollerItem* desc)
: ImageScreen(desc)
{}
void CallScript(int event, bool getorigin = false)
{
ud.returnvar[0] = int(origin.X * 65536);
ud.returnvar[1] = int(origin.Y * 65536);
ud.returnvar[2] = 0;
VM_OnEventWithReturn(event, g_player[screenpeek].ps->i, screenpeek, mDesc->scriptID);
if (getorigin)
{
origin.X = ud.returnvar[0] / 65536.;
origin.Y = ud.returnvar[1] / 65536.;
}
}
void Drawer() override
{
// Hack alert: The Ion Fury scripts - being true to the entire design here, take the current menu value
// not from the passed variable but instead from the global current_menu, so we have to temporarily alter that here.
// Ugh. (Talk about "broken by design"...)
auto cm = g_currentMenu;
g_currentMenu = mDesc->scriptID;
auto o = origin;
CallScript(EVENT_DISPLAYMENU, true);
ImageScreen::Drawer();
CallScript(EVENT_DISPLAYMENUREST, false);
g_currentMenu = cm;
origin = o;
}
};
class DDukeImageScrollerMenu : public DImageScrollerMenu
{
ImageScreen* newImageScreen(FImageScrollerDescriptor::ScrollerItem* desc) override
{
return new DukeImageScreen(desc);
}
};
//----------------------------------------------------------------------------
//
// Menu related game interface functions
//
//----------------------------------------------------------------------------
void GameInterface::DrawNativeMenuText(int fontnum, int state, double xpos, double ypos, float fontscale, const char* text, int flags)
{
int ydim_upper = 0;
int ydim_lower = ydim - 1;
//int32_t const indent = 0; // not set for any relevant menu
int x = int(xpos * 65536);
uint8_t status = 0;
if (state == NIT_SelectedState)
status |= MT_Selected;
if (state == NIT_InactiveState)
status |= MT_Disabled;
if (flags & LMF_Centered)
status |= MT_XCenter;
bool const dodraw = true;
MenuFont_t& font = fontnum == NIT_BigFont ? MF_Redfont : fontnum == NIT_SmallFont ? MF_Bluefont : MF_Minifont;
int32_t const height = font.get_yline();
status |= MT_YCenter;
int32_t const y_internal = int(ypos * 65536) + ((height >> 17) << 16);// -menu->scrollPos;
vec2_t textsize;
if (dodraw)
textsize = Menu_Text(x, y_internal, &font, text, status, ydim_upper, ydim_lower);
if (dodraw && (status & MT_Selected) && state != 1)
{
if (status & MT_XCenter)
{
Menu_DrawCursorLeft(x + font.cursorCenterPosition, y_internal, font.cursorScale);
Menu_DrawCursorRight(x - font.cursorCenterPosition, y_internal, font.cursorScale);
}
else
Menu_DrawCursorLeft(x /*+ indent*/ - font.cursorLeftPosition, y_internal, font.cursorScale);
}
}
void GameInterface::MenuOpened()
{
S_PauseSounds(true);
if ((!g_netServer && ud.multimode < 2))
{
ready2send = 0;
totalclock = ototalclock;
screenpeek = myconnectindex;
}
auto& gm = g_player[myconnectindex].ps->gm;
if (gm & MODE_GAME)
{
gm |= MODE_MENU;
}
}
void GameInterface::MenuSound(EMenuSounds snd)
{
switch (snd)
{
case ActivateSound:
S_MenuSound();
break;
case CursorSound:
S_PlaySound(KICK_HIT, CHAN_AUTO, CHANF_UI);
break;
case AdvanceSound:
S_PlaySound(PISTOL_BODYHIT, CHAN_AUTO, CHANF_UI);
break;
case CloseSound:
S_PlaySound(EXITMENUSOUND, CHAN_AUTO, CHANF_UI);
break;
default:
return;
}
}
void GameInterface::MenuClosed()
{
auto& gm = g_player[myconnectindex].ps->gm;
if (gm & MODE_GAME)
{
if (gm & MODE_MENU)
inputState.ClearAllInput();
// The following lines are here so that you cannot close the menu when no game is running.
gm &= ~MODE_MENU;
if ((!g_netServer && ud.multimode < 2) && ud.recstat != 2)
{
ready2send = 1;
totalclock = ototalclock;
CAMERACLOCK = (int32_t)totalclock;
CAMERADIST = 65536;
// Reset next-viewscreen-redraw counter.
// XXX: are there any other cases like that in need of handling?
if (g_curViewscreen >= 0)
actor[g_curViewscreen].t_data[0] = (int32_t)totalclock;
}
G_UpdateScreenArea();
S_PauseSounds(false);
}
}
bool GameInterface::CanSave()
{
if (ud.recstat == 2) return false;
auto &myplayer = *g_player[myconnectindex].ps;
if (sprite[myplayer.i].extra <= 0)
{
//P_DoQuote(QUOTE_SAVE_DEAD, &myplayer); // handled by the menu.
return false;
}
return true;
}
void GameInterface::CustomMenuSelection(int menu, int item)
{
ud.returnvar[0] = item;
ud.returnvar[1] = -1;
VM_OnEventWithReturn(EVENT_NEWGAMECUSTOM, -1, myconnectindex, menu);
}
void GameInterface::StartGame(FGameStartup& gs)
{
int32_t skillsound = PISTOL_BODYHIT;
soundEngine->StopAllChannels();
switch (gs.Skill)
{
case 0:
skillsound = JIBBED_ACTOR6;
break;
case 1:
skillsound = BONUS_SPEECH1;
break;
case 2:
skillsound = DUKE_GETWEAPON2;
break;
case 3:
skillsound = JIBBED_ACTOR5;
break;
}
ud.m_player_skill = gs.Skill + 1;
if (menu_sounds && skillsound >= 0 && SoundEnabled())
{
S_PlaySound(skillsound, CHAN_AUTO, CHANF_UI);
while (S_CheckSoundPlaying(skillsound))
{
S_Update();
gameHandleEvents();
}
}
ud.m_respawn_monsters = (gs.Skill == 3);
ud.m_monsters_off = ud.monsters_off = 0;
ud.m_respawn_items = 0;
ud.m_respawn_inventory = 0;
ud.multimode = 1;
ud.m_volume_number = gs.Episode;
m_level_number = gs.Level;
G_NewGame_EnterLevel();
}
FSavegameInfo GameInterface::GetSaveSig()
{
return { SAVESIG_DN3D, MINSAVEVER_DN3D, SAVEVER_DN3D };
}
void GameInterface::DrawMenuCaption(const DVector2& origin, const char* text)
{
Menu_DrawTopBar(origin);
Menu_DrawTopBarCaption(text, origin);
}
//----------------------------------------------------------------------------
//
//
//
//----------------------------------------------------------------------------
static void shadowminitext(int32_t x, int32_t y, const char* t, int32_t p)
{
int32_t f = 0;
if (!minitext_lowercase)
f |= TEXT_UPPERCASE;
G_ScreenTextShadow(1, 1, MINIFONT, x, y, 65536, 0, 0, t, 0, p, 2 | 8 | 16 | ROTATESPRITE_FULL16, 0, 4 << 16, 8 << 16, 1 << 16, 0, f, 0, 0, xdim - 1, ydim - 1);
}
//----------------------------------------------------------------------------
//
// allows the front end to override certain fullscreen image menus
// with custom implementations.
//
// This is needed because the credits screens in Duke Nukem
// are either done by providing an image or by printing text, based on the version used.
//
//----------------------------------------------------------------------------
bool GameInterface::DrawSpecialScreen(const DVector2 &origin, int tilenum)
{
// Older versions of Duke Nukem create the credits screens manually.
// On the latest version there's real graphics for this.
bool haveCredits = VOLUMEALL && PLUTOPAK;
int32_t m, l;
if (!haveCredits)
{
if (tilenum == CREDITSTEXT1)
{
Menu_DrawBackground(origin);
m = int(origin.X * 65536) + (20 << 16);
l = int(origin.Y * 65536) + (33 << 16);
shadowminitext(m, l, "Original Concept", 12); l += 7 << 16;
shadowminitext(m, l, "Todd Replogle and Allen H. Blum III", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Produced & Directed By", 12); l += 7 << 16;
shadowminitext(m, l, "Greg Malone", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Executive Producer", 12); l += 7 << 16;
shadowminitext(m, l, "George Broussard", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "BUILD Engine", 12); l += 7 << 16;
shadowminitext(m, l, "Ken Silverman", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Game Programming", 12); l += 7 << 16;
shadowminitext(m, l, "Todd Replogle", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "3D Engine/Tools/Net", 12); l += 7 << 16;
shadowminitext(m, l, "Ken Silverman", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Network Layer/Setup Program", 12); l += 7 << 16;
shadowminitext(m, l, "Mark Dochtermann", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Map Design", 12); l += 7 << 16;
shadowminitext(m, l, "Allen H. Blum III", 12); l += 7 << 16;
shadowminitext(m, l, "Richard Gray", 12); l += 7 << 16;
m = int(origin.X * 65536) + (180 << 16);
l = int(origin.Y * 65536) + (33 << 16);
shadowminitext(m, l, "3D Modeling", 12); l += 7 << 16;
shadowminitext(m, l, "Chuck Jones", 12); l += 7 << 16;
shadowminitext(m, l, "Sapphire Corporation", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Artwork", 12); l += 7 << 16;
shadowminitext(m, l, "Dirk Jones, Stephen Hornback", 12); l += 7 << 16;
shadowminitext(m, l, "James Storey, David Demaret", 12); l += 7 << 16;
shadowminitext(m, l, "Douglas R. Wood", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Sound Engine", 12); l += 7 << 16;
shadowminitext(m, l, "Jim Dose", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Sound & Music Development", 12); l += 7 << 16;
shadowminitext(m, l, "Robert Prince", 12); l += 7 << 16;
shadowminitext(m, l, "Lee Jackson", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Voice Talent", 12); l += 7 << 16;
shadowminitext(m, l, "Lani Minella - Voice Producer", 12); l += 7 << 16;
shadowminitext(m, l, "Jon St. John as \"Duke Nukem\"", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Graphic Design", 12); l += 7 << 16;
shadowminitext(m, l, "Packaging, Manual, Ads", 12); l += 7 << 16;
shadowminitext(m, l, "Robert M. Atkins", 12); l += 7 << 16;
shadowminitext(m, l, "Michael Hadwin", 12); l += 7 << 16;
return true;
}
else if (tilenum == CREDITSTEXT2__STATIC)
{
Menu_DrawBackground(origin);
m = int(origin.X * 65536) + (20 << 16);
l = int(origin.Y * 65536) + (33 << 16);
shadowminitext(m, l, "Special Thanks To", 12); l += 7 << 16;
shadowminitext(m, l, "Steven Blackburn, Tom Hall", 12); l += 7 << 16;
shadowminitext(m, l, "Scott Miller, Joe Siegler", 12); l += 7 << 16;
shadowminitext(m, l, "Terry Nagy, Colleen Compton", 12); l += 7 << 16;
shadowminitext(m, l, "HASH, Inc., FormGen, Inc.", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "The 3D Realms Beta Testers", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Nathan Anderson, Wayne Benner", 12); l += 7 << 16;
shadowminitext(m, l, "Glenn Brensinger, Rob Brown", 12); l += 7 << 16;
shadowminitext(m, l, "Erik Harris, Ken Heckbert", 12); l += 7 << 16;
shadowminitext(m, l, "Terry Herrin, Greg Hively", 12); l += 7 << 16;
shadowminitext(m, l, "Hank Leukart, Eric Baker", 12); l += 7 << 16;
shadowminitext(m, l, "Jeff Rausch, Kelly Rogers", 12); l += 7 << 16;
shadowminitext(m, l, "Mike Duncan, Doug Howell", 12); l += 7 << 16;
shadowminitext(m, l, "Bill Blair", 12); l += 7 << 16;
m = int(origin.X * 65536) + (160 << 16);
l = int(origin.Y * 65536) + (33 << 16);
shadowminitext(m, l, "Company Product Support", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "The following companies were cool", 12); l += 7 << 16;
shadowminitext(m, l, "enough to give us lots of stuff", 12); l += 7 << 16;
shadowminitext(m, l, "during the making of Duke Nukem 3D.", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Altec Lansing Multimedia", 12); l += 7 << 16;
shadowminitext(m, l, "for tons of speakers and the", 12); l += 7 << 16;
shadowminitext(m, l, "THX-licensed sound system.", 12); l += 7 << 16;
shadowminitext(m, l, "For info call 1-800-548-0620", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Creative Labs, Inc.", 12); l += 7 << 16;
l += 3 << 16;
shadowminitext(m, l, "Thanks for the hardware, guys.", 12); l += 7 << 16;
return true;
}
else if (tilenum == CREDITSTEXT3)
{
Menu_DrawBackground(origin);
mgametextcenter(int(origin.X * 65536), int(origin.Y * 65536) + (50 << 16), "Duke Nukem 3D is a trademark of\n"
"3D Realms Entertainment"
"\n"
"Duke Nukem 3D\n"
"(C) 1996 3D Realms Entertainment");
if (VOLUMEONE)
{
mgametextcenter(int(origin.X * 65536), int(origin.Y * 65536) + (106 << 16), "Please read LICENSE.DOC for shareware\n"
"distribution grants and restrictions.");
}
mgametextcenter(int(origin.X * 65536), int(origin.Y * 65536) + ((VOLUMEONE ? 134 : 115) << 16), "Made in Dallas, Texas USA");
return true;
}
}
return false;
}
void GameInterface::DrawCenteredTextScreen(const DVector2 &origin, const char *text, int position, bool bg)
{
if (bg) Menu_DrawBackground(origin);
else
{
// Only used for the confirmation screen.
int lines = 1;
for (int i = 0; text[i]; i++) if (text[i] == '\n') lines++;
int height = lines * Menu_GetFontHeight(NIT_SmallFont);
position -= height >> 17;
Menu_DrawCursorLeft(160 << 16, 130 << 16, 65536);
}
mgametextcenter(int(origin.X * 65536), int((origin.Y + position) * 65536), text);
}
void GameInterface::DrawPlayerSprite(const DVector2& origin, bool onteam)
{
rotatesprite_fs(int(origin.X * 65536) + (260<<16), int(origin.Y*65536) + ((24+(tilesiz[APLAYER].y>>1))<<16), 49152L,0,1441-((((4-((int32_t) totalclock>>4)))&3)*5),0,onteam ? G_GetTeamPalette(playerteam) : G_CheckPlayerColor(playercolor),10);
}
void GameInterface::QuitToTitle()
{
g_player[myconnectindex].ps->gm = MODE_DEMO;
if (ud.recstat == 1)
G_CloseDemoWrite();
artClearMapArt();
}
END_DUKE_NS
//----------------------------------------------------------------------------
//
// Class registration
//
//----------------------------------------------------------------------------
static TMenuClassDescriptor<Duke::DukeMainMenu> _mm("Duke.MainMenu");
static TMenuClassDescriptor<Duke::DukeListMenu> _lm("Duke.ListMenu");
static TMenuClassDescriptor<Duke::DukeNewGameCustomSubMenu> _ngcsm("Duke.NewGameCustomSubMenu");
static TMenuClassDescriptor<Duke::DDukeImageScrollerMenu> _ism("Duke.ImageScrollerMenu");
void RegisterDukeMenus()
{
menuClasses.Push(&_mm);
menuClasses.Push(&_lm);
menuClasses.Push(&_ngcsm);
menuClasses.Push(&_ism);
}
| 33.507712 | 296 | 0.6146 | [
"3d"
] |
bdc91011e82c1f6374c03bee3abe533a4d4eb5ab | 3,846 | cpp | C++ | UnitTests/Test_Registry_GetBinaryValue.cpp | ossewawiel/LibWinRegUtil | 602e391b521685deec809e0ae3ae97376025ffe4 | [
"MIT"
] | 5 | 2020-09-17T08:15:14.000Z | 2021-06-17T08:35:51.000Z | UnitTests/Test_Registry_GetBinaryValue.cpp | ossewawiel/LibWinRegUtil | 602e391b521685deec809e0ae3ae97376025ffe4 | [
"MIT"
] | null | null | null | UnitTests/Test_Registry_GetBinaryValue.cpp | ossewawiel/LibWinRegUtil | 602e391b521685deec809e0ae3ae97376025ffe4 | [
"MIT"
] | 4 | 2019-12-29T00:58:23.000Z | 2022-01-27T12:58:36.000Z | #include "stdafx.h"
#include "Test_Registry.h"
#include "TUtils.h"
#include "TConstants.h"
using namespace std;
using namespace WinReg;
using namespace TConst;
TEST_F(Test_Registry_GetBinaryValue, when_calling_getbinaryvalue_with_valid_parameter_values_expect_no_exception)
{
try
{
vector<unsigned char> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME) };
ASSERT_FALSE(vucRegVal.empty()) << "[ FAILED ] vwsRegVal is empty";
//for (const auto &val : vucRegVal)
//{
// wcout << L"[ VALUE ] " << val << endl;
//}
}
catch (exception &ex)
{
ASSERT_TRUE(false) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
}
TEST_F(Test_Registry_GetBinaryValue, when_calling_getbinaryvalue_with_invalid_hkey_type_expect_exception)
{
try
{
vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHkeyNotDefined, WS_TEST_SUBKEY, WS_BINARY_VALUENAME) };
ASSERT_FALSE(true) << "[ FAILED ] Expected an exception";
}
catch (exception &ex)
{
ASSERT_TRUE(TUtils::InString(TUtils::ErrMsg(ex), WS_INVALID_PARAM_VALUE)) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
}
TEST_F(Test_Registry_GetBinaryValue, when_calling_getbinaryvalue_with_no_valuename_expect_exception)
{
try
{
vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, L"") };
ASSERT_FALSE(true) << "[ FAILED ] Expected an exception";
}
catch (exception &ex)
{
ASSERT_TRUE(TUtils::InString(TUtils::ErrMsg(ex), WS_CANNOT_FIND_FILE)) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
}
TEST_F(Test_Registry_GetBinaryValue, when_calling_getbinaryvalue_with_invalid_valuename_expect_exception)
{
try
{
vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_INVALID_VALNAME) };
ASSERT_FALSE(true) << "[ FAILED ] Expected an exception";
}
catch (exception &ex)
{
ASSERT_TRUE(TUtils::InString(TUtils::ErrMsg(ex), WS_CANNOT_FIND_FILE)) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
}
TEST_F(Test_Registry_GetBinaryValue, when_calling_getbinaryvalue_with_invalid_subkey_expect_exception)
{
try
{
vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_INVALID_SUBKEY, WS_BINARY_VALUENAME) };
ASSERT_FALSE(true) << "[ FAILED ] Expected an exception";
}
catch (exception &ex)
{
ASSERT_TRUE(TUtils::InString(TUtils::ErrMsg(ex), WS_CANNOT_FIND_FILE)) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
}
TEST_F(Test_Registry_GetBinaryValue, when_calling_getbinaryvalue_with_invalid_subkey_and_returndefault_set_expect_no_exception_and_empty_vector)
{
try
{
vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_INVALID_SUBKEY, WS_BINARY_VALUENAME, true) };
ASSERT_EQ(vucRegVal.size(), 0) << "[ FAILED ] vwsRegVal.size() is not 0";
}
catch (exception &ex)
{
ASSERT_TRUE(false) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
}
TEST_F(Test_Registry_GetBinaryValue, when_calling_getbinaryvalue_with_invalid_valuename_and_returndefault_set_expect_no_exception_and_empty_vector)
{
try
{
vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_INVALID_VALNAME, true) };
ASSERT_EQ(vucRegVal.size(), 0) << "[ FAILED ] vwsRegVal.size() is not 0";
}
catch (exception &ex)
{
ASSERT_TRUE(false) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
} | 29.358779 | 147 | 0.725689 | [
"vector"
] |
bdca5289a007d7b3e95c42d5ea2297d016965380 | 5,015 | cpp | C++ | Causality/main.cpp | ArcEarth/SrInspection | 63c540d1736e323a0f409914e413cb237f03c5c9 | [
"MIT"
] | 3 | 2016-07-13T18:30:33.000Z | 2020-03-31T22:20:34.000Z | Causality/main.cpp | ArcEarth/SrInspection | 63c540d1736e323a0f409914e413cb237f03c5c9 | [
"MIT"
] | null | null | null | Causality/main.cpp | ArcEarth/SrInspection | 63c540d1736e323a0f409914e413cb237f03c5c9 | [
"MIT"
] | 5 | 2016-01-16T14:25:28.000Z | 2017-06-12T16:15:18.000Z | // Source.cpp : Defines the entry point for the console application.
//
#include "pch_bcl.h"
#include "CausalityApplication.h"
//#include <fbxsdk.h>
using namespace std;
using namespace Causality;
using namespace DirectX;
#include <Windows.h>
#include <string>
#include <vector>
#if defined(__cplusplus_winrt)
using namespace Platform;
using namespace Windows::Globalization;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
[Platform::MTAThread]
int WinMain(Platform::Array<Platform::String^>^ args)
#else
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
)
#endif
{
std::vector<std::string> args;
//for (size_t i = 0; i < argc; i++)
//{
// args[i] = argv[i];
//}
return Application::Invoke<Causality::App>(args);
//Leap::Controller controller;
//SampleListener listener;
//controller.addListener(listener);
//window = make_shared<Platform::NativeWindow>();
//window->Initialize(ref new String(L"Causality"), 1280U, 720,false);
//deviceResources = make_shared<DirectX::DeviceResources>();
//deviceResources->SetNativeWindow(window->Handle());
//auto pRift = std::make_shared<Platform::Devices::OculusRift>();
//auto pPlayer = std::make_unique<Player>();
//try
//{
// pRift->Initialize(window->Handle(), deviceResources.get());
// pRift->DissmisHealthWarnning();
//}
//catch (std::runtime_error exception)
//{
// pRift = nullptr;
//}
//if (pRift)
//{
// pPlayer->EnableStereo(pRift);
//}
//m_main = make_unique<Causality::DXAppMain>(deviceResources);
//pPlayer->SetPosition(Fundation::Vector3(0.0f, 0.7f, 1.5f));
//pPlayer->FocusAt(Fundation::Vector3(0, 0, 0), Fundation::Vector3(0.0f, 1.0f, 0));
//auto size = deviceResources->GetOutputSize();
//pPlayer->SetFov(75.f*XM_PI / 180.f, size.Width / size.Height);
//MSG msg;
//bool done = false;
//while (!done)
//{
// // Handle the windows messages.
// if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
// {
// TranslateMessage(&msg);
// DispatchMessage(&msg);
// }
// // If windows signals to end the application then exit out.
// if (msg.message == WM_QUIT)
// {
// done = true;
// }
// else
// {
// m_main->Update();
// if (pRift)
// {
// pRift->BeginFrame();
// // Otherwise do the frame processing.
// for (int eye = 0; eye < 2; eye++)
// {
// pRift->EyeTexture((DirectX::Scene::EyesEnum) eye).SetAsRenderTarget(deviceResources->GetD3DDeviceContext(), pRift->DepthStencilBuffer());
// auto view = pPlayer->GetViewMatrix((DirectX::Scene::EyesEnum) eye);
// auto projection = pPlayer->GetProjectionMatrix((DirectX::Scene::EyesEnum) eye);
// m_main->m_sceneRenderer->UpdateViewMatrix(view);
// m_main->m_sceneRenderer->UpdateProjectionMatrix(projection);
// m_main->m_pSkyBox->UpdateViewMatrix(view);
// m_main->m_sceneRenderer->UpdateProjectionMatrix(projection);
// m_main->Render();
// }
// pRift->EndFrame();
// }
// else
// {
// auto context = deviceResources->GetD3DDeviceContext();
// // Reset the viewport to target the whole screen.
// auto viewport = deviceResources->GetScreenViewport();
// context->RSSetViewports(1, &viewport);
// ID3D11RenderTargetView *const targets[1] = { deviceResources->GetBackBufferRenderTargetView() };
// context->OMSetRenderTargets(1, targets, deviceResources->GetDepthStencilView());
// context->ClearRenderTargetView(deviceResources->GetBackBufferRenderTargetView(), DirectX::Colors::White);
// context->ClearDepthStencilView(deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
//
// auto view = pPlayer->GetViewMatrix();
// auto projection = pPlayer->GetProjectionMatrix();
// m_main->m_sceneRenderer->UpdateViewMatrix(view);
// m_main->m_sceneRenderer->UpdateProjectionMatrix(projection);
// m_main->m_sceneRenderer->Render(context);
// m_main->m_pSkyBox->UpdateViewMatrix(view);
// m_main->m_pSkyBox->UpdateProjectionMatrix(projection);
// m_main->m_pSkyBox->Render(context);
// //m_main->Render();
// deviceResources->Present();
// }
// }
//}
////std::cin.get();
////auto calendar = ref new Calendar;
////calendar->SetToNow();
////wcout << "It's now " << calendar->HourAsPaddedString(2)->Data() << L":" <<
//// calendar->MinuteAsPaddedString(2)->Data() << L":" <<
//// calendar->SecondAsPaddedString(2)->Data() << endl;
////Platform::Details::Console::WriteLine("Hello World");
//controller.removeListener(listener);
//system("Pause");
return 0;
}
//void OnActivated(Causality::Window ^sender, Windows::UI::Core::WindowActivatedEventArgs ^args)
//{
// Platform::Details::Console::WriteLine("Lalalaa Demacia!");
//}
| 31.34375 | 144 | 0.689332 | [
"render",
"vector"
] |
bdd62610f0433e38bad6eab37e365c8b85157533 | 5,666 | cpp | C++ | RagePawn/pawn.cpp | infin1tyy/ragepawn | 20d5fea0ea3763a1a49654a34d03884a241716d7 | [
"MIT"
] | 4 | 2019-04-14T11:40:03.000Z | 2020-06-07T16:07:28.000Z | RagePawn/pawn.cpp | infin1tyy/ragepawn | 20d5fea0ea3763a1a49654a34d03884a241716d7 | [
"MIT"
] | 2 | 2019-04-13T14:54:04.000Z | 2019-05-03T14:11:45.000Z | RagePawn/pawn.cpp | infin1tyy/ragepawn | 20d5fea0ea3763a1a49654a34d03884a241716d7 | [
"MIT"
] | 5 | 2019-04-10T00:49:57.000Z | 2022-01-04T05:57:44.000Z | #include "pawn.hpp"
#include "../amxlib/amxaux.h"
#include <filesystem>
#include "format.hpp"
#pragma comment( lib, "winmm.lib") // amx_TimeInit(&amx);
#pragma comment( lib, "ws2_32.lib") // amx_DGramInit(&amx);
#include "callbacks.hpp"
namespace fs = std::experimental::filesystem;
extern "C" {
int AMXEXPORT AMXAPI amx_ConsoleInit(AMX *amx);
int AMXEXPORT AMXAPI amx_ConsoleCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_StringInit(AMX *amx);
int AMXEXPORT AMXAPI amx_StringCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_CoreInit(AMX *amx);
int AMXEXPORT AMXAPI amx_CoreCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_DGramInit(AMX *amx);
int AMXEXPORT AMXAPI amx_DGramCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_FileInit(AMX *amx);
int AMXEXPORT AMXAPI amx_FileCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_FloatInit(AMX *amx);
int AMXEXPORT AMXAPI amx_FloatCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_FixedInit(AMX *amx);
int AMXEXPORT AMXAPI amx_FixedCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_TimeInit(AMX *amx);
int AMXEXPORT AMXAPI amx_TimeCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_ProcessInit(AMX *amx);
int AMXEXPORT AMXAPI amx_ProcessCleanup(AMX *amx);
int AMXEXPORT AMXAPI amx_ArgsInit(AMX *amx);
int AMXEXPORT AMXAPI amx_ArgsCleanup(AMX *amx);
}
int amx_playerInit(AMX *amx);
int amx_utilInit(AMX *amx);
Pawn::Pawn()
{
std::cout << "Initializing RagePawn.." << std::endl;
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
const std::string::size_type pos = std::string(buffer).find_last_of("\\/");
std::string path = std::string(buffer).substr(0, pos);
Iterate(path.append("\\amx\\filterscripts"), true);
path.clear();
path = std::string(buffer).substr(0, pos);
std::cout << std::endl;
Iterate(path.append("\\amx\\gamemodes"), false);
}
void Pawn::Iterate(const std::string& path, const bool fs)
{
std::cout << "-> Loading " << path.substr(path.find_last_of("\\/") + 1) << ".." << std::endl;
for (const auto & p : fs::directory_iterator(path))
{
const auto path_str = p.path().string();
const auto filename = path_str.substr(path_str.find_last_of("\\/") + 1);
if (filename.substr(filename.find_last_of('.') + 1) != "amx") continue;
std::cout << "--> Loading '" << filename << "'.." << std::endl;
RunAMX(path_str, fs);
}
}
void Pawn::RunAMX(const std::string& path, const bool fs)
{
AMX amx;
const auto path_str = path.c_str();
const int err = aux_LoadProgram(&amx, (char*)path_str, NULL);
if (err != AMX_ERR_NONE) TerminateLoad(path.substr(path.find_last_of("\\/") + 1));
amx_ConsoleInit(&amx);
amx_StringInit(&amx);
amx_CoreInit(&amx);
amx_DGramInit(&amx);
amx_FloatInit(&amx);
amx_FileInit(&amx);
amx_FixedInit(&amx);
amx_TimeInit(&amx);
amx_ProcessInit(&amx);
amx_ArgsInit(&amx);
amx_utilInit(&amx);
amx_playerInit(&amx);
//int count;
//amx_NumNatives(&amx, &count);
//printf("natives: %d\n", count);
//for (int i = 0; i < count; i++) {
// char temp[32];
// amx_GetNative(&amx, i, temp);
// printf(" %s\n", temp);
//}
//amx_NumPublics(&amx, &count);
//printf("publics: %d\n", count);
//for (int i = 0; i < count; i++) {
// char temp[32];
// amx_GetPublicEx(&amx, i, temp);
// printf(" %s\n", temp);
//}
amx_Exec(&amx, nullptr, AMX_EXEC_MAIN); // execute main
script scr;
scr.amx = amx;
scr.fs = fs;
scripts.push_back(scr);
fs ? CallPublic(&amx, "OnFilterScriptInit") : CallPublic(&amx, "OnGameModeInit");
}
//void Pawn::UnloadAMX()
//{
//amx_ArgsCleanup();
//amx_ProcessCleanup();
//amx_TimeCleanup();
//amx_FixedCleanup();
//amx_FileCleanup();
//amx_FloatCleanup();
//amx_DGramCleanup();
//amx_CoreCleanup();
//amx_StringCleanup();
//amx_ConsoleCleanup();
//}
int Pawn::TerminateLoad(const std::string& filename)
{
std::cout << "Error: Failed to load '" << filename << "'.." << std::endl;
return false;
}
int Pawn::Terminate(const int err)
{
printf("Run time error %d: \"%s\"\n", err, aux_StrError(err));
exit(1);
}
void Pawn::TerminateScript(AMX *amx)
{
std::cout << "Terminating script..." << std::endl;
amx_Cleanup(amx);
aux_FreeProgram(amx);
}
void Pawn::SetMultiplayer(rage::IMultiplayer *mp)
{
this->m_mp = mp;
mp->AddEventHandler(dynamic_cast<rage::IEventHandler*>(&EventHandler::GetInstance()));
}
void Pawn::CallPublic(AMX *amx, const char* name)
{
int id;
if (!amx_FindPublic(amx, name, &id))
amx_Exec(amx, nullptr, id);
}
// Note: Params must be sent in REVERSE order to the function.
void Pawn::CallPublicEx(AMX *amx, const char *name, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
int index;
int err = amx_FindPublic(amx, name, &index);
if (err != AMX_ERR_NONE)
{
if(err != AMX_ERR_NOTFOUND) Terminate(err);
return;
}
std::vector<cell*> addresses;
while (*fmt != '\0')
{
if (*fmt == 'd')
{
amx_Push(amx, (cell)va_arg(args, int));
}
else if (*fmt == 's')
{
const char * s = va_arg(args, const char*);
cell* address;
amx_PushString(amx, &address, s, 0, 0);
addresses.push_back(address);
}
else if(*fmt == 'f')
{
float f = va_arg(args, float);
}
++fmt;
}
err = amx_Exec(amx, NULL, index);
if (err != AMX_ERR_NONE) Terminate(err);
for (auto &i : addresses) {
amx_Release(amx, i);
i = NULL;
}
addresses.clear();
va_end(args);
}
int Pawn::joaat(std::string string)
{
size_t i = 0;
int32_t hash = 0;
std::transform(string.begin(), string.end(), string.begin(), ::tolower);
while (i != string.length()) {
hash += string[i++];
hash += hash << 10;
hash ^= hash >> 6;
}
hash += hash << 3;
hash ^= hash >> 11;
hash += hash << 15;
return hash;
} | 25.070796 | 94 | 0.656548 | [
"vector",
"transform"
] |
75382fdcede02f5aefdc76953d362d7315096e2d | 577 | cpp | C++ | LeetCode/C++/66. Plus One.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | LeetCode/C++/66. Plus One.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | LeetCode/C++/66. Plus One.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | //Runtime: 4 ms, faster than 67.62% of C++ online submissions for Plus One.
//Memory Usage: 7.6 MB, less than 100.00% of C++ online submissions for Plus One.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int N = digits.size();
int pos = N -1;
while(pos >= 0 && digits[pos] == 9){
//carry
digits[pos] = 0;
pos--;
}
if(pos < 0){
digits.insert(digits.begin(), 1);
}else{
digits[pos]++;
}
return digits;
}
};
| 25.086957 | 81 | 0.478336 | [
"vector"
] |
753ea4a15a3ddc29aa6ba45c6f9dddf12d5a4c76 | 37,150 | cpp | C++ | test/core.cpp | vlanore/tinycompo | c7acf325c84b68ec91eaf937ad49f17281e84079 | [
"CECILL-B"
] | null | null | null | test/core.cpp | vlanore/tinycompo | c7acf325c84b68ec91eaf937ad49f17281e84079 | [
"CECILL-B"
] | null | null | null | test/core.cpp | vlanore/tinycompo | c7acf325c84b68ec91eaf937ad49f17281e84079 | [
"CECILL-B"
] | null | null | null | /* Copyright or © or Copr. Centre National de la Recherche Scientifique (CNRS) (2017/05/03)
Contributors:
- Vincent Lanore <vincent.lanore@gmail.com>
This software is a computer program whose purpose is to provide the necessary classes to write ligntweight component-based
c++ applications.
This software is governed by the CeCILL-B license under French law and abiding by the rules of distribution of free software.
You can use, modify and/ or redistribute the software under the terms of the CeCILL-B license as circulated by CEA, CNRS and
INRIA at the following URL "http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users
are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive
licensors have only limited liability.
In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or
reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated
to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth
computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements
in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in
the same conditions as regards security.
The fact that you are presently reading this means that you have had knowledge of the CeCILL-B license and that you accept
its terms.*/
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "test_utils.hpp"
using namespace std;
/*
=============================================================================================================================
~*~ Debug ~*~
===========================================================================================================================*/
TEST_CASE("Demangling test") {
CHECK(TinycompoDebug::type<void*(int, int)>() == "void* (int, int)");
CHECK(TinycompoDebug::type<_Port<MyCompo>>() == "tc::_Port<MyCompo>");
}
TEST_CASE("Exception overhaul tests") {
TinycompoException e1("An error occured");
TinycompoException e2("Something went wrong in context:", e1);
CHECK(string(e1.what()) == "An error occured");
CHECK(string(e2.what()) == "Something went wrong in context:");
}
/*
=============================================================================================================================
~*~ _Port ~*~
===========================================================================================================================*/
TEST_CASE("_Port tests.") {
class MyCompo {
public:
int i{1};
int j{2};
void setIJ(int iin, int jin) {
i = iin;
j = jin;
}
};
MyCompo compo;
auto ptr = static_cast<_AbstractPort*>(new _Port<int, int>{&compo, &MyCompo::setIJ});
auto ptr2 = dynamic_cast<_Port<int, int>*>(ptr);
REQUIRE(ptr2 != nullptr);
ptr2->_set(3, 4);
CHECK(compo.i == 3);
CHECK(compo.j == 4);
delete ptr;
}
/*
=============================================================================================================================
~*~ Component ~*~
===========================================================================================================================*/
TEST_CASE("Component tests.") {
MyCompo compo{};
// MyCompo compo2 = compo; // does not work because Component copy is forbidden (intentional)
CHECK(compo.debug() == "MyCompo");
compo.set("myPort", 17, 18);
CHECK(compo.i == 17);
CHECK(compo.j == 18);
TINYCOMPO_TEST_ERRORS { compo.set("myPort", true); }
TINYCOMPO_TEST_ERRORS_END("Setting property failed. Type tc::_Port<bool const> does not seem to match port myPort.");
TINYCOMPO_TEST_MORE_ERRORS { compo.set("badPort", 1, 2); }
TINYCOMPO_TEST_ERRORS_END("Port name not found. Could not find port badPort in component MyCompo.");
}
TEST_CASE("Component without debug") {
struct MyBasicCompo : public Component {};
MyBasicCompo compo{};
CHECK(compo.debug() == "Component");
}
TEST_CASE("Component get errors") {
struct MyBasicCompo : public Component {
int data;
MyBasicCompo() {
port("p1", &MyBasicCompo::data);
port("p2", &MyBasicCompo::data);
}
};
MyBasicCompo compo{};
TINYCOMPO_TEST_ERRORS { compo.get("p3"); }
TINYCOMPO_TEST_ERRORS_END("<Component::get> Port name p3 not found. Existing ports are:\n * p1\n * p2\n");
TINYCOMPO_TEST_MORE_ERRORS { compo.get<int>("p3"); }
TINYCOMPO_TEST_ERRORS_END("<Component::get<Interface>> Port name p3 not found. Existing ports are:\n * p1\n * p2\n");
}
/*
=============================================================================================================================
~*~ _ComponentBuilder ~*~
===========================================================================================================================*/
TEST_CASE("_ComponentBuilder tests.") {
_ComponentBuilder compo(_Type<MyCompo>(), "youpi", 3, 4); // create _ComponentBuilder object
auto ptr = compo._constructor(); // instantiate actual object
auto ptr2 = dynamic_cast<MyCompo*>(ptr.get());
REQUIRE(ptr2 != nullptr);
CHECK(ptr2->i == 3);
CHECK(ptr2->j == 4);
CHECK(compo.name == "youpi");
CHECK(compo.type == "MyCompo"); // technically compiler-dependant, but should work with gcc/clang
}
/*
=============================================================================================================================
~*~ Address ~*~
===========================================================================================================================*/
struct MyKey {
int i;
};
ostream& operator<<(ostream& os, MyKey const& m) { return os << m.i; }
TEST_CASE("Address/PortAddress to stream") {
std::stringstream ss;
Address a("a", "b", "c");
ss << a;
CHECK(ss.str() == "a__b__c");
ss.str("");
PortAddress p("ptr", "a", "b");
ss << p;
CHECK(ss.str() == "a__b.ptr");
}
TEST_CASE("key_to_string test.") {
CHECK(key_to_string(3) == "3");
CHECK(key_to_string("yolo") == "yolo");
MyKey key = {3};
CHECK(key_to_string(key) == "3");
}
TEST_CASE("Address tests.") {
auto a = Address("a", 2, 3, "b");
CHECK(a.first() == "a");
CHECK(a.rest().first() == "2");
CHECK(a.rest().rest().first() == "3");
CHECK(a.rest().rest().rest().first() == "b");
CHECK(a.is_composite() == true);
CHECK(Address("youpi").is_composite() == false);
CHECK(a.to_string() == "a__2__3__b");
CHECK(Address(a, 17).to_string() == "a__2__3__b__17");
Address b("a", "b");
Address c("c", "d");
Address e(b, c);
CHECK(e.to_string() == "a__b__c__d");
}
TEST_CASE("Address: builder from string") {
Address a("Omega__3__1");
CHECK(a.first() == "Omega");
CHECK(a.rest().first() == "3");
CHECK(a.rest().rest().first() == "1");
}
TEST_CASE("Address: == operator") {
Address abc("a", "b", "c");
Address abb("a", "b", "b");
Address ab("a", "b");
Address abc2("a", "b", "c");
CHECK(not(abc == abb));
CHECK(not(abc == ab));
CHECK(abc == abc);
CHECK(abc == abc2);
}
TEST_CASE("PortAddress == operator") {
PortAddress ra("ptr", "a");
PortAddress rab("ptr", "a", "b");
PortAddress ta("ptt", "a");
PortAddress rab2("ptr", "a", "b");
CHECK(not(ra == rab));
CHECK(not(ra == ta));
CHECK(rab == rab);
CHECK(rab == rab2);
}
TEST_CASE("Address: is_ancestor") {
Address e;
Address a("a");
Address abc("a", "b", "c");
Address abc2("a", "b", "c");
Address abd("a", "b", "d");
Address dbc("d", "b", "c");
Address ab("a", "b");
CHECK(e.is_ancestor(a));
CHECK(e.is_ancestor(abc));
CHECK(a.is_ancestor(abc));
CHECK(abc.is_ancestor(abc));
CHECK(abc.is_ancestor(abc2));
CHECK(ab.is_ancestor(abc));
CHECK(not ab.is_ancestor(dbc));
CHECK(not abc.is_ancestor(abd));
}
TEST_CASE("Address: rebase") {
Address ab("a", "b");
Address abcd("a", "b", "c", "d");
Address cd("c", "d");
CHECK(abcd.rebase(ab) == cd);
TINYCOMPO_TEST_ERRORS { cd.rebase(ab); }
TINYCOMPO_TEST_ERRORS_END("Trying to rebase address c__d from a__b although it is not an ancestor!\n")
}
TEST_CASE("Address: suffix") {
Address a("a", "b", "c", "de");
CHECK(a.format_last("log(%s)") == Address("a", "b", "c", "log(de)"));
}
TEST_CASE("Address: error for keyrs with __") {
TINYCOMPO_TEST_ERRORS { Address a("a", "b", "c__d"); }
TINYCOMPO_TEST_ERRORS_END("Trying to add key c__d (which contains __) of type char const* to address a__b\n");
TINYCOMPO_TEST_MORE_ERRORS { Address a(Address("a", "b"), "c__d"); }
TINYCOMPO_TEST_ERRORS_END("Trying to add key c__d (which contains __) of type char const* to address a__b\n");
}
TEST_CASE("Address::c_str") {
Address a("a", "b", "c");
CHECK(strcmp(a.c_str(), "a__b__c") == 0);
}
TEST_CASE("Address, first and last") {
Address a("aazz", "baz", "caz");
CHECK(a.last() == "caz");
CHECK(a.first() == "aazz");
CHECK(Address().last() == "");
CHECK(Address().first() == "");
}
TEST_CASE("Address: to_string with custom sep") {
Address a("a", "b", "c");
CHECK(a.to_string(".") == "a.b.c");
CHECK(a.to_string("") == "abc");
CHECK(Address().to_string("-") == "");
}
/*
=============================================================================================================================
~*~ Model ~*~
===========================================================================================================================*/
TEST_CASE("model test: components in composites") {
Model model;
model.composite("compo0");
model.component<MyInt>(Address("compo0", 1), 5);
model.composite(Address("compo0", 2));
model.component<MyInt>(Address("compo0", 2, 1), 3);
CHECK(model.size() == 1); // top level contains only one component which is a composite
auto& compo0 = model.get_composite("compo0");
CHECK(compo0.size() == 2);
auto& compo0_2 = compo0.get_composite(2);
CHECK(compo0_2.size() == 1);
auto& compo0_3 = model.get_composite(Address("compo0", 2));
CHECK(compo0_3.size() == 1);
TINYCOMPO_TEST_ERRORS { model.component<MyInt>(Address("badAddress", 1), 2); }
TINYCOMPO_TEST_ERRORS_END(
"Composite not found. Composite badAddress does not exist. Existing composites are:\n * compo0\n");
}
TEST_CASE("model test: model copy") {
Model model;
model.composite("compo0");
auto model2 = model;
model2.component<MyInt>(Address("compo0", 1), 19);
model2.component<MyInt>("compo1", 17);
CHECK(model.size() == 1);
CHECK(model2.size() == 2);
}
TEST_CASE("model test: composite referencees") {
Model model;
model.composite("compo0");
auto& compo0ref = model.get_composite("compo0");
compo0ref.component<MyCompo>(1, 17, 18);
compo0ref.component<MyCompo>(2, 21, 22);
CHECK(model.size() == 1);
CHECK(model.get_composite("compo0").size() == 2);
}
struct MyBasicCompo : public Component {
MyBasicCompo* buddy{nullptr};
std::string data;
MyBasicCompo() {
port("buddy", &MyBasicCompo::setBuddy);
port("data", &MyBasicCompo::data);
}
void setBuddy(MyBasicCompo* buddyin) { buddy = buddyin; }
};
TEST_CASE("Model test: dot output and representation print") {
Model model;
model.component<MyBasicCompo>("mycompo");
model.composite("composite");
model.component<MyBasicCompo>(Address("composite", 2));
model.connect<Use<MyBasicCompo>>(PortAddress("buddy", "mycompo"), Address("composite", 2));
stringstream ss;
model.dot(ss);
CHECK(ss.str() ==
"graph g {\n\tsep=\"+25,25\";\n\tnodesep=0.6;\n\tmycompo [label=\"mycompo\\n(MyBasicCompo)\" shape=component "
"margin=0.15];\n\tconnect_0 "
"[xlabel=\"tc::Use<MyBasicCompo>\" shape=point];\n\tconnect_0 -- mycompo[xlabel=\"buddy\"];\n\tconnect_0 -- "
"composite__2;\n\tsubgraph cluster_composite {\n\t\tcomposite__2 [label=\"2\\n(MyBasicCompo)\" shape=component "
"margin=0.15];\n\t}\n}\n");
stringstream ss2;
model.print(ss2);
CHECK(
ss2.str() ==
"Component \"mycompo\" (MyBasicCompo)\nConnector (tc::Use<MyBasicCompo>) ->mycompo.buddy ->composite__2 \nComposite "
"composite {\n Component \"2\" (MyBasicCompo)\n}\n");
}
TEST_CASE("Model test: addresses passed as strings detected as such by representation") {
Model model;
model.component<MyBasicCompo>("mycompo")
.connect<Use<MyBasicCompo>>("buddy", "compo2")
.connect<Set<string>>("data", "youpi");
stringstream ss;
model.print(ss);
CHECK((ss.str() ==
"Component \"mycompo\" (MyBasicCompo)\n"
"Connector (tc::Use<MyBasicCompo>) ->mycompo.buddy ->compo2 \n"
"Connector (tc::Set<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >) "
"->mycompo.data \n" or
ss.str() == "Component \"mycompo\" (MyBasicCompo)\n"
"Connector (tc::Use<MyBasicCompo>) ->mycompo.buddy ->compo2 \n"
"Connector (tc::Set<std::string>) ->mycompo.data \n"));
}
TEST_CASE("Model test: temporary keys") {
Model model;
for (int i = 0; i < 5; i++) {
stringstream ss;
ss << "compo" << i;
model.component<MyInt>(ss.str());
}
CHECK(model.size() == 5);
}
TEST_CASE("Model test: copy") {
Model model2;
model2.component<MyIntProxy>("compo3");
Assembly assembly(model2);
Model model3 = model2; // copy
model3.component<MyInt>("youpi", 17);
model2.component<MyInt>("youpla", 19);
Assembly assembly3(model3);
CHECK(assembly3.at<MyInt>("youpi").get() == 17);
TINYCOMPO_TEST_ERRORS { assembly3.at("youpla"); }
TINYCOMPO_THERE_WAS_AN_ERROR;
Assembly assembly4(model2);
CHECK(assembly4.at<MyInt>("youpla").get() == 19);
TINYCOMPO_TEST_MORE_ERRORS { assembly4.at("youpi"); }
TINYCOMPO_THERE_WAS_AN_ERROR;
TINYCOMPO_TEST_MORE_ERRORS { assembly.at("youpi"); } // checking that assembly (originally built from model2)
TINYCOMPO_THERE_WAS_AN_ERROR; // has not been modified (and has an actual copy)
TINYCOMPO_TEST_MORE_ERRORS { assembly.at("youpla"); }
TINYCOMPO_THERE_WAS_AN_ERROR;
}
TEST_CASE("Model test: copy and composites") {
Model model1;
model1.composite("composite");
Model model2 = model1; // copy
model1.component<MyInt>(Address("composite", 'r'), 17);
stringstream ss;
model2.print(ss); // should not contain composite_r
CHECK(ss.str() == "Composite composite {\n}\n");
}
TEST_CASE("Model test: digraph export") {
Model model;
model.component<MyInt>("d", 3);
model.component<MyInt>("e", 5);
model.component<IntReducer>("c");
model.connect<Use<IntInterface>>(PortAddress("ptr", "c"), Address("d"));
model.connect<Use<IntInterface>>(PortAddress("ptr", "c"), Address("e"));
// model.connect<Use<IntInterface>>(PortAddress("ptr", "c"), "e"); // TODO TODO WHY DOES THIS WORKS
model.component<MyIntProxy>("a");
model.component<MyIntProxy>("b");
model.connect<Use<IntInterface>>(PortAddress("ptr", "a"), Address("c"));
model.connect<Use<IntInterface>>(PortAddress("ptr", "b"), Address("c"));
auto graph = model.get_digraph();
CHECK((graph.first == set<string>{"a", "b", "c", "d", "e"}));
CHECK((graph.second ==
multimap<string, string>{make_pair("a", "c"), make_pair("b", "c"), make_pair("c", "d"), make_pair("c", "e")}));
}
TEST_CASE("_AssemblyGraph test: all_component_names") {
Model model;
model.component<MyInt>(0, 17);
model.component<MyInt>(2, 31);
model.composite(1);
model.component<MyInt>(Address(1, 'r'), 21);
model.composite(Address(1, 't'));
model.component<MyInt>(Address(1, 't', 'l'), 23);
vector<string> vec0 = model.all_component_names();
vector<string> vec1 = model.all_component_names(1);
vector<string> vec2 = model.all_component_names(2);
vector<string> vec3 = model.all_component_names(2, true);
CHECK((set<string>(vec0.begin(), vec0.end())) == (set<string>{"0", "2"}));
CHECK((set<string>(vec1.begin(), vec1.end())) == (set<string>{"0", "2", "1__r"}));
CHECK((set<string>(vec2.begin(), vec2.end())) == (set<string>{"0", "2", "1__r", "1__t__l"}));
CHECK((set<string>(vec3.begin(), vec3.end())) == (set<string>{"0", "1", "1__t", "2", "1__r", "1__t__l"}));
}
TEST_CASE("Model test: composite not found") {
Model model;
model.composite("youpi");
model.composite("youpla");
TINYCOMPO_TEST_ERRORS { model.get_composite("youplaboum"); }
TINYCOMPO_TEST_ERRORS_END(
"Composite not found. Composite youplaboum does not exist. Existing composites are:\n * youpi\n * youpla\n");
const Model model2{model}; // testing const version of error
TINYCOMPO_TEST_MORE_ERRORS { model2.get_composite("youplaboum"); }
TINYCOMPO_TEST_ERRORS_END(
"Composite not found. Composite youplaboum does not exist. Existing composites are:\n * youpi\n * youpla\n");
}
TEST_CASE("Model test: is_composite") {
Model model;
model.component<MyInt>("a", 17);
model.composite("b");
model.component<MyInt>(Address("b", "c"), 19);
CHECK(model.is_composite("a") == false);
CHECK(model.is_composite("b") == true);
CHECK(model.is_composite(Address("b", "c")) == false);
}
TEST_CASE("Model test: has_type") {
Model model;
model.component<MyInt>("a", 17);
model.composite("b");
model.component<MyIntProxy>(Address("b", "c"));
CHECK(model.has_type<MyInt>("a") == true);
CHECK(model.has_type<MyIntProxy>("a") == false);
CHECK(model.has_type<MyInt>("b") == false);
CHECK(model.has_type<MyIntProxy>("b") == false);
CHECK(model.has_type<MyInt>(Address("b", "c")) == false);
CHECK(model.has_type<MyIntProxy>(Address("b", "c")) == true);
}
TEST_CASE("Model test: exists") {
Model model;
model.component<MyInt>("a", 17);
model.composite("b");
model.component<MyInt>(Address("b", "c"), 19);
CHECK(model.exists("a") == true);
CHECK(model.exists("c") == false);
CHECK(model.exists("youplaboum") == false);
CHECK(model.exists("b") == true);
CHECK(model.exists(Address("b", "c")) == true);
}
TEST_CASE("Model test: all_addresses") {
Model model;
model.component<MyInt>("a", 17);
model.composite("b");
model.composite(Address("b", "c"));
model.component<MyInt>(Address("b", "c", "d"), 19);
vector<Address> expected_result{"a", Address("b", "c", "d")}, expected_result2{Address("c", "d")};
CHECK(model.all_addresses() == expected_result);
CHECK(model.all_addresses("b") == expected_result2);
}
/*
=============================================================================================================================
~*~ Meta things ~*~
===========================================================================================================================*/
template <class Interface>
struct UseOrArrayUse : public Meta {
static void connect(Model& model, PortAddress user, Address provider) {
if (model.is_composite(provider)) {
model.connect<MultiUse<Interface>>(user, provider);
} else {
model.connect<Use<Interface>>(user, provider);
}
}
};
TEST_CASE("Meta connections") {
Model model;
model.component<Array<MyInt>>("array", 5, 17);
model.component<IntReducer>("reducer");
model.component<MyIntProxy>("proxy");
model.connect<UseOrArrayUse<IntInterface>>(PortAddress("ptr", "reducer"), Address("array"));
model.connect<UseOrArrayUse<IntInterface>>(PortAddress("ptr", "proxy"), Address("reducer"));
Assembly assembly(model);
CHECK(assembly.at<IntInterface>("proxy").get() == 170);
}
struct MyIntWrapper : Meta {
static ComponentReference connect(Model& model, Address name, int value) { return model.component<MyInt>(name, value); }
};
TEST_CASE("Meta components") {
Model model;
model.composite("a");
model.component<MyIntWrapper>(Address("a", "b"), 17);
Assembly assembly(model);
CHECK(assembly.at<IntInterface>(Address("a", "b")).get() == 17);
}
/*
=============================================================================================================================
~*~ Assembly ~*~
===========================================================================================================================*/
TEST_CASE("Assembly test: instances and call.") {
Model a;
a.component<MyCompo>("Compo1", 13, 14);
a.component<MyCompo>("Compo2", 15, 16);
CHECK(a.size() == 2);
Assembly b(a);
auto& ref = b.at<MyCompo&>("Compo1");
auto& ref2 = b.at<MyCompo&>("Compo2");
CHECK(ref.j == 14);
CHECK(ref2.j == 16);
b.call("Compo2", "myPort", 77, 79);
CHECK(ref2.i == 77);
CHECK(ref2.j == 79);
b.call(PortAddress("myPort", "Compo2"), 17, 19);
CHECK(ref2.i == 17);
CHECK(ref2.j == 19);
stringstream ss;
b.print(ss);
CHECK(ss.str() == "Compo1: MyCompo\nCompo2: MyCompo\n");
}
TEST_CASE("Assembly test: instantiating composites.") {
Model model;
model.composite("composite");
model.component<MyInt>(Address("composite", 0), 12);
Assembly assembly(model);
stringstream ss;
assembly.print(ss);
CHECK(ss.str() == "composite: Composite {\n0: MyInt\n}\n");
auto& refComposite = assembly.at<Assembly>("composite");
CHECK(refComposite.size() == 1);
CHECK(refComposite.at<MyInt>(0).get() == 12);
}
TEST_CASE("Assembly test: sub-addressing tests.") {
Model model;
model.composite("Array");
model.component<MyCompo>(Address("Array", 0), 12, 13);
model.component<MyCompo>(Address("Array", 1), 15, 19);
model.composite(Address("Array", 2));
model.component<MyCompo>(Address("Array", 2, "youpi"), 7, 9);
Assembly assembly(model);
auto& arrayRef = assembly.at<Assembly>("Array");
CHECK(arrayRef.size() == 3);
auto& subArrayRef = assembly.at<Assembly>(Address("Array", 2));
CHECK(subArrayRef.size() == 1);
auto& subRef = assembly.at<MyCompo>(Address("Array", 1));
auto& subSubRef = assembly.at<MyCompo>(Address("Array", 2, "youpi"));
CHECK(subRef.i == 15);
CHECK(subSubRef.i == 7);
}
TEST_CASE("Assembly test: incorrect address.") {
Model model;
model.component<MyCompo>("compo0");
model.component<MyCompo>("compo1");
Assembly assembly(model);
TINYCOMPO_TEST_ERRORS { assembly.at<MyCompo>("compo"); }
TINYCOMPO_TEST_ERRORS_END(
"<Assembly::at> Trying to access incorrect address. Address compo does not exist. Existing addresses are:\n * "
"compo0\n * compo1\n");
}
TEST_CASE("Assembly test: component names.") {
Model model;
model.component<MyCompo>("compoYoupi");
model.component<MyCompo>("compoYoupla");
model.composite("composite");
model.component<MyCompo>(Address("composite", 3));
Assembly assembly(model);
CHECK(assembly.at<MyCompo>("compoYoupi").get_name() == "compoYoupi");
CHECK(assembly.at<MyCompo>("compoYoupla").get_name() == "compoYoupla");
CHECK(assembly.at<MyCompo>(Address("composite", 3)).get_name() == "composite__3");
}
TEST_CASE("Assembly test: get_model.") {
Model model;
model.component<MyCompo>("youpi");
Assembly assembly(model);
Model model2 = assembly.get_model();
model.component<MyCompo>("youpla");
CHECK(model2.size() == 1);
CHECK(model.size() == 2);
stringstream ss;
model2.print(ss);
CHECK(ss.str() == "Component \"youpi\" (MyCompo)\n"); // technically compiler-dependant
}
TEST_CASE("Assembly test: composite ports.") {
struct GetInt {
virtual int getInt() = 0;
};
struct User : public Component {
GetInt* ptr{nullptr};
void setPtr(GetInt* ptrin) { ptr = ptrin; }
User() { port("ptr", &User::setPtr); }
};
struct Two : public GetInt {
int getInt() override { return 2; }
};
struct Provider : public Component {
Two two;
GetInt* providePtr() { return &two; }
Provider() { provide("int", &Provider::providePtr); }
};
struct MyFancyComposite : public Composite {
void after_construct() override {
provide<IntInterface>("int", Address("a"));
provide<IntInterface>("proxy", Address("b"));
provide<GetInt>("prov", PortAddress("int", "p"));
}
static void contents(Model& model) {
model.component<MyInt>("a", 7);
model.component<MyIntProxy>("b");
model.connect<Use<IntInterface>>(PortAddress("ptr", "b"), "a");
model.component<Provider>("p");
}
};
Model model;
model.component<MyFancyComposite>("composite");
model.component<MyIntProxy>("myProxy");
model.connect<UseProvide<IntInterface>>(PortAddress("ptr", "myProxy"), PortAddress("int", "composite"));
model.component<User>("u");
model.connect<UseProvide<GetInt>>(PortAddress("ptr", "u"), PortAddress("prov", "composite"));
Assembly assembly(model);
CHECK(assembly.at<IntInterface>("myProxy").get() == 14);
CHECK(assembly.at<User>("u").ptr->getInt() == 2);
}
TEST_CASE("Assembly: derives_from and is_composite") {
Model model;
model.component<MyInt>("a", 1);
model.composite("b");
model.component<MyInt>(Address("b", "c"), 3);
model.composite(Address("b", "d"));
Assembly assembly(model);
CHECK(assembly.is_composite("a") == false);
CHECK(assembly.is_composite("b") == true);
CHECK(assembly.is_composite(Address("b", "c")) == false);
CHECK(assembly.is_composite(Address("b", "d")) == true);
CHECK(assembly.derives_from<IntInterface>("a") == true);
CHECK(assembly.derives_from<IntInterface>("b") == false);
}
TEST_CASE("Assembly: instantiate from new model") {
Model model;
model.component<MyInt>("a", 1);
model.composite("b");
model.component<MyInt>(Address("b", "c"), 3);
Model model2;
model2.component<MyInt>("a", 3);
model2.composite("c");
model2.component<MyInt>(Address("c", "d"), 17);
Assembly assembly(model);
assembly.instantiate_from(model2);
CHECK(assembly.at<MyInt>("a").get() == 3);
CHECK(assembly.at<MyInt>(Address("c", "d")).get() == 17);
TINYCOMPO_TEST_ERRORS { assembly.at<MyInt>(Address("b", "c")); }
TINYCOMPO_TEST_ERRORS_END(
"<Assembly::at> Trying to access incorrect address. Address b does not exist. "
"Existing addresses are:\n * a\n * c\n");
}
TEST_CASE("Assembly: at with port address") {
class SillyWrapper : public Component {
MyInt wrappee;
MyInt* provide_wrappee() { return &wrappee; }
public:
SillyWrapper(int init) : wrappee(init) { provide("port", &SillyWrapper::provide_wrappee); }
};
Model model;
model.component<SillyWrapper>("c", 1717);
Assembly assembly(model);
auto& wref = assembly.at<MyInt>(PortAddress("port", "c"));
CHECK(wref.get() == 1717);
}
TEST_CASE("Assembly: at with port address with composite port") {
struct SillyWrapper : public Composite {
void after_construct() override { provide<MyInt>("port", "c"); }
static void contents(Model& m, int i) { m.component<MyInt>("c", i); }
};
Model model;
model.component<SillyWrapper>("c", 1717);
Assembly assembly(model);
auto& wref = assembly.at<MyInt>(PortAddress("port", "c"));
CHECK(wref.get() == 1717);
}
TEST_CASE("Assembly: get_all") {
Model m;
m.component<MyInt>("c0", 21);
m.component<MyInt>("c1", 11);
m.composite("box");
m.component<MyInt>(Address("box", "c0"), 13);
m.component<MyInt>(Address("box", "c1"), 17);
m.component<MyIntProxy>("c3").connect<Use<IntInterface>>("ptr", Address("box", "c0"));
Assembly a(m);
auto all_myint = a.get_all<MyInt>();
auto all_intinterface = a.get_all<IntInterface>();
CHECK(accumulate(all_myint.pointers().begin(), all_myint.pointers().end(), 0,
[](int acc, MyInt* ptr) { return acc + ptr->i; }) == 62);
CHECK(accumulate(all_intinterface.pointers().begin(), all_intinterface.pointers().end(), 0,
[](int acc, IntInterface* ptr) { return acc + ptr->get(); }) == 88);
}
TEST_CASE("Assembly: get_all in composites") {
Model m;
m.component<MyInt>("c0", 13);
m.composite("a");
m.component<MyInt>(Address("a", "c1"), 15);
m.composite("b");
m.component<MyInt>(Address("b", "c2"), 17);
m.composite("c");
m.component<MyInt>(Address("c", "c3"), 19);
m.component<MyInt>(Address("c", "c4"), 31);
Assembly a(m);
std::vector<Address> expected1{Address("a", "c1"), Address("c", "c3"), Address("c", "c4")}, expected2{"c2"},
expected3{"c3", "c4"};
auto result1 = a.get_all<MyInt>(std::set<Address>{"a", "c"}).names();
auto result2 = a.get_all<MyInt>("b").names();
auto result3 = a.get_all<MyInt>(std::set<Address>{"c"}, "c").names();
CHECK(result1 == expected1);
CHECK(result2 == expected2);
CHECK(result3 == expected3);
}
/*
=============================================================================================================================
~*~ Composite ~*~
===========================================================================================================================*/
TEST_CASE("Instantiation of lone composite") {
struct MyComposite : public Composite {
static void contents(Model& m, int i) {
m.component<MyInt>("compo1", i);
m.component<MyIntProxy>("compo2").connect<Use<IntInterface>>("ptr", "compo1");
}
void after_construct() override { provide<IntInterface>("interface", "compo2"); }
};
MyComposite c;
instantiate_composite(c, 17);
auto value = c.get<IntInterface>("interface")->get();
CHECK(value == 34);
}
/*
=============================================================================================================================
~*~ ComponentReference ~*~
===========================================================================================================================*/
TEST_CASE("ComponentReference test") {
Model model;
auto a = model.component<MyInt>("a", 7);
auto b = model.component<MyIntProxy>("b");
b.connect<Use<IntInterface>>("ptr", a);
auto c = model.composite("c");
auto d = model.component<MyInt>(Address("c", "d"), 8);
auto e = model.component<MyIntProxy>(Address("c", "e")).connect<Use<IntInterface>>("ptr", d);
Assembly assembly(model);
CHECK(assembly.at<IntInterface>("b").get() == 14);
CHECK(assembly.at<IntInterface>(Address("c", "e")).get() == 16);
}
TEST_CASE("ComponentReference set test") {
Model model;
model.component<MyCompo>("compo").set("myPort", 19, 77);
Assembly assembly(model);
CHECK(assembly.at<MyCompo>("compo").i == 19);
CHECK(assembly.at<MyCompo>("compo").j == 77);
}
/*
=============================================================================================================================
~*~ Configure ~*~
===========================================================================================================================*/
TEST_CASE("Configure test") {
Model model;
model.component<MyInt>("Compo1", 4);
model.configure("Compo1", [](MyInt& r) { r.set(17); });
Assembly assembly(model);
CHECK(assembly.at<MyInt>("Compo1").get() == 17);
}
TEST_CASE("Configure with component references") {
Model model;
model.component<MyInt>("Compo1", 4).configure([](MyInt& r) { r.set(17); });
Assembly assembly(model);
CHECK(assembly.at<MyInt>("Compo1").get() == 17);
}
/*
=============================================================================================================================
~*~ Ports ~*~
===========================================================================================================================*/
TEST_CASE("Use/provide test.") {
Model model;
model.component<MyInt>("Compo1", 4);
model.component<MyIntProxy>("Compo2");
Assembly assembly(model);
stringstream ss;
assembly.print(ss);
CHECK(ss.str() == "Compo1: MyInt\nCompo2: MyIntProxy\n");
Use<IntInterface>::_connect(assembly, PortAddress("ptr", "Compo2"), Address("Compo1"));
CHECK(assembly.at<MyIntProxy>("Compo2").get() == 8);
}
TEST_CASE("Use + Assembly: connection test") {
Model model;
model.component<MyInt>("Compo1", 4);
model.component<MyIntProxy>("Compo2");
model.connect<Use<IntInterface>>(PortAddress("ptr", "Compo2"), Address("Compo1"));
Assembly assembly(model);
CHECK(assembly.at<MyIntProxy>("Compo2").get() == 8);
}
TEST_CASE("UseProvide test.") {
struct GetInt {
virtual int getInt() = 0;
};
struct User : public Component {
GetInt* ptr{nullptr};
void setPtr(GetInt* ptrin) { ptr = ptrin; }
User() { port("ptr", &User::setPtr); }
};
struct Two : public GetInt {
int getInt() override { return 2; }
};
struct Provider : public Component {
Two two;
GetInt* providePtr() { return &two; }
Provider() { provide("int", &Provider::providePtr); }
};
Model model;
model.component<User>("user");
model.component<Provider>("provider");
model.connect<UseProvide<GetInt>>(PortAddress("ptr", "user"), PortAddress("int", "provider"));
Assembly assembly(model);
CHECK(assembly.at<User>("user").ptr->getInt() == 2);
}
TEST_CASE("Set test") {
Model model;
model.component<MyCompo>("compo", 2, 3);
model.connect<Set<int, int>>(PortAddress("myPort", "compo"), 5, 7);
Assembly assembly(model);
CHECK(assembly.at<MyCompo>("compo").i == 5);
CHECK(assembly.at<MyCompo>("compo").j == 7);
}
TEST_CASE("Attribute port declaration.") {
struct MyUltraBasicCompo : public Component {
int data{0};
MyUltraBasicCompo() { port("data", &MyUltraBasicCompo::data); }
};
Model model;
model.component<MyUltraBasicCompo>("compo");
model.connect<Set<int>>(PortAddress("data", "compo"), 14);
Assembly assembly(model);
CHECK(assembly.at<MyUltraBasicCompo>("compo").data == 14);
}
/*
=============================================================================================================================
~*~ Drivers ~*~
===========================================================================================================================*/
TEST_CASE("Basic driver test.") {
struct MyWrapper : public Component {
MyInt state;
MyInt* provideState() { return &state; }
MyWrapper() { provide("state", &MyWrapper::provideState); }
};
Model model;
model.component<MyInt>("c1", 119);
model.component<MyWrapper>("c2");
model.driver("driver", [](MyInt* r, MyInt* r2) {
r->set(111);
r2->set(1111);
});
model.connect<DriverConnect<Address, PortAddress>>("driver", "c1", PortAddress("state", "c2"));
Assembly assembly(model);
assembly.call("driver", "go");
CHECK(assembly.at<MyInt>("c1").get() == 111);
CHECK(assembly.at<MyWrapper>("c2").state.get() == 1111);
}
TEST_CASE("Driver connect short syntax") {
Model model;
model.component<MyInt>("c1", 19);
model.component<MyInt>("c2", 321);
model
.driver("driver",
[](MyInt* p1, MyInt* p2) {
p1->set(17);
p2->set(37);
})
.connect("c1", "c2");
Assembly assembly(model);
assembly.call("driver", "go");
CHECK(assembly.at<MyInt>("c1").get() == 17);
CHECK(assembly.at<MyInt>("c2").get() == 37);
}
/*
=============================================================================================================================
~*~ Component sets ~*~
===========================================================================================================================*/
TEST_CASE("Basic InstanceSet test.") {
InstanceSet<MyInt> cs, cs2;
MyInt a(13);
MyInt b(17);
MyInt c(19);
cs2.push_back("a", &a);
cs.combine(cs2);
cs.push_back(Address("b"), &b);
cs.push_back(Address("composite", "c"), &c);
vector<string> observed_names, expected_names{"a", "b", "composite__c"};
vector<int> observed_ints, expected_ints{13, 17, 19};
for (auto&& name : cs.names()) {
observed_names.push_back(name.to_string());
}
for (auto&& ptr : cs.pointers()) {
observed_ints.push_back(ptr->get());
}
CHECK(observed_names == expected_names);
CHECK(observed_ints == expected_ints);
}
| 37.038883 | 125 | 0.563445 | [
"object",
"shape",
"vector",
"model"
] |
75407381a7de82f6b4931134fb4efa66c57e47a0 | 611 | cc | C++ | solutions/p23.cc | akshaypundle/projecteuler | 38c88476cde85b19fc13266d9437b7e78f6d7be4 | [
"MIT"
] | null | null | null | solutions/p23.cc | akshaypundle/projecteuler | 38c88476cde85b19fc13266d9437b7e78f6d7be4 | [
"MIT"
] | null | null | null | solutions/p23.cc | akshaypundle/projecteuler | 38c88476cde85b19fc13266d9437b7e78f6d7be4 | [
"MIT"
] | null | null | null | #include <library.h>
#include <iostream>
using namespace library;
using namespace std;
bool isAbundant(int n) {
int sum =0;
for(auto num:properDivisors(n)) {
sum+=num;
}
if(sum > n) {
return true;
}
return false;
}
int main() {
long tot;
bool abundant[28124];
vector<int> abundantVec;
for(int i=1;i<=28123;i++) {
if(isAbundant(i)) {
abundant[i]=true;
abundantVec.push_back(i);
}
}
for(int i=1;i<=28123;i++) {
for(auto abun : abundantVec) {
if(abun >= i) {tot+=i; break;}
if(abundant[i - abun]) break;
}
}
cout << tot << "\n";
}
| 15.666667 | 36 | 0.564648 | [
"vector"
] |
7545eb18f6153d7e080df1b4fe394cf4f50cccf1 | 9,693 | cpp | C++ | plugin/3dsmax/read/ThreeMFImport.cpp | hamedsabri/M3MF | de81cbe8e3d10f29c71936e08721629ca068d0ce | [
"BSD-2-Clause"
] | null | null | null | plugin/3dsmax/read/ThreeMFImport.cpp | hamedsabri/M3MF | de81cbe8e3d10f29c71936e08721629ca068d0ce | [
"BSD-2-Clause"
] | null | null | null | plugin/3dsmax/read/ThreeMFImport.cpp | hamedsabri/M3MF | de81cbe8e3d10f29c71936e08721629ca068d0ce | [
"BSD-2-Clause"
] | null | null | null | // Copyright (C) 2021 Hamed Sabri
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ThreeMFImport.h"
#include "utility.h"
#include "types.h"
#include <Max.h>
#include <color.h>
#include <stdmat.h>
ClassDesc2* GetThreeMFImportDesc()
{
static M3mf::ThreeMFImportClassDesc threeMfClassDesc;
return &threeMfClassDesc;
}
namespace M3mf {
ThreeMFImport::ThreeMFImport()
{
}
ThreeMFImport::~ThreeMFImport()
{
}
int ThreeMFImport::ExtCount()
{
return 1;
}
const TCHAR* ThreeMFImport::Ext(int n)
{
switch (n) {
case 0:
return _T("3mf");
default:
return nullptr;
}
return nullptr;
}
const TCHAR* ThreeMFImport::LongDesc()
{
return _T("3MF Import for 3DSMax");
}
const TCHAR* ThreeMFImport::ShortDesc()
{
return _T("3MF Import");
}
const TCHAR* ThreeMFImport::AuthorName()
{
return _T("Hamed Sabri");
}
const TCHAR* ThreeMFImport::CopyrightMessage()
{
return _T("Copyright 2021 Hamed Sabri");
}
const TCHAR* ThreeMFImport::OtherMessage1()
{
return _T("");
}
const TCHAR* ThreeMFImport::OtherMessage2()
{
return _T("");
}
unsigned int ThreeMFImport::Version()
{
return 100;
}
void ThreeMFImport::ShowAbout(HWND /*hWnd*/)
{
}
int ThreeMFImport::DoImport(const TCHAR* filename, ImpInterface* importerInt, Interface* ip, BOOL suppressPrompts)
{
_impInterface = importerInt;
std::wstring_view fName(filename);
read(fName);
return TRUE;
}
bool ThreeMFImport::read(std::wstring_view fileName)
{
// read the 3mf file
Lib3MF::PWrapper wrapper = Lib3MF::CWrapper::loadLibrary();
Lib3MF::PModel model = wrapper->CreateModel();
Lib3MF::PReader reader3MF = model->QueryReader("3mf");
try {
reader3MF->ReadFromFile(wstring_to_utf8(fileName.data()));
} catch (Lib3MF::ELib3MFException e) {
return e.getErrorCode();
}
// iterate through builditem(s)
Lib3MF::PBuildItemIterator buildItemIterator = model->GetBuildItems();
while (buildItemIterator->MoveNext()) {
Lib3MF::PBuildItem buildItem = buildItemIterator->GetCurrent();
Lib3MF::PObject object = buildItem->GetObjectResource();
// name
std::string_view objectName;
if (object->GetName().empty()) {
const std::string name { "Object_" + std::to_string(buildItem->GetObjectResourceID()) };
objectName = name;
} else {
objectName = object->GetName();
}
// transform
sLib3MFTransform affineTransform;
if (buildItem->HasObjectTransform()) {
affineTransform = std::move(buildItem->GetObjectTransform());
} else {
affineTransform = std::move(wrapper->GetIdentityTransform());
}
// components
if (object->IsComponentsObject()) {
Lib3MF::PComponentsObject componentsObject = model->GetComponentsObjectByID(object->GetResourceID());
// we care only about model. ignore support, solidsupport, other
if (componentsObject->GetType() == Lib3MF::eObjectType::Model) {
for (uint32_t nIndex = 0; nIndex < componentsObject->GetComponentCount(); nIndex++) {
Lib3MF::PComponent component = componentsObject->GetComponent(nIndex);
sLib3MFTransform compAffineTransform;
if (component->HasTransform()) {
compAffineTransform = std::move(component->GetTransform());
} else {
compAffineTransform = std::move(affineTransform);
}
Lib3MF::PMeshObject meshObject = model->GetMeshObjectByID(component->GetObjectResourceID());
bool status = createMeshObject(wrapper, model, meshObject, compAffineTransform, objectName);
if (!status) {
return false;
}
}
}
}
// mesh
if (object->IsMeshObject()) {
Lib3MF::PMeshObject meshObject = model->GetMeshObjectByID(object->GetResourceID());
bool status = createMeshObject(wrapper, model, meshObject, affineTransform, objectName);
if (!status) {
return false;
}
}
}
return true;
}
bool ThreeMFImport::createMeshObject(const Lib3MF::PWrapper& wrapper, const Lib3MF::PModel& model, const Lib3MF::PMeshObject& mesh, const sLib3MFTransform& transform, std::string_view objectName)
{
bool status { true };
// create a new TriObject
TriObject* object = CreateNewTriObject();
if (!object) {
return false;
}
// get the pointer to the Mesh
Mesh* mMesh = &object->GetMesh();
// set vertex positions for the Mesh
std::vector<Lib3MF::sPosition> vertPos;
mesh->GetVertices(vertPos);
// base material color
M3mf::ColorM materialColor { 0.5f, 0.5f, 0.5f };
status = mMesh->setNumVerts(mesh->GetVertexCount());
if (!status) {
return false;
}
for (auto index = 0; index < vertPos.size(); ++index) {
mMesh->setVert(index, vertPos[index].m_Coordinates[0], vertPos[index].m_Coordinates[1], vertPos[index].m_Coordinates[2]);
}
// set triangle indices for the Mesh
std::vector<Lib3MF::sTriangle> triangleIndices;
mesh->GetTriangleIndices(triangleIndices);
status = mMesh->setNumFaces(mesh->GetTriangleCount());
if (!status) {
return false;
}
// triangle properties
std::vector<Lib3MF::sTriangleProperties> properties;
mesh->GetAllTriangleProperties(properties);
// verify that lib3mf resource ID is present in model
ResourceIDCheck resourceIDCheck(model);
for (uint32_t index = 0; index < mesh->GetTriangleCount(); ++index) {
// create a face and set it's indicies
Face& face = mMesh->faces[index];
face.setMatID(1);
face.setEdgeVisFlags(1, 1, 1);
// face indices
DWORD indicies[3];
indicies[0] = triangleIndices[index].m_Indices[0];
indicies[1] = triangleIndices[index].m_Indices[1];
indicies[2] = triangleIndices[index].m_Indices[2];
face.setVerts(indicies);
// BaseMaterial
if (resourceIDCheck.isRessourceIDValid(properties[index].m_ResourceID) && model->GetPropertyTypeByID(properties[index].m_ResourceID) == Lib3MF::ePropertyType::BaseMaterial) {
Lib3MF::PBaseMaterialGroup baseMaterialGroup = model->GetBaseMaterialGroupByID(properties[index].m_ResourceID);
sLib3MFColor color(baseMaterialGroup->GetDisplayColor(properties[index].m_PropertyIDs[0]));
wrapper->ColorToFloatRGBA(color, materialColor[0], materialColor[1], materialColor[2], materialColor[3]);
}
}
// build bbox and invalidate cache
mMesh->buildBoundingBox();
mMesh->InvalidateGeomCache();
mMesh->InvalidateTopologyCache();
// create a scenegraph node
ImpNode* node = _impInterface->CreateNode();
if (!node) {
delete object;
return false;
}
// set the affine matrix
Matrix3 xformM(M3mf::convert(transform));
node->SetTransform(0, xformM);
// set the reference
node->Reference(object);
// add the node to the scene
_impInterface->AddNodeToScene(node);
// create a new Standard material
StdMat2* standardMat = NewDefaultStdMat();
standardMat->SetName(_T("Standard Material"));
standardMat->SetAmbient(Color(materialColor[0], materialColor[1], materialColor[2]), 0);
standardMat->SetDiffuse(Color(materialColor[0], materialColor[1], materialColor[2]), 0);
standardMat->SetSpecular(Color(materialColor[0], materialColor[1], materialColor[2]), 0);
// assign the material to the node
node->GetINode()->SetMtl(standardMat);
// draw update
_impInterface->RedrawViews();
return status;
}
ResourceIDCheck::ResourceIDCheck(Lib3MF::PModel model)
{
auto pResources = model->GetResources();
if (pResources->Count() != 0) {
while (pResources->MoveNext()) {
auto pResource = pResources->GetCurrent();
_resourceIDs.insert(pResource->GetResourceID());
}
}
}
bool ResourceIDCheck::isRessourceIDValid(uint32_t ID)
{
auto iter = _resourceIDs.find(ID);
if (iter != _resourceIDs.end()) {
return true;
} else {
return false;
}
}
} // namespace M3mf | 30.577287 | 195 | 0.658207 | [
"mesh",
"object",
"vector",
"model",
"transform"
] |
75472f74bc1baf0b8d73918806ab18c7a28bdd0d | 14,676 | cc | C++ | CalibFormats/SiPixelObjects/src/PixelTBMSettings.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CalibFormats/SiPixelObjects/src/PixelTBMSettings.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CalibFormats/SiPixelObjects/src/PixelTBMSettings.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | //
// This class provide a base class for the
// pixel ROC DAC data for the pixel FEC configuration
//
//
//
//
#include "CalibFormats/SiPixelObjects/interface/PixelTBMSettings.h"
#include "CalibFormats/SiPixelObjects/interface/PixelTimeFormatter.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <ios>
#include <cassert>
#include <stdexcept>
using namespace pos;
PixelTBMSettings::PixelTBMSettings(std::vector < std::vector< std::string> > &tableMat):PixelConfigBase("","",""){
std::string mthn = "]\t[PixelTBMSettings::PixelTBMSettings()]\t\t\t " ;
std::vector< std::string > ins = tableMat[0];
std::map<std::string , int > colM;
std::vector<std::string > colNames;
/**
EXTENSION_TABLE_NAME: (VIEW:)
CONFIG_KEY NOT NULL VARCHAR2(80)
KEY_TYPE NOT NULL VARCHAR2(80)
KEY_ALIAS NOT NULL VARCHAR2(80)
VERSION VARCHAR2(40)
KIND_OF_COND NOT NULL VARCHAR2(40)
TBM_NAME VARCHAR2(200)
MODULE_NAME NOT NULL VARCHAR2(200)
HUB_ADDRS NUMBER(38)
TBM_MODE VARCHAR2(200)
ANLG_INBIAS_ADDR NUMBER(38)
ANLG_INBIAS_VAL NOT NULL NUMBER(38)
ANLG_OUTBIAS_ADDR NUMBER(38)
ANLG_OUTBIAS_VAL NOT NULL NUMBER(38)
ANLG_OUTGAIN_ADDR NUMBER(38)
ANLG_OUTGAIN_VAL NOT NULL NUMBER(38)
N.B.: Here we should (MUST) get a single row referring to a particula module for a particula version.
*/
colNames.push_back("CONFIG_KEY" );
colNames.push_back("KEY_TYPE" );
colNames.push_back("KEY_ALIAS" );
colNames.push_back("VERSION" );
colNames.push_back("KIND_OF_COND" );
colNames.push_back("TBM_NAME" );
colNames.push_back("MODULE_NAME" );
colNames.push_back("HUB_ADDRS" );
colNames.push_back("TBM_MODE" );
colNames.push_back("ANLG_INBIAS_ADDR" );
colNames.push_back("ANLG_INBIAS_VAL" );
colNames.push_back("ANLG_OUTBIAS_ADDR");
colNames.push_back("ANLG_OUTBIAS_VAL" );
colNames.push_back("ANLG_OUTGAIN_ADDR");
colNames.push_back("ANLG_OUTGAIN_VAL" );
for(unsigned int c = 0 ; c < ins.size() ; c++){
for(unsigned int n=0; n<colNames.size(); n++){
if(tableMat[0][c] == colNames[n]){
colM[colNames[n]] = c;
break;
}
}
}//end for
for(unsigned int n=0; n<colNames.size(); n++){
if(colM.find(colNames[n]) == colM.end()){
std::cerr << __LINE__ << mthn << "Couldn't find in the database the column with name " << colNames[n] << std::endl;
assert(0);
}
}
if(tableMat.size() >1)
{
//std::cout << __LINE__ << mthn << "Module from DB: " << tableMat[1][colM["MODULE_NAME"]]<< std::endl ;
PixelROCName tmp(tableMat[1][colM["MODULE_NAME"]]);
rocid_ = tmp ;
//std::cout << __LINE__ << mthn << "Built ROCNAME: " << rocid_.rocname()<< std::endl ;
analogInputBias_ = atoi(tableMat[1][colM["ANLG_INBIAS_VAL"]].c_str());
analogOutputBias_ = atoi(tableMat[1][colM["ANLG_OUTBIAS_VAL"]].c_str());
analogOutputGain_ = atoi(tableMat[1][colM["ANLG_OUTGAIN_VAL"]].c_str());
if( tableMat[1][colM["TBM_MODE"]] == "SingleMode"){
singlemode_=true;
}
else{
singlemode_=false;
}
}
}//end contructor
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
PixelTBMSettings::PixelTBMSettings(std::string filename):
PixelConfigBase("","",""){
std::string mthn = "]\t[PixelTBMSettings::PixelTBMSettings()]\t\t\t " ;
if (filename[filename.size()-1]=='t'){
std::ifstream in(filename.c_str());
if (!in.good()){
std::cout << __LINE__ << mthn << "Could not open:"<<filename<<std::endl;
throw std::runtime_error("Failed to open file "+filename);
}
else {
// std::cout << "Opened:"<<filename<<std::endl;
}
std::string tag;
PixelROCName tmp(in);
rocid_=tmp;
unsigned int tmpint;
in >> tag;
//std::cout << "Tag="<<tag<<std::endl;
assert(tag=="AnalogInputBias:");
in >> tmpint;
analogInputBias_=tmpint;
in >> tag;
//std::cout << "Tag="<<tag<<std::endl;
assert(tag=="AnalogOutputBias:");
in >> tmpint;
analogOutputBias_=tmpint;
in >> tag;
//std::cout << "Tag="<<tag<<std::endl;
assert(tag=="AnalogOutputGain:");
in >> tmpint;
analogOutputGain_=tmpint;
in >> tag;
//std::cout << "Tag="<<tag<<std::endl;
assert(tag=="Mode:");
in >> tag;
assert(tag=="SingleMode"||tag=="DualMode");
singlemode_=true;
if (tag=="DualMode") singlemode_=false;
in.close();
}
else{
std::ifstream in(filename.c_str(),std::ios::binary);
if (!in.good()){
std::cout << __LINE__ << mthn << "Could not open:"<<filename<<std::endl;
assert(0);
}
else {
std::cout << __LINE__ << mthn << "Opened:"<<filename<<std::endl;
}
char nchar;
std::string s1;
in.read(&nchar,1);
s1.clear();
//wrote these lines of code without ref. needs to be fixed
for(int i=0;i< nchar; i++){
char c;
in >>c;
s1.push_back(c);
}
PixelROCName tmp(s1);
rocid_=tmp;
in >> analogInputBias_;
in >> analogOutputBias_;
in >> analogOutputGain_;
in >> singlemode_;
in.close();
}
}
void PixelTBMSettings::setTBMGenericValue(std::string what, int value)
{
if( what == "analogInputBias" ) {analogInputBias_ = (unsigned char)value;}
else if( what == "analogOutputBias" ) {analogOutputBias_ = (unsigned char)value;}
else if( what == "analogOutputGain" ) {analogOutputGain_ = (unsigned char)value;}
else if( what == "Mode" ) {singlemode_ = (bool)value; }
else
{
std::cout << __LINE__ << "]\t[PixelTBMSettings::setTBMGenericValue()]\t\tFATAL: invalid key/value pair: " << what << "/" << value << std::endl ;
assert(0);
}
}
void PixelTBMSettings::writeBinary(std::string filename) const {
std::ofstream out(filename.c_str(),std::ios::binary);
out << (char)rocid_.rocname().size();
out.write(rocid_.rocname().c_str(),rocid_.rocname().size());
out <<analogInputBias_;
out <<analogOutputBias_;
out <<analogOutputGain_;
out << singlemode_;
}
void PixelTBMSettings::writeASCII(std::string dir) const {
PixelModuleName module(rocid_.rocname());
if (dir!="") dir+="/";
std::string filename=dir+"TBM_module_"+module.modulename()+".dat";
std::ofstream out(filename.c_str());
out << rocid_.rocname() << std::endl;
out << "AnalogInputBias: "<<(int)analogInputBias_<<std::endl;
out << "AnalogOutputBias: "<<(int)analogOutputBias_<<std::endl;
out << "AnalogOutputGain: "<<(int)analogOutputGain_<<std::endl;
out << "Mode: ";
if (singlemode_) {
out << "SingleMode" << std::endl;
}
else{
out << "DualMode" << std::endl;
}
}
void PixelTBMSettings::generateConfiguration(PixelFECConfigInterface* pixelFEC,
PixelNameTranslation* trans,
bool physics, bool doResets) const{
PixelHdwAddress theROC=*(trans->getHdwAddress(rocid_));
int mfec=theROC.mfec();
int mfecchannel=theROC.mfecchannel();
int tbmchannel=14;
int tbmchannelB=15;
int hubaddress=theROC.hubaddress();
if (doResets) {
pixelFEC->injectrsttbm(mfec, 1);
pixelFEC->injectrstroc(mfec,1);
}
pixelFEC->enablecallatency(mfec,0);
pixelFEC->disableexttrigger(mfec,0);
pixelFEC->injecttrigger(mfec,0);
pixelFEC->callatencycount(mfec,79);
//pixelFEC->synccontrolregister(mfec);
//Reset TBM and reset ROC
if (doResets) pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 2, 0x14, 0);
//setting speed to 40MHz
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 0, 1, 0);
// setting the mode, we should always stay in the CAL mode
// since the EventNumberClear Mode does not work correctly
//if (physics) { // comment out, stau always in the CAL mode, d.k. 27/09/09
//pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 1, 0x80, 0);
//} else {
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 1, 0xc0, 0);
//}
//Enable token and analog output
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 4, 0x0, 0);
//Analog input bias
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 5,
analogInputBias_, 0);
//Analog output bias
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 6,
analogOutputBias_, 0);
//Analog output gain
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannel, hubaddress, 4, 7,
analogOutputGain_, 0);
//setting speed to 40MHz
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannelB, hubaddress, 4, 0, 1, 0);
//pre-calibration, stay always in this mode
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannelB, hubaddress, 4, 1, 0xc0, 0);
//Reset TBM and reset ROC
if (doResets) pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannelB, hubaddress, 4, 2, 0x14, 0);
//Enable token and analog output
if (singlemode_){
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannelB, hubaddress, 4, 4, 0x3, 0);
}
else{
pixelFEC->tbmcmd(mfec, mfecchannel, tbmchannelB, hubaddress, 4, 4, 0x0, 0);
}
}
std::ostream& pos::operator<<(std::ostream& s, const PixelTBMSettings& tbm){
s << "Module :"<<tbm.getROCName().rocname() <<std::endl;
s << "analogInputBias :"<<tbm.getAnalogInputBias()<<std::endl;
s << "analogOutputBias:"<<tbm.getAnalogOutputBias()<<std::endl;
s << "analogOutputGain:"<<tbm.getAnalogOutputGain()<<std::endl;
if (tbm.getMode()){
s << "mode :Singlemode"<<std::endl;
}
else{
s << "mode :Dualmode"<<std::endl;
}
return s;
}
//=============================================================================================
void PixelTBMSettings::writeXMLHeader(pos::PixelConfigKey key,
int version,
std::string path,
std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "]\t[PixelTBMSettings::writeXMLHeader()]\t\t\t " ;
std::stringstream fullPath ;
fullPath << path << "/Pixel_TbmParameters_" << PixelTimeFormatter::getmSecTime() << ".xml" ;
std::cout << __LINE__ << mthn << "Writing to: " << fullPath.str() << std::endl ;
outstream->open(fullPath.str().c_str()) ;
*outstream << "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" << std::endl ;
*outstream << "<ROOT xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" << std::endl ;
*outstream << " <HEADER>" << std::endl ;
*outstream << " <TYPE>" << std::endl ;
*outstream << " <EXTENSION_TABLE_NAME>PIXEL_TBM_PARAMETERS</EXTENSION_TABLE_NAME>" << std::endl ;
*outstream << " <NAME>Pixel TBM Parameters</NAME>" << std::endl ;
*outstream << " </TYPE>" << std::endl ;
*outstream << " <RUN>" << std::endl ;
*outstream << " <RUN_TYPE>Pixel TBM Parameters</RUN_TYPE>" << std::endl ;
*outstream << " <RUN_NUMBER>1</RUN_NUMBER>" << std::endl ;
*outstream << " <RUN_BEGIN_TIMESTAMP>" << pos::PixelTimeFormatter::getTime() << "</RUN_BEGIN_TIMESTAMP>" << std::endl ;
*outstream << " <LOCATION>CERN P5</LOCATION>" << std::endl ;
*outstream << " </RUN>" << std::endl ;
*outstream << " </HEADER>" << std::endl ;
*outstream << "" << std::endl ;
*outstream << " <DATA_SET>" << std::endl ;
*outstream << " <PART>" << std::endl ;
*outstream << " <NAME_LABEL>CMS-PIXEL-ROOT</NAME_LABEL>" << std::endl ;
*outstream << " <KIND_OF_PART>Detector ROOT</KIND_OF_PART>" << std::endl ;
*outstream << " </PART>" << std::endl ;
*outstream << " <VERSION>" << version << "</VERSION>" << std::endl ;
*outstream << " <COMMENT_DESCRIPTION>" << getComment() << "</COMMENT_DESCRIPTION>" << std::endl ;
*outstream << " <CREATED_BY_USER>" << getAuthor() << "</CREATED_BY_USER>" << std::endl ;
*outstream << " " << std::endl ;
}
//=============================================================================================
void PixelTBMSettings::writeXML(std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "]\t[PixelTBMSettings::writeXML()]\t\t\t " ;
PixelModuleName module(rocid_.rocname());
*outstream << " <DATA>" << std::endl ;
*outstream << " <MODULE_NAME>" << rocid_.rocname() << "</MODULE_NAME>" << std::endl ;
*outstream << " <ANLG_INBIAS_VAL>" <<(int)analogInputBias_ << "</ANLG_INBIAS_VAL>" << std::endl ;
*outstream << " <ANLG_OUTBIAS_VAL>" <<(int)analogOutputBias_ << "</ANLG_OUTBIAS_VAL>" << std::endl ;
*outstream << " <ANLG_OUTGAIN_VAL>" <<(int)analogOutputGain_ << "</ANLG_OUTGAIN_VAL>" << std::endl ;
if (singlemode_) {
*outstream << " <TBM_MODE>SingleMode</TBM_MODE>" << std::endl ;
}
else{
*outstream << " <TBM_MODE>DualMode</TBM_MODE>" << std::endl ;
}
*outstream << " </DATA>" << std::endl ;
}
//=============================================================================================
void PixelTBMSettings::writeXMLTrailer(std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "]\t[PixelTBMSettings::writeXMLTrailer()]\t\t\t " ;
*outstream << " " << std::endl ;
*outstream << " </DATA_SET>" << std::endl ;
*outstream << "</ROOT> " << std::endl ;
outstream->close() ;
}
| 35.621359 | 148 | 0.553421 | [
"vector"
] |
7549de82ba1ee516bbe57636673708398c2a1a65 | 1,387 | cpp | C++ | src/third_party/wiredtiger/test/unittest/tests/test_fnv.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/unittest/tests/test_fnv.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/unittest/tests/test_fnv.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /*-
* Copyright (c) 2014-present MongoDB, Inc.
* Copyright (c) 2008-2014 WiredTiger, Inc.
* All rights reserved.
*
* See the file LICENSE for redistribution information.
*/
#include <catch2/catch.hpp>
#include "wt_internal.h"
// Due credit: the cases that hash to zero came from
// http://www.isthe.com/chongo/tech/comp/fnv/#zero-hash
TEST_CASE("Hashing: hash_fnv64", "[fnv]")
{
const uint64_t fnv1a_64_init = 0xcbf29ce484222325;
REQUIRE(__wt_hash_fnv64(nullptr, 0) == fnv1a_64_init);
REQUIRE(__wt_hash_fnv64("", 0) == fnv1a_64_init);
REQUIRE(__wt_hash_fnv64("a", 1) == 0xaf63dc4c8601ec8c);
REQUIRE(__wt_hash_fnv64("asdf", 4) == 0x90285684421f9857);
const std::vector<uint8_t> hash_to_zero = {0xd5, 0x6b, 0xb9, 0x53, 0x42, 0x87, 0x08, 0x36};
REQUIRE(__wt_hash_fnv64(&hash_to_zero[0], hash_to_zero.size()) == 0x00);
const std::string ascii_hash_to_zero = "!0IC=VloaY";
REQUIRE(__wt_hash_fnv64(&ascii_hash_to_zero[0], ascii_hash_to_zero.length()) == 0x00);
const std::string alphanum_hash_to_zero = "77kepQFQ8Kl";
REQUIRE(__wt_hash_fnv64(&alphanum_hash_to_zero[0], alphanum_hash_to_zero.length()) == 0x00);
std::string really_long = "this is a really long string ";
for (int i = 0; i < 5; i++)
really_long += really_long;
REQUIRE(__wt_hash_fnv64(&really_long[0], really_long.length()) == 0x774ab448918be805);
}
| 36.5 | 96 | 0.704398 | [
"vector"
] |
755172f9d061c369d5ee0f49273a7fbb9f931798 | 10,168 | cpp | C++ | ui/startsavingtoharddisk.cpp | joke-lab/project | ef5984d9ec0ad61b76b85f21c9ffc58fb99c94c9 | [
"Apache-2.0"
] | null | null | null | ui/startsavingtoharddisk.cpp | joke-lab/project | ef5984d9ec0ad61b76b85f21c9ffc58fb99c94c9 | [
"Apache-2.0"
] | null | null | null | ui/startsavingtoharddisk.cpp | joke-lab/project | ef5984d9ec0ad61b76b85f21c9ffc58fb99c94c9 | [
"Apache-2.0"
] | null | null | null | #include "startsavingtoharddisk.h"
startsavingtoharddisk::startsavingtoharddisk(uchar *&save_buffer,float *&angle_buff,QReadWriteLock *share_lock,QObject*parent):
QObject(parent),buf_read(save_buffer),angle_buf(angle_buff),lock_read(share_lock)
{
}
startsavingtoharddisk::~startsavingtoharddisk()
{
}
//将数据存入硬盘的函数
void startsavingtoharddisk::harddisk_save_thread()
{
/*
while(global::start_running_thread)
{
}*/
qDebug() << "startsavingtoharddisk函数被调用";
}
//接收来自paintonline线程的经纬度,用于数据文件头的存储
void startsavingtoharddisk::gps_toheadSave_Slot(int *data)
{
memcpy(gps_headData,data,2*4);
qDebug() << "经度和纬度" << gps_headData[0] << gps_headData[1];
}
//循环体中要用的内容
void startsavingtoharddisk::harddisk_save_thread2(double *ins_Data)
{
//qDebug() << "startsavingtoharddisk线程开始上锁";
lock_read->lockForRead();
//qDebug() << "startsavingtoharddisk线程上锁成功";
memcpy(insData,ins_Data,16*10*N*sizeof (double)); //将paintonline传输的数据拷贝下来
//qDebug() << "startsavingtoharddisk线程的循环体被调用";
if(for_first_run)
{
for_first_run = false;
emit start_saving_message(); //这里的内容,每次点击“开始处理”(点击停止处理时不会)运行一次
//第一次点击“开始处理”后,运行一次与共享内存有关的设置 `
//从初始文件中获取存储路径
//此路径一定存在,在写入ini文件时已进行确认
//放在第一次运行的判断外,为了防止“暂停处理”时改变存储路径和文件夹
QSettings *ini = new QSettings(QCoreApplication::applicationDirPath()+"/setting.ini",QSettings::IniFormat);
int min = ini->value("/radar_information/minimum").toInt();
int max = ini->value("/radar_information/maximum").toInt();
float sample_x = ini->value("/radar_information/samplestep").toFloat();
sample_num = int((max - min) / sample_x); //通过观测范围和采样间距计算出采样点数
QString path_ini = ini->value("/initialPath/savepath").toString(); //获取存储路径
QString site_ini = ini->value("/site_information/name").toString(); //获取站点名称
frame_num = ini->value("/collection_mode/framenumber").toInt(); //获取每隔数据文件存储的数据总帧数
QDateTime time = QDateTime::currentDateTime(); //获取当前系统的时间
QString year = time.toString("yyyy") + "年"; //获取当前的年份
QString dir_name = year + site_ini; //文件夹名称为年份加站点名称
//qDebug() << "文件夹名称为年份加时间" << dir_name << "num = " << sample_num;
QDir data_save_dir;
if(!data_save_dir.exists(path_ini))
{
qDebug() << "运行设置中的存储路径不存在!";
path_ini = QCoreApplication::applicationDirPath();
}
data_save_dir.setCurrent(path_ini); //设置现在的目录为存储在ini文件中的目录
//qDebug() << "文件夹所在的目录" << path_ini;
if(!data_save_dir.exists(dir_name)) //判断在此路径下是否存在指定文件夹
{
qDebug() << "文件不存在,新建一个文件";
data_save_dir.mkdir(dir_name); //不存在时,生成文件夹
}
QString year_dir_path = data_save_dir.filePath(dir_name); //获取“年份+地点”文件夹的路径
data_save_dir.setCurrent(year_dir_path); //将“年份+地点”文件夹的路径设为当前路径
QString month = time.toString("M") + "月"; //文件夹名称为系统时间的月份
if(!data_save_dir.exists(month)) //判断此路径下是否存在现在月份的文件夹
{
data_save_dir.mkdir(month); //不存在时,生成子文件夹
}
data_save_dir.setCurrent(month); //设置当前月份对应的文件夹路径为当前路径
filename = time.toString("yyyy_MM_dd_hh_mm_ss")+".RRAW";
file.setFileName(filename);
if(!file.exists()) //判断此文件现在是否存在,不存在时新建
{
qDebug() << "文件已经存在";
file.open(QIODevice::ReadWrite);
file.close();
}
streamIn.setDevice(&file);
//qDebug() << "saving调用一次数据头函数11";
filehead_Slot(); //数据文件写入文件头数据
saveAngle_old = angle_buf[0] - 0.1;
//qDebug() << "startsavingtoharddisk线程中初始化的角度值为" << saveAngle_old << angle_buf[0]-10;
}
if(file.open(QIODevice::WriteOnly|QIODevice::Append))
{
//QTime time;
//time.start();
//qDebug() << "startsavingtoharddisk线程中" << saveAngle_old << angle_buf[0];
if(angle_buf[0] >= saveAngle_old && angle_buf[0] - saveAngle_old < 0.2)
{
//qDebug() << "startsavingtoharddisk线程中开始存入数据1";
for(int i=0;i<10*N;i++)
{
//qDebug() << "startsavingtoharddis存入1";
file.write(QByteArray::fromRawData((char *)insData,16*sizeof (double)));
//qDebug() << "startsavingtoharddis存入2";
//file.write(QByteArray::fromRawData((char *)markerBit,1));
streamIn << markerBit;
//qDebug() << "startsavingtoharddis存入3";
file.write(QByteArray::fromRawData((char *)buf_read,sample_num*2));
//qDebug() << "startsavingtoharddis存入4";
}
}
else if(angle_buf[0] < saveAngle_old && 360 - saveAngle_old + angle_buf[0] < 0.2)
{
//qDebug() << "startsavingtoharddisk线程中开始存入数据2";
for(int i=0;i<10*N;i++)
{
//qDebug() << "startsavingtoharddis存入1";
file.write(QByteArray::fromRawData((char *)insData,16*sizeof (double)));
//qDebug() << "startsavingtoharddis存入2";
//file.write(QByteArray::fromRawData((char *)markerBit,1));
streamIn << markerBit;
//qDebug() << "startsavingtoharddis存入3";
file.write(QByteArray::fromRawData((char *)buf_read,sample_num*2));
//qDebug() << "startsavingtoharddis存入4";
}
}
/*else
{
qDebug() << "startsavingtoharddisk线程中开始存入数据3";
//char bitTemp[int((angle_buf[0] - saveAngle_old)*10)];
//for(int m=0;m<int(angle_buf[0] - saveAngle_old)*10-1;m++)
//bitTemp[m] = 0;
if(angle_buf[0] > saveAngle_old)
{
int n = int((angle_buf[0] - saveAngle_old)*10-1)*int(2*sample_num + 1 + 16*sizeof (double));
qDebug() << "存储硬盘中N1的值为" << angle_buf[0] << saveAngle_old << n;
for(int k=0;k<n;k++)
streamIn << 0x00;
}
else
{
int n = int((360 - saveAngle_old + angle_buf[0])*10-1)*int(2*sample_num + 1 + 16*sizeof (double));
qDebug() << "存储硬盘中N2的值为" << angle_buf[0] << saveAngle_old << n;
for(int k=0;k<n;k++)
streamIn << 0x00;
}
//streamIn << bitTemp;
//file.write(QByteArray::fromRawData((char *)bitTemp,int((angle_buf[0] - saveAngle_old)*10)));
for(int i=0;i<10*N;i++)
{
file.write(QByteArray::fromRawData((char *)insData,16*sizeof (double)));
streamIn << markerBit;
file.write(QByteArray::fromRawData((char *)buf_read,sample_num*2));
}
}*/
lock_read->unlock();
saveAngle_old = angle_buf[10*N-1];
count_for_frame+=10*N; //用以判断什么时候存满一组数据
//qDebug() << "startsavingtoharddisk线程中将数据存入硬盘完成";
file.close();
}
if(count_for_frame == 3600*frame_num) //当存满一组数据的时候
{
count_for_frame = 0;
QDateTime time_now = QDateTime::currentDateTime(); //获取当前系统的时间
filename = time_now.toString("yyyy_MM_dd_hh_mm_ss")+".RRAW";
file.setFileName(filename);
if(!file.exists()) //判断此文件现在是否存在,不存在时新建
{
//qDebug() << "文件已经存在";
file.open(QIODevice::ReadWrite);
file.close();
}
//qDebug() << "saving调用一次数据头函数12";
filehead_Slot(); //数据文件写入文件头数据
}
//qDebug() << "startsavingtoharddisk线程的循环体调用完毕";
}
//数据文件写入文件头数据
void startsavingtoharddisk::filehead_Slot()
{
qDebug() << "saving调用一次数据头函数2";
//在此处向文件中输入前100个字节的数据
if(file.open(QIODevice::WriteOnly|QIODevice::Append))
{
char head[100] = {0};
//软件版本号、保存时间、站点名称共31个字节
QString site_num = "MRDV1.1"; //临时
//软件版本号:7个字节
streamIn << site_num; //存入软件版本号
//保存时间:14个字节
streamIn << QDateTime::currentDateTime().toString("yyyyMMddhhmmss"); //存入当前的保存时间
QSettings *setting = new QSettings(QCoreApplication::applicationDirPath()+"/setting.ini",QSettings::IniFormat);
QString sitename = setting->value("/site_information/name").toString(); //读出站点名称
//站点名称:10个字节
if(sitename.length() <= 10)
{
streamIn << sitename;
for(int i=0;i < 10 - sitename.length();i++)
streamIn << 0x00;
}
else if(sitename.length() > 10)
{
for(int i=0;i<10;i++)
streamIn << 0x00;
QMessageBox::warning(nullptr,"站点名称存储错误","站点名称长度过长,超过10个字符,无法存入文件中!",nullptr,QMessageBox::Ok);
}
//经度、纬度:4个字节
streamIn << gps_headData[0] << gps_headData[1];
//Nt,int类型
/////////////
file.write(head,4);
//每根线上的采样点数:4个字节
streamIn << sample_num;
//角度分辨率,float类型,一般为CD CC CC 3D
streamIn << 0xCD << 0xCC << 0xCC << 0x3D;
//起始距离、结束距离,int类型
streamIn << min << max;
//采样频率,float类型
file.write(head,4);
//修正角度:4个字节
streamIn << setting->value("/calculation_parameter/radar_correction_angle").toInt();
//一个标志位
//////////////
streamIn << 0x01;
//计算区域的四个边界值:8个字节
qint16 value;
value = setting->value("/area/angle1").toInt();
streamIn << value;
value = setting->value("/area/angle2").toInt();
streamIn << value;
value = setting->value("/area/radio1").toInt();
streamIn << value;
value = setting->value("/area/radio2").toInt();
streamIn << value;
int frame = setting->value("/collection_mode/framenumber").toInt(); //读出每个数据文件存储的帧数
streamIn << frame;
float n = setting->value("/calculation_parameter/sampling_interval_time").toFloat(); //读出时间抽样间隔,即周期
streamIn << float(1/n); //计算出转速,存入数据头中
for(int i=0;i < 24;i++)
streamIn << 0x00;
}
file.close();
}
| 40.50996 | 128 | 0.562746 | [
"3d"
] |
7552055f92d28ac36053c866989562914674d455 | 1,907 | cpp | C++ | ARPREC/arprec-2.2.13/src/sub.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | ARPREC/arprec-2.2.13/src/sub.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | ARPREC/arprec-2.2.13/src/sub.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | /*
* src/mpreal.cc
*
* This work was supported by the Director, Office of Science, Division
* of Mathematical, Information, and Computational Sciences of the
* U.S. Department of Energy under contract number DE-AC03-76SF00098.
*
* Copyright (c) 2002
*
*/
#include <arprec/mp_real.h>
#include "small_inline.h"
using std::cerr;
using std::endl;
void mp_real::mpsub(const mp_real &a, const mp_real &b, mp_real& c,
int prec_words)
{
// This routine subtracts MP numbers A and B to yield the MP difference C,
// by negating B and adding. Debug output starts with debug_level = 9.
//
// Max SP space for C: MPNW + 5 cells.
int i, BreakLoop;
double b1;
if (error_no != 0) {
if (error_no == 99) mpabrt();
zero(c);
return;
}
if (debug_level >= 9) cerr << " MPSUB" << endl;
// Check if A = B. This is necessary because A and B might be same array,
// in which case negating B below won't work.
// check if A == B points to the same object
if(&a == &b) {
zero(c);
if(debug_level >= 9) print_mpreal("MPSUB O ", c);
return;
}
// check if their exponent and mantissas are the same
if (a[1] == b[1]) {
BreakLoop = 0;
for (i = 2; i < int(std::abs(a[1])) + FST_M; ++i) {
if (a[i] != b[i]) {
BreakLoop = 1;
break;
}
}
if (!BreakLoop) {
zero(c);
if(debug_level >= 9) print_mpreal("MPSUB O ", c);
return;
}
}
// Save the sign of B, and then negate B.
b1 = b[1];
double *temp; // use temp to keep const modifier
temp = b.mpr;
temp[1] = -b1;
// Perform addition and restore the sign of B.
mpadd(a, b, c, prec_words);
// When restoring the sign of b, we must make sure that
// b and c were not the same object. if they were,
// then b was overwriten, and c already contains the correct
// result.
if(&b != &c)
temp[1] = b1;
return;
}
| 23.54321 | 76 | 0.598322 | [
"object"
] |
7575052516a3f798ba4baa7da195d46861f41fdc | 9,081 | cpp | C++ | external/vqi_frogs/Module/config.cpp | kellerkompanie/kellerkompanie-mods | f15704710f77ba6c018c486d95cac4f7749d33b8 | [
"MIT"
] | 6 | 2018-05-05T22:28:57.000Z | 2019-07-06T08:46:51.000Z | external/vqi_frogs/Module/config.cpp | Schwaggot/kellerkompanie-mods | 7a389e49e3675866dbde1b317a44892926976e9d | [
"MIT"
] | 107 | 2018-04-11T19:42:27.000Z | 2019-09-13T19:05:31.000Z | external/vqi_frogs/Module/config.cpp | kellerkompanie/kellerkompanie-mods | f15704710f77ba6c018c486d95cac4f7749d33b8 | [
"MIT"
] | 3 | 2018-10-03T11:54:46.000Z | 2019-02-28T13:30:16.000Z | // : : : FROGS Module System : : :
//
#define private 0
#define protected 1
#define public 2
class CfgPatches {
class VQI_FROGS { // multi allowed?
units[] = {"VQI_ModuleFROGS"};
requiredVersion = 1.0;
requiredAddons[] = {"A3_Modules_F"};
//directory = "SPOOKWARCOM\SPOOKWARCOM";
};
};
class CfgFunctions
{
class VQI
{
class FROGSystem
{
class FROGSmod { file = "\vqi_frogs\module\fn_module.sqf"; };
class FROGSinit { file = "\vqi_frogs\init.sqf"; };
};
};
};
class CfgFactionClasses {
class NO_CATEGORY;
class VQI_FROGS: NO_CATEGORY
{
displayName = "=VQI= F. R. O. G. S";
};
};
class CfgVehicles {
class Logic; // internal game class reference
class Module_F : Logic {
class ArgumentsBaseUnits {
class Units; };
class ModuleDescription {
class AnyBrain; };
};
///////////////////////////////////
// Combat Diver
class VQI_ModuleFROGS : Module_F {
icon = "vqi_frogs\module\iconFROGS.paa";
scope = public;
author = "R.Von Quest aka 'Goblin'";
category = "VQI_FROGS";
displayName = "Combat Diver";
function = "VQI_fnc_FROGSmod";
functionPriority = 1;
isGlobal = 1;
isTriggerActivated = 0;
class Arguments: ArgumentsBaseUnits
{
//class Units: Units {};
class vqi_module_frogs_debughints { //Debug, Info, Hints
displayName = "Debug/Hints/Info";
description = "Recommend: OFF";
typeName = NUMBER;
class Values
{
class 0OFF {name = "OFF"; value = 0; default = 0;}; // ListBox Items
class 1ON {name = "ON"; value = 1; };
};
};
class vqi_module_frogs_mapobject { //
displayName = "Menu Object";
description = "Enter the Name of the OBJECT (user placed) that the Main Menu will appear. Submarine Transport, Intel, etc. This can be ANY Object";
typeName = OBJECT;
defaultValue = "VQI_FROGS_LAPTOP";
};
class vqi_module_frogs_boarding { //
displayName = "Boarding Option";
description = "Allow Player Boarding Options (teleport) from OBJECT or MUST Travel out to PLACED SURFACED Submarine BEFORE boarding";
typeName = NUMBER;
class Values
{
class 0DOPDB {name = "Board from Surfaced Sub"; value = 0; }; // ListBox Items
class 1DOPDB {name = "Teleport from MENU OBJECT"; value = 1; default = 1;};
class 2DOPDB {name = "Auto-Teleport at Game Start"; value = 2; };
};
};
/*
class vqi_module_frogs_loc { //
displayName = "Lockout Chamber";
description = "Select to use Lockout Chamber during transition, or Teleport directly into water over placed Submarine. NOTE: LOC is clunky and only a placeholder. LOC 3D Model is coming SOON!";
typeName = NUMBER;
class Values
{
class 0LOC {name = "OFF - Teleport into water ONLY"; value = 0; }; // ListBox Items
class 1LOC {name = "ON - Teleport onto LOC"; value = 1; default = 1;};
};
};
*/
class vqi_module_frogs_db1watch { //
displayName = "DiveMate (watch)";
description = "Adds 'Watch' Key option, (3rd option) See KeyBinding README for more info. Display Time of DiveMate on screen when pressed.";
typeName = NUMBER;
class Values
{
class 0DB1 {name = "OFF - Not needed, Using other"; value = 0; }; // ListBox Items
class 1DB1 {name = "Watch Key - Temp, Quick On/Off"; value = 1; };
class 2DB1 {name = "Watch Key - Temp, 10sec"; value = 2; };
class 3DB1 {name = "Watch Key - Temp, 20sec"; value = 3; default = 3;};
class 4DB1 {name = "Watch Key - Temp, 30sec"; value = 4; };
class 5DB1 {name = "Watch Key - Temp, 60sec"; value = 5; };
class 6DB1 {name = "Watch Key - Temp, 90sec"; value = 6; };
};
};
class vqi_module_frogs_sub_traveltime { //
displayName = "Sub Travel Time";
description = "Simulates the Travel Time it takes the Sub to reach its destination (Advances Game Time)";
typeName = NUMBER;
class Values
{
class 0STT {name = "None, Teleport Instantly"; value = 0; }; // ListBox Items
class 1STT {name = "Advance Game Time 1 Hour, Exact"; value = 1; };
class 2STT {name = "Advance Game Time 1-3 Hours, Random"; value = 2; default = 2; };
class 3STT {name = "Advance Game Time 2-6 Hours, Random"; value = 3; };
class 4STT {name = "Advance Game Time 3-9 Hours, Random"; value = 4; };
class 5STT {name = "Advance Game Time 4-12 Hours, Random"; value = 5; };
class 6STT {name = "Advance Game Time 3 Hours, Exact"; value = 6; };
class 7STT {name = "Advance Game Time 6 Hours, Exact"; value = 7; };
class 8STT {name = "Advance Game Time 12 Hours, Exact"; value = 8; };
};
};
class vqi_module_frogs_ao_sub { //
displayName = "AO: Submarines";
description = "How many SUB/SDVs for the Map. Enter 0, Positive, or a Negative Number. Positive is EXACTLY that many SUBs. A Negative number is RANDOM upto that Number.";
typeName = NUMBER;
defaultValue = "-5";
};
class vqi_module_frogs_ao_sub_intel { //
displayName = "Sub Intel";
description = "Select the INTEL SOURCE for how/what Enemy Submarine info is known. See DOCs for more Info.";
typeName = NUMBER;
class Values
{
//class 0SUBINTEL {name = "Off / None"; value = 0; default = 0; };
class 1SUBINTEL {name = "SIGINT - NSA Radio Intercept/Decrypt"; value = 1; };
class 2SUBINTEL {name = "NATO Fleet & Naval Surface Ships"; value = 2; };
class 3SUBINTEL {name = "Submarines and/or SONAR Bouy Array"; value = 3; };
class 4SUBINTEL {name = "Satellite - NROL-34: Odin"; value = 4; default = 4; };
class 5SUBINTEL {name = "Satellite - NROL-55: Intruder"; value = 5; };
class 6SUBINTEL {name = "Satellite - NROL-79: N.O.S.S."; value = 6; };
};
};
class vqi_module_frogs_ao_nav { //
displayName = "AO: Naval";
description = "How many NAVAL AOs for the Map. Enter 0, Positive, or a Negative Number. Positive is EXACTLY that many AOs. A Negative number is RANDOM upto that Number.";
typeName = NUMBER;
defaultValue = "-15";
};
class vqi_module_frogs_ao_nav_color { //
displayName = "Naval AO Color";
description = "Set the COLOR of the Map Intel Icon for this AO";
typeName = NUMBER;
class Values
{
class 0AOMAPN {name = "Black"; value = 0; };
class 1AOMAPN {name = "Grey"; value = 1; };
class 2AOMAPN {name = "Red"; value = 2; };
class 3AOMAPN {name = "Brown"; value = 3; };
class 4AOMAPN {name = "Orange"; value = 4; };
class 5AOMAPN {name = "Yellow"; value = 5; };
class 6AOMAPN {name = "Khaki"; value = 6; };
class 7AOMAPN {name = "Green"; value = 7; };
class 8AOMAPN {name = "Blue"; value = 8; };
class 9AOMAPN {name = "Pink"; value = 9; };
class 10AOMAPN {name = "White"; value = 10; };
class 11AOMAPN {name = "WEST"; value = 11; };
class 12AOMAPN {name = "EAST"; value = 12; };
class 13AOMAPN {name = "GUER"; value = 13; };
class 14AOMAPN {name = "CIV"; value = 14; };
class 15AOMAPN {name = "UNKNOWN"; value = 15; };
class 16AOMAPN {name = "Dark Blue"; value = 16; default = 16; };
class 17AOMAPN {name = "Dark Red"; value = 17; };
class 18AOMAPN {name = "Dark Green"; value = 18; };
class 19AOMAPN {name = "Civilian"; value = 19; };
};
};
class vqi_module_frogs_ao_nav_intel { //
displayName = "Naval Intel %";
description = "DYNAMIC AOs are RANDOMIZED probability of Calculated-Intel; Realistic and Organic. STATIC AOs are 100% GUARANTEED to be there, 100% of the time.";
typeName = NUMBER;
class Values
{
class 0NAVINTEL {name = "STATIC - 100% Guaranteed, Absolute!"; value = 0; default = 0; };
class 1NAVINTEL {name = "DYNAMIC - Unknown, Probability ONLY"; value = 1; }; // ListBox Items
};
};
class vqi_module_frogs_ao_nav_side { //
displayName = "Naval Side =";
description = "Spawns Random Naval Ops & Units";
typeName = NUMBER;
class Values
{
class 1NAVSIDE {name = "RED / OPF / CSAT"; value = 1; default = 1; }; // ListBox Items
class 4NAVSIDE {name = "RED / OPF / RHS Russians"; value = 4; };
class 2NAVSIDE {name = "GRN / IND / A.A.F"; value = 2; };
class 3NAVSIDE {name = "BLU / BLU / NATO"; value = 3; };
};
};
class vqi_module_frogs_tempmarker { //
displayName = "Submarine Marker";
description = "Select Permanent or Temporary (20 min) displayed Marker";
typeName = NUMBER;
class Values
{
class 1ONPERM {name = "Permanent - Marker stays ON"; value = 1; default = 1;}; // ListBox Items
class 0OFTEMP {name = "Temporary - Marker ON for 20 Minutes Only"; value = 0; };
};
};
};
// Module description. Must inherit from base class, otherwise pre-defined entities won't be available
class ModuleDescription {
description = "Place Module to turn ON System. Select options as desired. Will spawn and de-spawn enemy, items, effects, etc. around player.";
//sync[] = {};
};
};
};
| 34.660305 | 197 | 0.617773 | [
"object",
"model",
"3d"
] |
757b11870233e16ee5a65234bd2f93bc2197e8dd | 719 | cpp | C++ | Atcoder/abc228/c.cpp | hyturing/Competitve-Programming | 571da19ae5d17fdcf2b9a9956eaf5a6c5f7d27e8 | [
"MIT"
] | 5 | 2021-01-25T17:08:45.000Z | 2021-09-11T17:33:39.000Z | Atcoder/abc228/c.cpp | hyturing/Competitve-Programming | 571da19ae5d17fdcf2b9a9956eaf5a6c5f7d27e8 | [
"MIT"
] | null | null | null | Atcoder/abc228/c.cpp | hyturing/Competitve-Programming | 571da19ae5d17fdcf2b9a9956eaf5a6c5f7d27e8 | [
"MIT"
] | 1 | 2021-03-22T16:53:30.000Z | 2021-03-22T16:53:30.000Z | /* hyturing - Hemant Kumar Yadav */
#include "bits/stdc++.h"
using namespace std;
#define endl "\n"
#define ll long long
const ll MOD = 1e9+7;
void solve(){
int n, k;
cin >> n >> k;
vector<int> p(n);
for(int i = 0; i < n; i++){
int a, b, c;
cin >> a >> b >> c;
p[i] = a+b+c;
}
vector<int> r=p;
sort(r.begin(), r.end());
for(auto x: p){
int me = x+300;
auto it = upper_bound(r.begin(), r.end(), me);
int rank = (int)(r.end()-it)+1;
cout << (rank <= k ? "Yes" : "No") << endl;
}
return;
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int tc = 1;
// cin >> tc;
for(int i = 1; i <= tc; i++){
// cout << "Case #" << i << ": ";
solve();
}
return 0;
}
| 14.979167 | 48 | 0.504868 | [
"vector"
] |
757d22a218692deeba670ce487cf65db34ebe082 | 5,043 | hpp | C++ | include/utils4cpp/filesystem/UPath.hpp | shaoguangwu/utils4cpp | 6cc2093220e7be293761432cde88dff275c8f678 | [
"BSD-3-Clause"
] | 1 | 2019-10-17T01:34:56.000Z | 2019-10-17T01:34:56.000Z | include/utils4cpp/filesystem/UPath.hpp | shaoguangwu/utils4cpp | 6cc2093220e7be293761432cde88dff275c8f678 | [
"BSD-3-Clause"
] | null | null | null | include/utils4cpp/filesystem/UPath.hpp | shaoguangwu/utils4cpp | 6cc2093220e7be293761432cde88dff275c8f678 | [
"BSD-3-Clause"
] | 3 | 2019-10-17T01:33:37.000Z | 2019-12-02T02:13:45.000Z | /************************************************************************************
**
** BSD 3-Clause License
**
** Copyright (c) 2019, shaoguang. All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
** 1. Redistributions of source code must retain the above copyright notice, this
** list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and/or other materials provided with the distribution.
**
** 3. Neither the name of the copyright holder nor the names of its
** contributors may be used to endorse or promote products derived from
** this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
************************************************************************************/
#ifndef UTILS4CPP_FILESYSTEM_UPATH_HPP
#define UTILS4CPP_FILESYSTEM_UPATH_HPP
#include <utility>
#include "utils4cpp/filesystem/UFileSystemGlobal.hpp"
#include "utils4cpp/filesystem/UPathToString.inl"
namespace utils4cpp {
namespace filesystem {
/**
\class UPath
\brief Objects of type path represent paths on a filesystem.
\since v0.0
Only syntactic aspects of paths are handled: the pathname may represent a non-existing
path or even one that is not allowed to exist on the current file system or OS.
*/
template<class StringT>
class UPath
{
public:
/** Typedef for StringT::value_type. Provided for STL compatibility. */
using valu_type = typename StringT::value_type;
/** Typedef for StringT. Provided for STL compatibility. */
using string_type = StringT;
/** Typedef for StringT::size_type. Provided for STL compatibility. */
using size_type = typename StringT::size_type;
public:
/**
Constructs an empty path.
*/
UPath() noexcept(std::is_nothrow_default_constructible_v<StringT>) = default;
/**
Destroys the path object.
*/
~UPath() = default;
UPath(const StringT& str) : m_data(str)
{}
UPath(StringT&& str) noexcept : m_data(std::move(str))
{}
UPath(const UPath& other) : m_data(other.m_data)
{}
UPath(UPath&& other) noexcept : m_data(std::move(other.m_data))
{}
UPath& operator=(const StringT& str)
{
m_data = str;
return *this;
}
UPath& operator=(StringT& str) noexcept
{
m_data = std::move(str);
return *this;
}
UPath& operator=(const UPath& other)
{
if (&other != this) {
m_data = other.m_data;
}
return *this;
}
#if UTILS4CPP_HAS_CPP17
UPath& operator=(UPath&& other) noexcept
{
if (&other != this) {
m_data = std::move(other.m_data);
}
return *this;
}
#else
UPath& operator=(UPath&& other)
{
if (&other != this) {
m_data = std::move(other.m_data);
}
return *this;
}
#endif
#if UTILS4CPP_HAS_STDFILESYSTEM
UPath(const std::filesystem::path& path) : m_data(impl::pathToString<StringT>(path))
{}
UPath& operator=(const std::filesystem::path& path)
{
m_data = impl::pathToString<StringT>(path);
return *this;
}
#endif
StringT& data() noexcept
{
return m_data;
}
const StringT& data() const noexcept
{
return m_data;
}
const StringT& constData() const noexcept
{
return m_data;
}
StringT toInputString() const
{
return m_data;
}
StringT moveToInputString() noexcept
{
return std::move(m_data);
}
bool empty() const noexcept
{
return m_data.empty();
}
void clear() noexcept
{
m_data.clear();
}
#if UTILS4CPP_HAS_CPP17
void swap(UPath& other) noexcept
{
m_data.swap(other.m_data);
}
#else
void swap(UPath& other)
{
m_data.swap(other.m_data);
}
#endif
private:
StringT m_data;
};
} // namespace filesystem
} // namespace utils4cpp
#endif // UTILS4CPP_FILESYSTEM_UPATH_HPP | 26.68254 | 90 | 0.635931 | [
"object"
] |
757fb859ce14348da1cb0726fd372e217df27b75 | 1,759 | hpp | C++ | src/sys/opengl/buffer.hpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | 8 | 2021-01-18T12:06:21.000Z | 2022-02-13T17:12:56.000Z | src/sys/opengl/buffer.hpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | null | null | null | src/sys/opengl/buffer.hpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | null | null | null | // Minote - sys/opengl/buffer.hpp
// Type-safe wrapper for OpenGL buffer object types
#pragma once
#include "glad/glad.h"
#include "base/concept.hpp"
#include "base/array.hpp"
#include "base/util.hpp"
#include "sys/opengl/base.hpp"
namespace minote {
// Generic buffer object. Use one of the template specializations below
template<copy_constructible T, GLenum _target>
struct BufferBase : GLObject {
// Element type that is being stored by the buffer
using Type = T;
// The GLenum value of the buffer's binding target
static constexpr GLenum Target = _target;
// Whether the buffer data can be uploaded more than once
bool dynamic = false;
// Whether there has been at least one data upload
bool uploaded = false;
// Create the buffer object; the storage is empty by default. Set dynamic
// to true if you want to upload data more than once (streaming buffer.)
void create(char const* name, bool dynamic);
// Clean up the buffer, freeing memory on the GPU.
void destroy();
// Upload new data to the GPU buffer, replacing previous data. The buffer
// is resized to fit the new data, and the previous storage is orphaned.
void upload(span<Type const> data);
// Bind the buffer to the Target binding point.
void bind() const;
};
// Buffer object for storing per-vertex data (VBO)
template<copy_constructible T>
using VertexBuffer = BufferBase<T, GL_ARRAY_BUFFER>;
// Valid underlying type for an element buffer
template<typename T>
concept ElementType =
std::is_same_v<T, GLubyte> ||
std::is_same_v<T, GLushort> ||
std::is_same_v<T, GLuint>;
// Buffer object for storing vertex indices (EBO)
template<ElementType T = GLuint>
using ElementBuffer = BufferBase<T, GL_ELEMENT_ARRAY_BUFFER>;
}
#include "sys/opengl/buffer.tpp"
| 27.484375 | 74 | 0.744741 | [
"object"
] |
7588a9a60c9bb5b8edea75052833185ff7e1b795 | 21,722 | cpp | C++ | main.cpp | Paulina-Majda/ksiazkaAdresowa | 97de05ff1380daf71448ad4f9fb496b5cdab360b | [
"Unlicense"
] | null | null | null | main.cpp | Paulina-Majda/ksiazkaAdresowa | 97de05ff1380daf71448ad4f9fb496b5cdab360b | [
"Unlicense"
] | null | null | null | main.cpp | Paulina-Majda/ksiazkaAdresowa | 97de05ff1380daf71448ad4f9fb496b5cdab360b | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <fstream>
#include <cstdio>
#include <algorithm>
using namespace std;
int iteratorUzytkownikow;
int iteratorAdresatow;
int idZalogowanegoUzytkownika = -1;
string nazwaPlikuAdresowego = "Adresaci.txt";
string nazwaPlikuUzytkownikow = "Uzytkownicy.txt";
string nazwaPlikuTymczasowego = "Tymczasowy.txt";
struct Uzytkownik{
int id;
string nazwa, haslo;
};
struct Kontakt {
int id;
int idUzytkownika;
string imie;
string nazwisko;
string email;
string numer;
string adres;
};
void dopiszKontaktDoPliku(Kontakt kontakt) {
fstream fileWriter(nazwaPlikuAdresowego, ios::in | ios::out | ios::app);
if (fileWriter.is_open()) {
fileWriter << to_string(kontakt.id) << '|';
fileWriter << to_string(kontakt.idUzytkownika) << '|';
fileWriter << kontakt.imie << '|';
fileWriter << kontakt.nazwisko << '|';
fileWriter << kontakt.email << '|';
fileWriter << kontakt.numer << '|';
fileWriter << kontakt.adres << '|' << endl;
fileWriter.close();
} else cout << "Pliku nie udalo sie odczytac.";
}
void wyswietlKontakty(vector<Kontakt> kontakty) {
cout << endl << "LISTA WSZYSTKICH KONTAKTOW" << endl << endl;
for (int i = 0; i < kontakty.size(); i++) {
cout << endl << "Id: " << kontakty[i].id;
cout << endl << "Imie: " << kontakty[i].imie;
cout << endl << "Nazwisko: " << kontakty[i].nazwisko;
cout << endl << "Email: " << kontakty[i].email;
cout << endl << "Numer telefonu: " << kontakty[i].numer;
cout << endl << "Adres zamieszkania: " << kontakty[i].adres << endl;
}
cout << endl;
}
void stworzKontakt(vector<Kontakt> &kontakty) {
Kontakt kontakt;
cout << endl << "ZAPISZ NOWY KONTAKT" << endl << endl;
cout << "Wpisz imie: ";
cin >> kontakt.imie;
cout << "Wpisz nazwisko: ";
cin >> kontakt.nazwisko;
cout << "Wpisz adres email: ";
cin >> kontakt.email;
cout << "Wpisz numer telefonu: ";
cin.sync();
getline(cin, kontakt.numer);
cout << "Wpisz adres zamieszkania: ";
cin.sync();
getline(cin, kontakt.adres);
kontakt.id = iteratorAdresatow;
kontakt.idUzytkownika = idZalogowanegoUzytkownika;
iteratorAdresatow++;
kontakty.push_back(kontakt);
dopiszKontaktDoPliku(kontakt);
system("cls");
}
void znajdzImie(vector<Kontakt> kontakty) {
string imie;
cout << endl << "WYSZUKIWANIE KONTAKTOW PO IMIENIU" << endl << endl;
cout << "Wpisz imie kontaktu, ktorego szukasz: ";
cin >> imie;
system("cls");
cout << endl << "KONTAKTY ZAWIERAJACE PODANE IMIE: " << imie << endl << endl;
for (int i = 0; i < kontakty.size(); i++) {
if (kontakty[i].imie == imie) {
cout << endl << "Id: " << kontakty[i].id;
cout << endl << "Imie: " << kontakty[i].imie;
cout << endl << "Nazwisko: " << kontakty[i].nazwisko;
cout << endl << "Email: " << kontakty[i].email;
cout << endl << "Numer telefonu: " << kontakty[i].numer;
cout << endl << "Adres zamieszkania: " << kontakty[i].adres << endl;
}
}
cout << endl << endl;
}
void znajdzNazwisko(vector<Kontakt> kontakty) {
string nazwisko;
cout << endl << "WYSZUKIWANIE KONTAKTOW PO NAZWISKU" << endl << endl;
cout << "Wpisz nazwisko kontaktu, ktorego szukasz: ";
cin >> nazwisko;
system("cls");
cout << endl << "KONTAKTY ZAWIEAJACE PODANE NAZWISKO: " << nazwisko << endl << endl;
for (int i = 0; i < kontakty.size(); i++) {
if (kontakty[i].nazwisko == nazwisko) {
cout << endl << "Id: " << kontakty[i].id;
cout << endl << "Imie: " << kontakty[i].imie;
cout << endl << "Nazwisko: " << kontakty[i].nazwisko;
cout << endl << "Email: " << kontakty[i].email;
cout << endl << "Numer telefonu: " << kontakty[i].numer;
cout << endl << "Adres zamieszkania: " << kontakty[i].adres << endl;
}
}
cout << endl << endl;
}
void zapiszKontaktyDoPliku(vector<Kontakt> kontakty){
fstream fileWriter(nazwaPlikuAdresowego, ios::in | ios::out | ios::trunc);
if (fileWriter.is_open()){
for (int i = 0; i < kontakty.size(); i++){
fileWriter << kontakty[i].id << "|";
fileWriter << kontakty[i].idUzytkownika << "|";
fileWriter << kontakty[i].imie << "|";
fileWriter << kontakty[i].nazwisko << "|";
fileWriter << kontakty[i].email << "|";
fileWriter << kontakty[i].numer << "|";
fileWriter << kontakty[i].adres << "|" << endl;
}
fileWriter.close();
} else cout << "Pliku nie udalo sie odczytac.";
}
void usunKontaktWPliku(int idKontaktu){
fstream fileWriterAdresaci(nazwaPlikuAdresowego, ios::in | ios::out | ios::app);
fstream fileWriterTymczasowy(nazwaPlikuTymczasowego, ios::in | ios::out | ios::trunc);
string bufor;
int n;
int licznik = 1;
while(getline(fileWriterAdresaci, bufor, '|')){
bufor.erase(remove(bufor.begin(), bufor.end(), '\n'), bufor.end());
switch(licznik){
case 1:
if (to_string(idKontaktu) == bufor){
n = 6;
while (n > 0){
getline(fileWriterAdresaci, bufor, '|');
n--;
}
licznik = 0;
} else {
if (bufor != "\0"){
fileWriterTymczasowy << bufor << "|";
}
}
break;
case 2:
fileWriterTymczasowy << bufor << "|";
break;
case 3:
fileWriterTymczasowy << bufor << "|";
break;
case 4:
fileWriterTymczasowy << bufor << "|";
break;
case 5:
fileWriterTymczasowy << bufor << "|";
break;
case 6:
fileWriterTymczasowy << bufor << "|";
break;
case 7:
fileWriterTymczasowy << bufor << "|" << endl;
licznik = 0;
break;
}
licznik++;
}
fileWriterTymczasowy.close();
fileWriterAdresaci.close();
char charPlikAdresowy[nazwaPlikuAdresowego.size() + 1];
strcpy(charPlikAdresowy, nazwaPlikuAdresowego.c_str());
char charPlikTymczasowy[nazwaPlikuTymczasowego.size() + 1];
strcpy(charPlikTymczasowy, nazwaPlikuTymczasowego.c_str());
int rezultatUsuwania = remove(charPlikAdresowy);
if (rezultatUsuwania == 0){
rename(charPlikTymczasowy, charPlikAdresowy);
}
}
void usunKontakt(vector<Kontakt> &kontakty){
int indeksDoUsuniecia = 0;
char potwierdzenie;
int idKontaktu;
cout << endl << "USUWANIE KONTAKTU O PODANYM ID" << endl << endl;
cout << "Podaj id kontaktu, ktory chcesz usunac: ";
cin >> idKontaktu;
for (int i = 0; i < kontakty.size(); i++){
if (kontakty[i].id == idKontaktu){
indeksDoUsuniecia = i;
}
}
cout << "Potwierdz chec usuniecia tego kontaktu poprzez wcisniecie litery t: ";
cin >> potwierdzenie;
if(potwierdzenie == 't'){
kontakty.erase(kontakty.begin() + indeksDoUsuniecia);
usunKontaktWPliku(idKontaktu);
}
system("cls");
}
vector<Kontakt> zaladujKontakty() {
fstream fileWriter(nazwaPlikuAdresowego, ios::in | ios::out | ios::app);
string bufor;
int najwiekszeId = 0;
Kontakt kontakt;
vector<Kontakt> kontakty;
int licznik = 1;
while(getline(fileWriter, bufor, '|')){
bufor.erase(remove(bufor.begin(), bufor.end(), '\n'), bufor.end());
switch(licznik){
case 1:
kontakt.id = atoi(bufor.c_str());
if (kontakt.id > najwiekszeId){
najwiekszeId = kontakt.id;
}
break;
case 2:
if (atoi(bufor.c_str()) != idZalogowanegoUzytkownika){
int n = 5;
while (n > 0){
getline(fileWriter, bufor, '|');
n--;
}
licznik = 0;
} else {
kontakt.idUzytkownika = atoi(bufor.c_str());
break;
}
case 3:
kontakt.imie = bufor;
break;
case 4:
kontakt.nazwisko = bufor;
break;
case 5:
kontakt.email = bufor;
break;
case 6:
kontakt.numer = bufor;
break;
case 7:
kontakt.adres = bufor;
kontakty.push_back(kontakt);
licznik = 0;
break;
}
licznik++;
}
iteratorAdresatow = najwiekszeId + 1;
return kontakty;
}
void edytujKontaktWPliku(int idDoEdycji, char opcja, string noweDane, vector<Kontakt> &kontakty){
fstream fileWriterAdresaci(nazwaPlikuAdresowego, ios::in | ios::out | ios::app);
fstream fileWriterTymczasowy(nazwaPlikuTymczasowego, ios::in | ios::out | ios::trunc);
string bufor;
Kontakt kontakt;
int n;
int licznik = 1;
while(getline(fileWriterAdresaci, bufor, '|')){
bufor.erase(remove(bufor.begin(), bufor.end(), '\n'), bufor.end());
switch(licznik){
case 1:
if (to_string(idDoEdycji) == bufor){
kontakt.id = atoi(bufor.c_str());
getline(fileWriterAdresaci, bufor, '|');
kontakt.idUzytkownika = atoi(bufor.c_str());
getline(fileWriterAdresaci, bufor, '|');
kontakt.imie = bufor;
getline(fileWriterAdresaci, bufor, '|');
kontakt.nazwisko = bufor;
getline(fileWriterAdresaci, bufor, '|');
kontakt.email = bufor;
getline(fileWriterAdresaci, bufor, '|');
kontakt.numer = bufor;
getline(fileWriterAdresaci, bufor, '|');
kontakt.adres = bufor;
switch (opcja){
case '1':
kontakt.imie = noweDane;
break;
case '2':
kontakt.nazwisko = noweDane;
break;
case '3':
kontakt.email = noweDane;
break;
case '4':
kontakt.numer = noweDane;
break;
case '5':
kontakt.adres = noweDane;
break;
}
if (fileWriterTymczasowy.is_open()) {
fileWriterTymczasowy << to_string(kontakt.id) << '|';
fileWriterTymczasowy << to_string(kontakt.idUzytkownika) << '|';
fileWriterTymczasowy << kontakt.imie << '|';
fileWriterTymczasowy << kontakt.nazwisko << '|';
fileWriterTymczasowy << kontakt.email << '|';
fileWriterTymczasowy << kontakt.numer << '|';
fileWriterTymczasowy << kontakt.adres << '|' << endl;
} else cout << "Pliku nie udalo sie odczytac.";
licznik = 0;
} else {
if (bufor != "\0"){
fileWriterTymczasowy << bufor << "|";
}
}
break;
case 2:
fileWriterTymczasowy << bufor << "|";
break;
case 3:
fileWriterTymczasowy << bufor << "|";
break;
case 4:
fileWriterTymczasowy << bufor << "|";
break;
case 5:
fileWriterTymczasowy << bufor << "|";
break;
case 6:
fileWriterTymczasowy << bufor << "|";
break;
case 7:
fileWriterTymczasowy << bufor << "|" << endl;
licznik = 0;
break;
}
licznik++;
}
fileWriterTymczasowy.close();
fileWriterAdresaci.close();
char charPlikAdresowy[nazwaPlikuAdresowego.size() + 1];
strcpy(charPlikAdresowy, nazwaPlikuAdresowego.c_str());
char charPlikTymczasowy[nazwaPlikuTymczasowego.size() + 1];
strcpy(charPlikTymczasowy, nazwaPlikuTymczasowego.c_str());
int rezultatUsuwania = remove(charPlikAdresowy);
if (rezultatUsuwania == 0){
rename(charPlikTymczasowy, charPlikAdresowy);
kontakty = zaladujKontakty();
}
}
void menuEdycjiKontaktu(vector<Kontakt> &kontakty){
int idDoEdycji;
char opcja;
string noweDane;
cout << endl << "EDYCJA KONTAKTU CZ 1" << endl << endl;
cout << endl << "1. Wybierz id uzytkownika do edycji" << endl;
cout << endl << "Twoj wybor: ";
cin >> idDoEdycji;
cout << endl << "EDYCJA KONTAKTU CZ 2" << endl << endl;
cout << "1. Zmien imie" << endl;
cout << "2. Zmien nazwisko" << endl;
cout << "3. Zmien adres email" << endl;
cout << "4. Zmien telefon" << endl;
cout << "5. Zmien adres" << endl;
cout << "6. Powrot do menu" << endl;
cout << endl << "Twoj wybor: ";
cin >> opcja;
cout << endl << "EDYCJA KONTAKTU CZ 3" << endl << endl;
cout << "1. Wprowadz ";
switch (opcja){
case '1':
cout << "nowe imie\nTwoj wybor: ";
cin >> noweDane;
break;
case '2':
cout << "nowe nazwisko\nTwoj wybor: ";
cin >> noweDane;
break;
case '3':
cout << "nowy adres email\nTwoj wybor: ";
cin >> noweDane;
break;
case '4':
cout << "nowy telefon\nTwoj wybor: ";
cin.sync();
getline(cin, noweDane);
break;
case '5':
cout << "nowy adres\nTwoj wybor: ";
cin.sync();
getline(cin, noweDane);
break;
}
edytujKontaktWPliku(idDoEdycji, opcja, noweDane, kontakty);
}
void zmianaHasla(){
string stareHaslo, noweHaslo;
cout << endl << "ZMIANA HASLA" << endl << endl;
cout << endl << "Wprowadz nowe haslo: ";
cin >> noweHaslo;
fstream fileWriterUzytkownicy(nazwaPlikuUzytkownikow, ios::in | ios::out | ios::app);
fstream fileWriterTymczasowy(nazwaPlikuTymczasowego, ios::in | ios::out | ios::trunc);
string bufor;
int n;
int licznik = 1;
while(getline(fileWriterUzytkownicy, bufor, '|')){
bufor.erase(remove(bufor.begin(), bufor.end(), '\n'), bufor.end());
switch(licznik){
case 1:
if (to_string(idZalogowanegoUzytkownika) == bufor){
fileWriterTymczasowy << to_string(idZalogowanegoUzytkownika) << '|';
getline(fileWriterUzytkownicy, bufor, '|');
fileWriterTymczasowy << bufor << '|';
getline(fileWriterUzytkownicy, bufor, '|');
fileWriterTymczasowy << noweHaslo << '|' << endl;
licznik = 0;
} else {
if (bufor != "\0"){
fileWriterTymczasowy << bufor << "|";
}
}
break;
case 2:
fileWriterTymczasowy << bufor << "|";
break;
case 3:
fileWriterTymczasowy << bufor << "|" << endl;
licznik = 0;
break;
}
licznik++;
}
fileWriterTymczasowy.close();
fileWriterUzytkownicy.close();
char charPlikUzytkownicy[nazwaPlikuUzytkownikow.size() + 1];
strcpy(charPlikUzytkownicy, nazwaPlikuUzytkownikow.c_str());
char charPlikTymczasowy[nazwaPlikuTymczasowego.size() + 1];
strcpy(charPlikTymczasowy, nazwaPlikuTymczasowego.c_str());
int rezultatUsuwania = remove(charPlikUzytkownicy);
if (rezultatUsuwania == 0){
rename(charPlikTymczasowy, charPlikUzytkownicy);
}
cout << "Haslo zmienione pomyslnie!";
}
void menuKsiazkiAdresowej() {
vector<Kontakt> kontakty = zaladujKontakty();
char wybor;
bool petla = true;
while (petla) {
cout << endl << "KSIAZKA ADRESOWA" << endl << endl;
cout << "1. Dodaj adresata" << endl;
cout << "2. Wyszukaj po imieniu" << endl;
cout << "3. Wyszukaj po nazwisku" << endl;
cout << "4. Wyswietl wszystkich adresatow" << endl;
cout << "5. Usun adresata" << endl;
cout << "6. Edytuj adresata" << endl;
cout << "7. Zmien haslo" << endl;
cout << "8. Wyloguj" << endl;
cout << endl << "Twoj wybor: ";
cin >> wybor;
system("cls");
switch(wybor) {
case '1':
stworzKontakt(kontakty);
break;
case '2':
znajdzImie(kontakty);
break;
case '3':
znajdzNazwisko(kontakty);
break;
case '4':
wyswietlKontakty(kontakty);
break;
case '5':
usunKontakt(kontakty);
break;
case '6':
menuEdycjiKontaktu(kontakty);
break;
case '7':
zmianaHasla();
break;
case '8':
idZalogowanegoUzytkownika = -1;
petla = false;
break;
}
}
}
vector<Uzytkownik> zaladujUzytkownikow(){
fstream fileWriter(nazwaPlikuUzytkownikow, ios::in | ios::out | ios::app);
string bufor;
int najwiekszeId = 0;
Uzytkownik uzytkownik;
vector<Uzytkownik> uzytkownicy;
int licznik = 1;
while(getline(fileWriter, bufor, '|')){
bufor.erase(remove(bufor.begin(), bufor.end(), '\n'), bufor.end());
switch(licznik){
case 1:
uzytkownik.id = atoi(bufor.c_str());
if (uzytkownik.id > najwiekszeId){
najwiekszeId = uzytkownik.id;
}
break;
case 2:
uzytkownik.nazwa = bufor;
break;
case 3:
uzytkownik.haslo = bufor;
licznik = 0;
uzytkownicy.push_back(uzytkownik);
break;
}
licznik++;
}
iteratorUzytkownikow = najwiekszeId + 1;
return uzytkownicy;
}
bool rejestracja(vector<Uzytkownik> &uzytkownicy){
string nazwa, haslo;
bool poprawnoscLoginu = false;
system("cls");
while (poprawnoscLoginu != true){
cout << "Podaj nazwe uzytkownika: ";
cin >> nazwa;
poprawnoscLoginu = true;
for (int i = 0; i < uzytkownicy.size(); i++){
if(uzytkownicy[i].nazwa == nazwa){
cout << "Podana nazwa jest juz w uzyciu\n";
poprawnoscLoginu = false;
}
}
}
cout << "Podaj haslo: ";
cin >> haslo;
Uzytkownik nowy;
nowy.id = iteratorUzytkownikow;
nowy.nazwa = nazwa;
nowy.haslo = haslo;
fstream fileWriter(nazwaPlikuUzytkownikow, ios::in | ios::out | ios::app);
if (fileWriter.is_open()) {
fileWriter << to_string(nowy.id) << '|';
fileWriter << nowy.nazwa << '|';
fileWriter << nowy.haslo << '|' << endl;
fileWriter.close();
uzytkownicy.push_back(nowy);
iteratorUzytkownikow++;
} else {
cout << "Pliku [" + nazwaPlikuUzytkownikow + "] nie udalo sie odczytac.";
return false;
}
cout<<"Konto uzytkownika zostalo pomyslnie utworzone"<<endl;
return true;
}
bool logowanie(vector<Uzytkownik> &uzytkownicy){
string nazwa, haslo;
system("cls");
int proba = 0;
while(proba < 3){
cout << "Podaj nazwe uzytkownika: ";
cin >> nazwa;
cout << "Podaj haslo: ";
cin >> haslo;
for (int i = 0; i < uzytkownicy.size(); i++){
if ((uzytkownicy[i].nazwa == nazwa) && (uzytkownicy[i].haslo == haslo)){
idZalogowanegoUzytkownika = uzytkownicy[i].id;
cout << "Logowanie zakonczone pomyslnie\n";
return true;
}
}
cout << "Niepoprawne dane logowania. Sprobuj ponownie\n";
proba++;
}
cout << "Wpisales bledne haslo 3 razy!. Operacja zakonczona niepowodzeniem";
return false;
}
int main()
{
vector<Uzytkownik> uzytkownicy = zaladujUzytkownikow();
bool powodzenieRejestracji;
bool powodzenieLogowania = false;
char wybor;
while (1) {
cout << endl << "MENU REJESTRACJI/LOGOWANIA" << endl << endl;
cout << "1. Rejestracja"<<endl;
cout << "2. Logowanie"<<endl;
cout << "9. Zakoncz program"<<endl;
cout << endl << "Twoj wybor: ";
cin >> wybor;
system("cls");
switch(wybor) {
case '1':
powodzenieRejestracji = rejestracja(uzytkownicy);
break;
case '2':
powodzenieLogowania = logowanie(uzytkownicy);
if ((powodzenieLogowania == true) && (idZalogowanegoUzytkownika >= 0)){
menuKsiazkiAdresowej();
}
break;
case '9':
exit(0);
break;
}
}
}
| 30.855114 | 98 | 0.51266 | [
"vector"
] |
758bf96233642b478e0f5e31e57c337931afacd5 | 71,785 | cpp | C++ | src/modules/hip/hip_geometry_transforms.cpp | Reza-Najafi/rpp | 26b21762d4fbc4971b03f939fe00ae8bcf49fef9 | [
"MIT"
] | null | null | null | src/modules/hip/hip_geometry_transforms.cpp | Reza-Najafi/rpp | 26b21762d4fbc4971b03f939fe00ae8bcf49fef9 | [
"MIT"
] | null | null | null | src/modules/hip/hip_geometry_transforms.cpp | Reza-Najafi/rpp | 26b21762d4fbc4971b03f939fe00ae8bcf49fef9 | [
"MIT"
] | null | null | null | #include "hip_declarations.hpp"
/************* Fish eye ******************/
RppStatus
fisheye_hip(Rpp8u* srcPtr, RppiSize srcSize,
Rpp8u* dstPtr,
RppiChnFormat chnFormat, unsigned int channel,
rpp::Handle& handle)
{
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "fish_eye.cpp", "fisheye_planar", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "fish_eye.cpp", "fisheye_packed", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
// else
// {std::cerr << "Internal error: Unknown Channel format";}
// err = clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &srcPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &dstPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.height);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.width);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &channel);
// size_t gDim3[3];
// gDim3[0] = srcSize.width;
// gDim3[1] = srcSize.height;
// gDim3[2] = channel;
// cl_kernel_implementer (handle, gDim3, NULL/*Local*/, theProgram, theKernel);
return RPP_SUCCESS;
}
RppStatus
fisheye_hip_batch ( Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle,
RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{max_width, max_height, handle.GetBatchSize()};
handle.AddKernel("", "", "fish_eye.cpp", "fisheye_batch", vld, vgd, "")(srcPtr,
dstPtr,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.roiPoints.x,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth,
handle.GetInitHandle()->mem.mgpu.roiPoints.y,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
plnpkdind);
return RPP_SUCCESS;
}
/************* LensCorrection ******************/
RppStatus
lens_correction_hip( Rpp8u* srcPtr,RppiSize srcSize, Rpp8u* dstPtr,
float strength,float zoom,
RppiChnFormat chnFormat, unsigned int channel,
rpp::Handle& handle)
{
unsigned short counter=0;
if (strength == 0)
strength = 0.000001;
float halfWidth = (float)srcSize.width / 2.0;
float halfHeight = (float)srcSize.height / 2.0;
float correctionRadius = (float)sqrt((float)srcSize.width * srcSize.width + srcSize.height * srcSize.height) / (float)strength;
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "lens_correction.cpp", "lenscorrection_pln", vld, vgd, "")(srcPtr,
dstPtr,
strength,
zoom,
halfWidth,
halfHeight,
correctionRadius,
srcSize.height,
srcSize.width,
channel
);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "lens_correction.cpp", "lenscorrection_pkd", vld, vgd, "")(srcPtr,
dstPtr,
strength,
zoom,
halfWidth,
halfHeight,
correctionRadius,
srcSize.height,
srcSize.width,
channel
);
}
else
{
std::cerr << "Internal error: Unknown Channel format";
}
// //---- Args Setter
// err = clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &srcPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &dstPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &strength);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &zoom);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &halfWidth);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &halfHeight);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &correctionRadius);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.height);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.width);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &channel);
// //----
// size_t gDim3[3];
// gDim3[0] = srcSize.width;
// gDim3[1] = srcSize.height;
// gDim3[2] = channel;
// cl_kernel_implementer (handle, gDim3, NULL/*Local*/, theProgram, theKernel);
return RPP_SUCCESS;
}
RppStatus
lens_correction_hip_batch ( Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle,
RppiChnFormat chnFormat, unsigned int channel)
{
unsigned int maxHeight, maxWidth;
maxHeight = handle.GetInitHandle()->mem.mgpu.csrcSize.height[0];
maxWidth = handle.GetInitHandle()->mem.mgpu.csrcSize.width[0];
for(int i = 0 ; i < handle.GetBatchSize() ; i++)
{
if(maxHeight < handle.GetInitHandle()->mem.mgpu.csrcSize.height[i])
maxHeight = handle.GetInitHandle()->mem.mgpu.csrcSize.height[i];
if(maxWidth < handle.GetInitHandle()->mem.mgpu.csrcSize.width[i])
maxWidth = handle.GetInitHandle()->mem.mgpu.csrcSize.width[i];
}
Rpp8u* srcPtr1;
hipMalloc(&srcPtr1, sizeof(unsigned char) * maxHeight * maxWidth * channel);
Rpp8u* dstPtr1;
hipMalloc(&dstPtr1, sizeof(unsigned char) * maxHeight * maxWidth * channel);
size_t gDim3[3];
size_t batchIndex = 0;
for(int i = 0 ; i < handle.GetBatchSize() ; i++)
{
gDim3[0] = handle.GetInitHandle()->mem.mgpu.csrcSize.width[i];
gDim3[1] = handle.GetInitHandle()->mem.mgpu.csrcSize.height[i];
gDim3[2] = channel;
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{gDim3[0], gDim3[1], gDim3[2]};
if (handle.GetInitHandle()->mem.mcpu.floatArr[0].floatmem[i] == 0)
handle.GetInitHandle()->mem.mcpu.floatArr[0].floatmem[i] = 0.000001;
float halfWidth = (float)handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] / 2.0;
float halfHeight = (float)handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] / 2.0;
float correctionRadius = (float)sqrt((float)handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] + handle.GetInitHandle()->mem.mgpu.csrcSize.height[i]
* handle.GetInitHandle()->mem.mgpu.csrcSize.height[i]) / (float)handle.GetInitHandle()->mem.mcpu.floatArr[0].floatmem[i];
hipMemcpy(srcPtr1, srcPtr+batchIndex , sizeof(unsigned char) * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * channel, hipMemcpyDeviceToDevice);
if (chnFormat == RPPI_CHN_PLANAR)
{
handle.AddKernel("", "", "lens_correction.cpp", "lenscorrection_pln", vld, vgd, "")(srcPtr1,
dstPtr1,
handle.GetInitHandle()->mem.mcpu.floatArr[0].floatmem[i],
handle.GetInitHandle()->mem.mcpu.floatArr[1].floatmem[i],
halfWidth,
halfHeight,
correctionRadius,
handle.GetInitHandle()->mem.mgpu.csrcSize.height[i],
handle.GetInitHandle()->mem.mgpu.csrcSize.width[i],
channel);
// CreateProgramFromBinary(handle.GetStream(),"lens_correction.cpp","lens_correction.bin","lenscorrection_pln",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
handle.AddKernel("", "", "lens_correction.cpp", "lenscorrection_pkd", vld, vgd, "")(srcPtr1,
dstPtr1,
handle.GetInitHandle()->mem.mcpu.floatArr[0].floatmem[i],
handle.GetInitHandle()->mem.mcpu.floatArr[1].floatmem[i],
halfWidth,
halfHeight,
correctionRadius,
handle.GetInitHandle()->mem.mgpu.csrcSize.height[i],
handle.GetInitHandle()->mem.mgpu.csrcSize.width[i],
channel);
// CreateProgramFromBinary(handle.GetStream(),"lens_correction.cpp","lens_correction.bin","lenscorrection_pkd",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else
{std::cerr << "Internal error: Unknown Channel format";}
// //---- Args Setter
// err = clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &srcPtr1);
// err |= clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &dstPtr1);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &handle.GetInitHandle()->mem.mcpu.floatArr[0].floatmem[i]);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &handle.GetInitHandle()->mem.mcpu.floatArr[1].floatmem[i]);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &halfWidth);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &halfHeight);
// err |= clSetKernelArg(theKernel, counter++, sizeof(float), &correctionRadius);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.csrcSize.height[i]);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.csrcSize.width[i]);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &channel);
// //----
// cl_kernel_implementer (handle.GetStream(), gDim3, NULL/*Local*/, theProgram, theKernel);
hipMemcpy(dstPtr+batchIndex, dstPtr1, sizeof(unsigned char) * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * channel, hipMemcpyDeviceToDevice); batchIndex += handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * channel * sizeof(unsigned char);
batchIndex += handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * channel * sizeof(unsigned char);
}
return RPP_SUCCESS;
}
/************* Flip ******************/
RppStatus
flip_hip(Rpp8u * srcPtr, RppiSize srcSize, Rpp8u * dstPtr, uint flipAxis,
RppiChnFormat chnFormat, unsigned int channel,
rpp::Handle& handle)
{
if (chnFormat == RPPI_CHN_PLANAR)
{
if (flipAxis == 1)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "flip.cpp", "flip_vertical_planar", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
else if (flipAxis == 0)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "flip.cpp", "flip_horizontal_planar", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
else if (flipAxis == 2)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "flip.cpp", "flip_bothaxis_planar", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
}
else if (chnFormat == RPPI_CHN_PACKED)
{
if (flipAxis == 1)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "flip.cpp", "flip_vertical_packed", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
else if (flipAxis == 0)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "flip.cpp", "flip_horizontal_packed", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
else if (flipAxis == 2)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{srcSize.width, srcSize.height, channel};
handle.AddKernel("", "", "flip.cpp", "flip_bothaxis_packed", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel
);
}
}
return RPP_SUCCESS;
}
RppStatus
flip_hip_batch ( Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle,
RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if (chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{max_width, max_height, handle.GetBatchSize()};
// std::cout << "coming till near kernel here" << std::endl;
handle.AddKernel("", "", "flip.cpp", "flip_batch", vld, vgd, "")(srcPtr, dstPtr,
handle.GetInitHandle()->mem.mgpu.uintArr[0].uintmem,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
handle.GetInitHandle()->mem.mgpu.roiPoints.x,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth,
handle.GetInitHandle()->mem.mgpu.roiPoints.y,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
plnpkdind);
return RPP_SUCCESS;
}
/************* Resize ******************/
RppStatus
resize_hip(Rpp8u * srcPtr, RppiSize srcSize,
Rpp8u * dstPtr, RppiSize dstSize,
RppiChnFormat chnFormat, unsigned int channel,
rpp::Handle& handle)
{
if(chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "resize.cpp", "resize_pkd", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
}
else
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "resize.cpp", "resize_pln", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
}
// size_t gDim3[3];
// gDim3[0] = dstSize.width;
// gDim3[1] = dstSize.height;
// gDim3[2] = channel;
return RPP_SUCCESS;
}
RppStatus
resize_hip_batch ( Rpp8u * srcPtr, Rpp8u * dstPtr, rpp::Handle& handle,
RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
//unsigned int padding = 0;
//unsigned int type = 0;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.cdstSize.height, handle.GetInitHandle()->mem.mgpu.cdstSize.width, handle.GetBatchSize(), &max_height, &max_width);
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{max_width, max_height, handle.GetBatchSize()};
handle.AddKernel("", "", "resize.cpp", "resize_batch", vld, vgd, "")(srcPtr, dstPtr,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.dstSize.height,
handle.GetInitHandle()->mem.mgpu.dstSize.width,
handle.GetInitHandle()->mem.mgpu.roiPoints.x,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth,
handle.GetInitHandle()->mem.mgpu.roiPoints.y,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.maxDstSize.width,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
handle.GetInitHandle()->mem.mgpu.dstBatchIndex,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
handle.GetInitHandle()->mem.mgpu.dstInc,
plnpkdind
);
return RPP_SUCCESS;
}
/************* Resize Crop ******************/
RppStatus
resize_crop_hip(Rpp8u * srcPtr, RppiSize srcSize,
Rpp8u * dstPtr, RppiSize dstSize,
Rpp32u x1, Rpp32u x2, Rpp32u y1, Rpp32u y2,
RppiChnFormat chnFormat, unsigned int channel,
rpp::Handle& handle)
{
// unsigned short counter=0;
// cl_int err;
// cl_kernel theKernel;
// cl_program theProgram;
// cl_context theContext;
unsigned int type = 0, padding = 0;
unsigned int width,height;
if(type == 1)
{
width = dstSize.width - padding * 2;
height = dstSize.height - padding * 2;
}
else
{
width = dstSize.width;
height = dstSize.height;
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &dstSize.height);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &dstSize.width);
}
if(chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{width, height, channel};
handle.AddKernel("", "", "resize.cpp", "resize_crop_pkd", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
height,
width,
x1,
x2,
y1,
y2,
padding,
type,
channel
);
}
else
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{width, height, channel};
handle.AddKernel("", "", "resize.cpp", "resize_crop_pln", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
height,
width,
x1,
x2,
y1,
y2,
padding,
type,
channel
);
}
// if (chnFormat == RPPI_CHN_PLANAR)
// {
// CreateProgramFromBinary(handle,"resize.cpp","resize.cpp.bin","resize_crop_pln",theProgram,theKernel);
// clRetainKernel(theKernel);
// // cl_kernel_initializer( "resize.cpp", "resize_crop_pln",
// // theProgram, theKernel);
// }
// else if (chnFormat == RPPI_CHN_PACKED)
// {
// CreateProgramFromBinary(handle,"resize.cpp","resize.cpp.bin","resize_crop_pkd",theProgram,theKernel);
// clRetainKernel(theKernel);
// // cl_kernel_initializer( "resize.cpp", "resize_crop_pkd",
// // theProgram, theKernel);
// }
// else
// {std::cerr << "Internal error: Unknown Channel format";}
// err = clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &srcPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &dstPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.height);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.width);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &x1);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &y1);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &x2);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &y2);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &padding);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &type);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &channel);
// size_t gDim3[3];
// if(type == 1)
// {
// gDim3[0] = dstSize.width - padding * 2;
// gDim3[1] = dstSize.height - padding * 2;
// gDim3[2] = channel;
// }
// else
// {
// gDim3[0] = dstSize.width;
// gDim3[1] = dstSize.height;
// gDim3[2] = channel;
// }
// cl_kernel_implementer (handle, gDim3, NULL/*Local*/, theProgram, theKernel);
return RPP_SUCCESS;
}
RppStatus
resize_crop_hip_batch ( Rpp8u * srcPtr, Rpp8u * dstPtr, rpp::Handle& handle,
RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if (chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
unsigned int padding = 10;
unsigned int type = 1;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.cdstSize.height, handle.GetInitHandle()->mem.mgpu.cdstSize.width, handle.GetBatchSize(), &max_height, &max_width);
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{max_width, max_height, handle.GetBatchSize()};
//std::cout << "coming till here" << std::endl;
handle.AddKernel("", "", "resize.cpp", "resize_crop_batch", vld, vgd, "")(srcPtr, dstPtr,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.dstSize.height,
handle.GetInitHandle()->mem.mgpu.dstSize.width,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.maxDstSize.width,
handle.GetInitHandle()->mem.mgpu.uintArr[0].uintmem,
handle.GetInitHandle()->mem.mgpu.uintArr[1].uintmem,
handle.GetInitHandle()->mem.mgpu.uintArr[2].uintmem,
handle.GetInitHandle()->mem.mgpu.uintArr[3].uintmem,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
handle.GetInitHandle()->mem.mgpu.dstBatchIndex,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
handle.GetInitHandle()->mem.mgpu.dstInc,
padding,
type,
plnpkdind);
return RPP_SUCCESS;
}
/*************Rotate ******************/
RppStatus
rotate_hip(Rpp8u * srcPtr, RppiSize srcSize,
Rpp8u * dstPtr, RppiSize dstSize, float angleDeg,
RppiChnFormat chnFormat, unsigned int channel,
rpp::Handle& handle)
{
if(chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "rotate.cpp", "rotate_pkd", vld, vgd, "")(srcPtr,
dstPtr,
angleDeg,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
}
else
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "rotate.cpp", "rotate_pln", vld, vgd, "")(srcPtr,
dstPtr,
angleDeg,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
}
return RPP_SUCCESS;
}
RppStatus
rotate_hip_batch ( Rpp8u * srcPtr, Rpp8u * dstPtr, rpp::Handle& handle,
RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.cdstSize.height, handle.GetInitHandle()->mem.mgpu.cdstSize.width, handle.GetBatchSize(), &max_height, &max_width);
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{max_width, max_height, handle.GetBatchSize()};
handle.AddKernel("", "", "rotate.cpp", "rotate_batch", vld, vgd, "")(srcPtr, dstPtr,
handle.GetInitHandle()->mem.mgpu.floatArr[0].floatmem,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.dstSize.height,
handle.GetInitHandle()->mem.mgpu.dstSize.width,
handle.GetInitHandle()->mem.mgpu.roiPoints.x,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth,
handle.GetInitHandle()->mem.mgpu.roiPoints.y,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.maxDstSize.width,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
handle.GetInitHandle()->mem.mgpu.dstBatchIndex,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
handle.GetInitHandle()->mem.mgpu.dstInc,
plnpkdind
);
return RPP_SUCCESS;
}
/************* Warp affine ******************/
RppStatus
warp_affine_hip(Rpp8u * srcPtr, RppiSize srcSize,
Rpp8u * dstPtr, RppiSize dstSize, float *affine,
RppiChnFormat chnFormat, unsigned int channel,
rpp::Handle& handle)
{
float affine_inv[6];
float det; //for Deteminent
det = (affine[0] * affine [4]) - (affine[1] * affine[3]);
affine_inv[0] = affine[4]/ det;
affine_inv[1] = (- 1 * affine[1])/ det;
affine_inv[2] = -1 * affine[2];
affine_inv[3] = (-1 * affine[3]) /det ;
affine_inv[4] = affine[0]/det;
affine_inv[5] = -1 * affine[5];
float *affine_matrix;
Rpp32u* affine_array;
hipMalloc(&affine_array, sizeof(float)*6);
hipMemcpy(affine_array,affine_inv,sizeof(float)*6,hipMemcpyHostToDevice);
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "warp_affine.cpp", "warp_affine_pln", vld, vgd, "")(srcPtr,
dstPtr,
affine_array,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
// CreateProgramFromBinary(handle,"warp_affine.cpp","warp_affine.cpp.bin","waro_affine_pln",theProgram,theKernel);
// clRetainKernel(theKernel);
// cl_kernel_initializer( "rotate.cpp", "rotate_pln",
// theProgram, theKernel);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "warp_affine.cpp", "warp_affine_pkd", vld, vgd, "")(srcPtr,
dstPtr,
affine_array,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
// CreateProgramFromBinary(handle,"warp_affine.cpp","warp_affine.cpp.bin","warp_affine_pkd",theProgram,theKernel);
// clRetainKernel(theKernel);
// cl_kernel_initializer( "rotate.cpp", "rotate_pkd",
// theProgram, theKernel);
}
else
{std::cerr << "Internal error: Unknown Channel format";}
// err = clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &srcPtr);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &dstPtr);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &affine_array);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &srcSize.height);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &srcSize.width);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &dstSize.height);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &dstSize.width);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &channel);
// size_t gDim3[3];
// gDim3[0] = dstSize.width;
// gDim3[1] = dstSize.height;
// gDim3[2] = channel;
// cl_kernel_implementer (handle, gDim3, NULL/*Local*/, theProgram, theKernel);
return RPP_SUCCESS;
}
RppStatus
warp_affine_hip_batch(Rpp8u * srcPtr, Rpp8u * dstPtr, rpp::Handle& handle,Rpp32f *affine,
RppiChnFormat chnFormat, unsigned int channel)
// Rpp8u* srcPtr, RppiSize *srcSize, RppiSize *src_maxSize,
// Rpp8u* dstPtr, RppiSize *dstSize, RppiSize *dst_maxSize,
// Rpp32f *affine, Rpp32u nBatchSize,
// RppiChnFormat chnFormat, unsigned int channel,
// rpp::Handle& handle)
{
Rpp32u nBatchSize = handle.GetBatchSize();
float affine_inv[6];
float det; //for Deteminent
short counter;
size_t gDim3[3];
Rpp32f* affine_array;
hipMalloc(&affine_array, sizeof(float)*6);
unsigned int maxsrcHeight, maxsrcWidth, maxdstHeight, maxdstWidth;
maxsrcHeight = handle.GetInitHandle()->mem.mgpu.csrcSize.height[0];
maxsrcWidth = handle.GetInitHandle()->mem.mgpu.csrcSize.width[0];
maxdstHeight = handle.GetInitHandle()->mem.mgpu.cdstSize.height[0];
maxdstWidth = handle.GetInitHandle()->mem.mgpu.cdstSize.width[0];
for(int i = 0 ; i < nBatchSize ; i++)
{
if(maxsrcHeight < handle.GetInitHandle()->mem.mgpu.csrcSize.height[i])
maxsrcHeight = handle.GetInitHandle()->mem.mgpu.csrcSize.height[i];
if(maxsrcWidth < handle.GetInitHandle()->mem.mgpu.csrcSize.width[i])
maxsrcWidth = handle.GetInitHandle()->mem.mgpu.csrcSize.width[i];
if(maxdstHeight < handle.GetInitHandle()->mem.mgpu.cdstSize.height[i])
maxdstHeight = handle.GetInitHandle()->mem.mgpu.cdstSize.height[i];
if(maxdstWidth < handle.GetInitHandle()->mem.mgpu.cdstSize.width[i])
maxdstWidth = handle.GetInitHandle()->mem.mgpu.cdstSize.width[i];
}
Rpp8u * srcPtr1;
hipMalloc(&srcPtr1,sizeof(unsigned char) * maxsrcHeight * maxsrcWidth * channel);
Rpp8u * dstPtr1;
hipMalloc(&dstPtr1,sizeof(unsigned char) * maxdstHeight * maxdstWidth * channel);
int ctr;
size_t srcbatchIndex = 0, dstbatchIndex = 0;
size_t index =0;
for(int i =0; i<nBatchSize; i++)
{
hipMemcpy(srcPtr1, srcPtr+srcbatchIndex , sizeof(unsigned char) * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * channel, hipMemcpyDeviceToDevice); det = (affine[index+0] * affine [index+4]) - (affine[index+1] * affine[index+3]);
affine_inv[0] = affine[index+4]/ det;
affine_inv[1] = (- 1 * affine[index+1])/ det;
affine_inv[2] = -1 * affine[index+2];
affine_inv[3] = (-1 * affine[index+3]) /det ;
affine_inv[4] = affine[index+0]/det;
affine_inv[5] = -1 * affine[index+5];
hipMemcpy(affine_array,affine_inv,sizeof(float)*6,hipMemcpyHostToDevice);
gDim3[0] = handle.GetInitHandle()->mem.mgpu.cdstSize.width[i];
gDim3[1] = handle.GetInitHandle()->mem.mgpu.cdstSize.height[i];
gDim3[2] = channel;
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{gDim3[0], gDim3[1], gDim3[2]};
handle.AddKernel("", "", "warp_affine.cpp", "warp_affine_pln", vld, vgd, "")(srcPtr,
dstPtr,
affine_array,
handle.GetInitHandle()->mem.mgpu.csrcSize.height[i],
handle.GetInitHandle()->mem.mgpu.csrcSize.width[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.height[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.width[i],
channel
);
// CreateProgramFromBinary(handle.GetStream(),"warp_affine.cpp","warp_affine.cpp.bin","warp_affine_pln",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{gDim3[0], gDim3[1], gDim3[2]};
handle.AddKernel("", "", "warp_affine.cpp", "warp_affine_pkd", vld, vgd, "")(srcPtr,
dstPtr,
affine_array,
handle.GetInitHandle()->mem.mgpu.csrcSize.height[i],
handle.GetInitHandle()->mem.mgpu.csrcSize.width[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.height[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.width[i],
channel
);
// CreateProgramFromBinary(handle.GetStream(),"warp_affine.cpp","warp_affine.cpp.bin","warp_affine_pkd",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else
{std::cerr << "Internal error: Unknown Channel format";}
// int ctr =0;
// err = clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &srcPtr1);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &dstPtr1);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &affine_array);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.csrcSize.height[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.csrcSize.width[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.cdstSize.height[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.cdstSize.width[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &channel);
// cl_kernel_implementer (gDim3, NULL/*Local*/, theProgram, theKernel);
hipMemcpy(dstPtr+dstbatchIndex, dstPtr1, sizeof(unsigned char) * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * channel, hipMemcpyDeviceToDevice); srcbatchIndex += handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * channel * sizeof(unsigned char);
dstbatchIndex += handle.GetInitHandle()->mem.mgpu.cdstSize.height[i] * handle.GetInitHandle()->mem.mgpu.cdstSize.width[i] * channel * sizeof(unsigned char);
index = index + 6;
}
return RPP_SUCCESS;
/* CLrelease should come here */
}
/************* Warp Perspective ******************/
RppStatus
warp_perspective_hip(Rpp8u * srcPtr, RppiSize srcSize, Rpp8u * dstPtr,
RppiSize dstSize, float *perspective, RppiChnFormat chnFormat,
unsigned int channel, rpp::Handle& handle)
{
float perspective_inv[9];
float det; //for Deteminent
det = (perspective[0] * ((perspective[4] * perspective[8]) - (perspective[5] * perspective[7]))) - (perspective[1] * ((perspective[3] * perspective[8]) - (perspective[5] * perspective[6]))) + (perspective[2] * ((perspective[3] * perspective[7]) - (perspective[4] * perspective[6])));
perspective_inv[0] = (1 * ((perspective[4] * perspective[8]) - (perspective[5] * perspective[7]))) / det;
perspective_inv[1] = (-1 * ((perspective[1] * perspective[8]) - (perspective[7] * perspective[2]))) / det;
perspective_inv[2] = (1 * ((perspective[1] * perspective[5]) - (perspective[4] * perspective[2]))) / det;
perspective_inv[3] = (-1 * ((perspective[3] * perspective[8]) - (perspective[6] * perspective[5]))) / det;
perspective_inv[4] = (1 * ((perspective[0] * perspective[8]) - (perspective[6] * perspective[2]))) / det;
perspective_inv[5] = (-1 * ((perspective[0] * perspective[5]) - (perspective[3] * perspective[2]))) / det;
perspective_inv[6] = (1 * ((perspective[3] * perspective[7]) - (perspective[6] * perspective[4]))) / det;
perspective_inv[7] = (-1 * ((perspective[0] * perspective[7]) - (perspective[6] * perspective[1]))) / det;
perspective_inv[8] = (1 * ((perspective[0] * perspective[4]) - (perspective[3] * perspective[1]))) / det;
float *perspective_matrix;
Rpp32f* perspective_array;
hipMalloc(&perspective_array, sizeof(float) * 9);
hipMemcpy(perspective_array, perspective_inv,sizeof(float) * 9, hipMemcpyHostToDevice);
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "warp_perspective.cpp", "warp_perspective_pln", vld, vgd, "")(srcPtr,
dstPtr,
perspective_array,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
// CreateProgramFromBinary(handle.GetStream(),"warp_perspective.cpp","warp_perspective.cpp.bin","warp_perspective_pln",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "warp_perspective.cpp", "warp_perspective_pln", vld, vgd, "")(srcPtr,
dstPtr,
perspective_array,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel
);
// CreateProgramFromBinary(handle.GetStream(),"warp_perspective.cpp","warp_perspective.cpp.bin","warp_perspective_pkd",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else
{
std::cerr << "Internal error: Unknown Channel format";
}
// int ctr =0;
// err = clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &srcPtr);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &dstPtr);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &perspective_array);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &srcSize.height);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &srcSize.width);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &dstSize.height);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &dstSize.width);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &channel);
// size_t gDim3[3];
// gDim3[0] = dstSize.width;
// gDim3[1] = dstSize.height;
// gDim3[2] = channel;
// cl_kernel_implementer (gDim3, NULL/*Local*/, theProgram, theKernel);
return RPP_SUCCESS;
}
RppStatus
warp_perspective_hip_batch(Rpp8u * srcPtr, Rpp8u * dstPtr, rpp::Handle& handle,Rpp32f *perspective,
RppiChnFormat chnFormat, unsigned int channel)
// Rpp8u* srcPtr, RppiSize *srcSize, RppiSize *src_maxSize,
// Rpp8u* dstPtr, RppiSize *dstSize, RppiSize *dst_maxSize,
// Rpp32f *perspective, Rpp32u nBatchSize,
// RppiChnFormat chnFormat, unsigned int channel,
// rpp::Handle& handle)
{
Rpp32u nBatchSize = handle.GetBatchSize();
float perspective_inv[9];
float det; //for Deteminent
short counter;
size_t gDim3[3];
Rpp32f* perspective_array;
hipMalloc(&perspective_array,sizeof(float)*9);
unsigned int maxsrcHeight, maxsrcWidth, maxdstHeight, maxdstWidth;
maxsrcHeight = handle.GetInitHandle()->mem.mgpu.csrcSize.height[0];
maxsrcWidth = handle.GetInitHandle()->mem.mgpu.csrcSize.width[0];
maxdstHeight = handle.GetInitHandle()->mem.mgpu.cdstSize.height[0];
maxdstWidth = handle.GetInitHandle()->mem.mgpu.cdstSize.width[0];
for(int i = 0 ; i < nBatchSize ; i++)
{
if(maxsrcHeight < handle.GetInitHandle()->mem.mgpu.csrcSize.height[i])
maxsrcHeight = handle.GetInitHandle()->mem.mgpu.csrcSize.height[i];
if(maxsrcWidth < handle.GetInitHandle()->mem.mgpu.csrcSize.width[i])
maxsrcWidth = handle.GetInitHandle()->mem.mgpu.csrcSize.width[i];
if(maxdstHeight < handle.GetInitHandle()->mem.mgpu.cdstSize.height[i])
maxdstHeight = handle.GetInitHandle()->mem.mgpu.cdstSize.height[i];
if(maxdstWidth < handle.GetInitHandle()->mem.mgpu.cdstSize.width[i])
maxdstWidth = handle.GetInitHandle()->mem.mgpu.cdstSize.width[i];
}
Rpp8u * srcPtr1;
hipMalloc(&srcPtr1, sizeof(unsigned char) * maxsrcHeight * maxsrcWidth * channel);
Rpp8u * dstPtr1;
hipMalloc(&dstPtr1, sizeof(unsigned char) * maxdstHeight * maxdstWidth * channel);
int ctr;
size_t srcbatchIndex = 0, dstbatchIndex = 0;
size_t index =0;
for(int i =0; i<nBatchSize; i++)
{
hipMemcpy(srcPtr1, srcPtr+srcbatchIndex , sizeof(unsigned char) * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] *
handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * channel, hipMemcpyDeviceToDevice);
det = (perspective[index] * ((perspective[index+4] * perspective[index+8]) - (perspective[index+5] * perspective[index+7]))) - (perspective[index+1] * ((perspective[index+3] * perspective[index+8]) - (perspective[index+5] * perspective[index+6]))) + (perspective[index+2] * ((perspective[index+3] * perspective[index+7]) - (perspective[index+4] * perspective[index+6])));
perspective_inv[0] = (1 * ((perspective[index+4] * perspective[index+8]) - (perspective[index+5] * perspective[index+7]))) / det;
perspective_inv[1] = (-1 * ((perspective[index+1] * perspective[index+8]) - (perspective[index+7] * perspective[index+2]))) / det;
perspective_inv[2] = (1 * ((perspective[index+1] * perspective[index+5]) - (perspective[index+4] * perspective[index+2]))) / det;
perspective_inv[3] = (-1 * ((perspective[index+3] * perspective[index+8]) - (perspective[index+6] * perspective[index+5]))) / det;
perspective_inv[4] = (1 * ((perspective[index] * perspective[index+8]) - (perspective[index+6] * perspective[index+2]))) / det;
perspective_inv[5] = (-1 * ((perspective[index] * perspective[index+5]) - (perspective[index+3] * perspective[index+2]))) / det;
perspective_inv[6] = (1 * ((perspective[index+3] * perspective[index+7]) - (perspective[index+6] * perspective[index+4]))) / det;
perspective_inv[7] = (-1 * ((perspective[index] * perspective[index+7]) - (perspective[index+6] * perspective[index+1]))) / det;
perspective_inv[8] = (1 * ((perspective[index] * perspective[index+4]) - (perspective[index+3] * perspective[index+1]))) / det;
hipMemcpy(perspective_array,perspective_inv,sizeof(float)*9,hipMemcpyHostToDevice);
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{handle.GetInitHandle()->mem.mgpu.cdstSize.width[i], handle.GetInitHandle()->mem.mgpu.cdstSize.height[i], channel};
handle.AddKernel("", "", "warp_perspective.cpp", "warp_perspective_pln", vld, vgd, "")(srcPtr1,
dstPtr1,
perspective_array,
handle.GetInitHandle()->mem.mgpu.csrcSize.height[i],
handle.GetInitHandle()->mem.mgpu.csrcSize.width[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.height[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.width[i],
channel
);
// CreateProgramFromBinary(handle.GetStream(),"warp_perspective.cpp","warp_perspective.cpp.bin","warp_perspective_pln",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{handle.GetInitHandle()->mem.mgpu.cdstSize.width[i], handle.GetInitHandle()->mem.mgpu.cdstSize.height[i], channel};
handle.AddKernel("", "", "warp_perspective.cpp", "warp_perspective_pkd", vld, vgd, "")(srcPtr1,
dstPtr1,
perspective_array,
handle.GetInitHandle()->mem.mgpu.csrcSize.height[i],
handle.GetInitHandle()->mem.mgpu.csrcSize.width[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.height[i],
handle.GetInitHandle()->mem.mgpu.cdstSize.width[i],
channel
);
// CreateProgramFromBinary(handle.GetStream(),"warp_perspective.cpp","warp_perspective.cpp.bin","warp_perspective_pkd",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else
{std::cerr << "Internal error: Unknown Channel format";}
// int ctr =0;
// err = clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &srcPtr1);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &dstPtr1);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(Rpp8u*), &perspective_array);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.csrcSize.height[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.csrcSize.width[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.cdstSize.height[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &handle.GetInitHandle()->mem.mgpu.cdstSize.width[i]);
// err |= clSetKernelArg(theKernel, ctr++, sizeof(unsigned int), &channel);
// gDim3[0] = handle.GetInitHandle()->mem.mgpu.cdstSize.width[i];
// gDim3[1] = handle.GetInitHandle()->mem.mgpu.cdstSize.height[i];
// gDim3[2] = channel;
// cl_kernel_implementer (gDim3, NULL/*Local*/, theProgram, theKernel);
hipMemcpy(dstPtr+dstbatchIndex, dstPtr1, sizeof(unsigned char) * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * channel, hipMemcpyDeviceToDevice); srcbatchIndex += handle.GetInitHandle()->mem.mgpu.csrcSize.height[i] * handle.GetInitHandle()->mem.mgpu.csrcSize.width[i] * channel * sizeof(unsigned char);
dstbatchIndex += handle.GetInitHandle()->mem.mgpu.cdstSize.height[i] * handle.GetInitHandle()->mem.mgpu.cdstSize.width[i] * channel * sizeof(unsigned char);
index = index + 9;
}
return RPP_SUCCESS;
/* CLrelease should come here */
}
// /************* Scale ******************/
RppStatus
scale_hip(Rpp8u * srcPtr, RppiSize srcSize, Rpp8u * dstPtr, RppiSize dstSize,
Rpp32f percentage, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
percentage /= 100;
unsigned int dstheight = (Rpp32s) (percentage * (Rpp32f) srcSize.height);
unsigned int dstwidth = (Rpp32s) (percentage * (Rpp32f) srcSize.width);
unsigned short counter=0;
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "scale.cpp", "scale_pln", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel,
dstheight,
dstwidth
);
// CreateProgramFromBinary(handle.GetStream(),"resize.cpp","resize.cpp.bin","resize_pln",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else if (chnFormat == RPPI_CHN_PACKED)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{dstSize.width, dstSize.height, channel};
handle.AddKernel("", "", "scale.cpp", "scale_pkd", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
dstSize.height,
dstSize.width,
channel,
dstheight,
dstwidth
);
// CreateProgramFromBinary(handle.GetStream(),"resize.cpp","resize.cpp.bin","resize_pkd",theProgram,theKernel);
// clRetainKernel(theKernel);
}
else
{
std::cerr << "Internal error: Unknown Channel format";
}
// err = clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &srcPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(Rpp8u*), &dstPtr);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.height);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.width);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &dstSize.height);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &dstSize.width);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &channel);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &dstheight);
// err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &dstwidth);
// size_t gDim3[3];
// gDim3[0] = dstSize.width;
// gDim3[1] = dstSize.height;
// gDim3[2] = channel;
// cl_kernel_implementer (gDim3, NULL/*Local*/, theProgram, theKernel);
return RPP_SUCCESS;
}
RppStatus
scale_hip_batch (Rpp8u * srcPtr, Rpp8u * dstPtr, rpp::Handle& handle,
RppiChnFormat chnFormat, unsigned int channel)
// Rpp8u* srcPtr, RppiSize *srcSize, RppiSize *src_maxSize,
// Rpp8u* dstPtr, RppiSize *dstSize, RppiSize *dst_maxSize,
// Rpp32f *percentage, Rpp32u nBatchSize,
// RppiChnFormat chnFormat, unsigned int channel,
// rpp::Handle& handle)
{
int plnpkdind;
if (chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
unsigned int padding = 0;
unsigned int type = 0;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.cdstSize.height, handle.GetInitHandle()->mem.mgpu.cdstSize.width, handle.GetBatchSize(), &max_height, &max_width);
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{max_width, max_height, handle.GetBatchSize()};
//std::cout << "coming till here" << std::endl;
handle.AddKernel("", "", "scale.cpp", "scale_batch", vld, vgd, "")(srcPtr, dstPtr,
handle.GetInitHandle()->mem.mgpu.floatArr[0].floatmem,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.dstSize.height,
handle.GetInitHandle()->mem.mgpu.dstSize.width,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.maxDstSize.width,
handle.GetInitHandle()->mem.mgpu.roiPoints.x,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth,
handle.GetInitHandle()->mem.mgpu.roiPoints.y,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
handle.GetInitHandle()->mem.mgpu.dstBatchIndex,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
handle.GetInitHandle()->mem.mgpu.dstInc,
plnpkdind);
return RPP_SUCCESS;
} | 61.093617 | 379 | 0.446779 | [
"vector"
] |
758f728e717731e2b06018da563aea3a3efce68d | 2,254 | cpp | C++ | modules/ruby/k_ruby_list.cpp | appcelerator/kroll | 50b9788d2c391db7676ad0d32f6d8271f51e2a66 | [
"Apache-2.0"
] | 17 | 2015-01-23T08:23:12.000Z | 2019-07-24T11:44:31.000Z | kroll/modules/ruby/k_ruby_list.cpp | MChorfa/TideSDK | fae6a35e39a0171942060948084f884391cf6f8a | [
"Apache-2.0"
] | 1 | 2016-03-04T06:11:37.000Z | 2016-03-04T06:11:37.000Z | kroll/modules/ruby/k_ruby_list.cpp | MChorfa/TideSDK | fae6a35e39a0171942060948084f884391cf6f8a | [
"Apache-2.0"
] | 9 | 2015-02-10T17:22:04.000Z | 2019-05-17T08:45:05.000Z | /**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "ruby_module.h"
#include <cstring>
namespace kroll
{
KRubyList::KRubyList(VALUE list) :
KList("Ruby.KRubyList"),
list(list),
object(new KRubyObject(list))
{
rb_gc_register_address(&list);
}
KRubyList::~KRubyList()
{
rb_gc_unregister_address(&list);
}
void KRubyList::Append(KValueRef value)
{
rb_ary_push(list, RubyUtils::ToRubyValue(value));
}
unsigned int KRubyList::Size()
{
return (unsigned int) RARRAY_LEN(list);
}
bool KRubyList::Remove(unsigned int index)
{
return (rb_ary_delete_at(list, index) != Qnil);
}
KValueRef KRubyList::At(unsigned int index)
{
if (index >= 0 && index < this->Size())
{
return RubyUtils::ToKrollValue(rb_ary_entry(list, index));
}
else
{
return Value::Undefined;
}
}
void KRubyList::Set(const char* name, KValueRef value)
{
if (KList::IsInt(name))
{
this->SetAt(KList::ToIndex(name), value);
}
else
{
this->object->Set(name, value);
}
}
void KRubyList::SetAt(unsigned int index, KValueRef value)
{
VALUE rv = RubyUtils::ToRubyValue(value);
// rb_ary_store will take care of sizing the list
// appropriately in the case that index > current list size
rb_ary_store(list, index, rv);
}
KValueRef KRubyList::Get(const char* name)
{
if (KList::IsInt(name))
{
return this->At(KList::ToIndex(name));
}
else
{
return object->Get(name);
}
}
SharedStringList KRubyList::GetPropertyNames()
{
SharedStringList property_names = object->GetPropertyNames();
for (size_t i = 0; i < this->Size(); i++)
{
std::string name = KList::IntToChars(i);
property_names->push_back(new std::string(name));
}
return property_names;
}
VALUE KRubyList::ToRuby()
{
return this->object->ToRuby();
}
SharedString KRubyList::DisplayString(int levels)
{
return this->object->DisplayString(levels);
}
bool KRubyList::Equals(KObjectRef other)
{
AutoPtr<KRubyList> listOther = other.cast<KRubyList>();
if (listOther.isNull())
return false;
return listOther->ToRuby() == this->ToRuby();
}
}
| 19.6 | 66 | 0.679237 | [
"object"
] |
758fbb82bc96f7a605208e4d1017577724dff063 | 1,126 | cpp | C++ | libnet/src/libnet.cpp | avdgrinten/managarm | 4c4478cbde21675ca31e65566f10e1846b268bd5 | [
"MIT"
] | 13 | 2017-02-13T23:29:44.000Z | 2021-09-30T05:41:21.000Z | libnet/src/libnet.cpp | avdgrinten/managarm | 4c4478cbde21675ca31e65566f10e1846b268bd5 | [
"MIT"
] | 12 | 2016-12-03T13:06:13.000Z | 2018-05-04T15:49:17.000Z | libnet/src/libnet.cpp | avdgrinten/managarm | 4c4478cbde21675ca31e65566f10e1846b268bd5 | [
"MIT"
] | 1 | 2021-12-01T19:01:53.000Z | 2021-12-01T19:01:53.000Z |
#include <stdio.h>
#include <stdlib.h>
#include <fs.pb.h>
#include <libnet.hpp>
#include "udp.hpp"
#include "tcp.hpp"
#include "dns.hpp"
#include "arp.hpp"
#include "usernet.hpp"
#include "ethernet.hpp"
#include "network.hpp"
namespace libnet {
uint32_t dhcpTransaction = 0xD61FF088; // some random integer
DhcpState dhcpState = kDefaultState;
NetDevice *globalDevice;
Ip4Address dnsIp;
Ip4Address localIp;
Ip4Address routerIp;
Ip4Address subnetMask;
MacAddress localMac;
MacAddress routerMac;
TcpSocket tcpSocket;
void receivePacket(EthernetInfo link_info, Ip4Info network_info, void *buffer, size_t length);
void deviceReady(void *object) {
printf("Network registered!\n");
}
void testDevice(helx::EventHub &event_hub, NetDevice &device, uint8_t mac_octets[6]) {
globalDevice = &device;
memcpy(localMac.octets, mac_octets, 6);
//sendDhcpDiscover(device);
auto network = new Network(device);
auto client = new Client(event_hub, *network);
client->init(CALLBACK_STATIC(nullptr, &deviceReady));
};
void onReceive(void *buffer, size_t length) {
receiveEthernetPacket(buffer, length);
}
} // namespace libnet
| 22.52 | 94 | 0.760213 | [
"object"
] |
75934fb0430796d4578f71c3536e60aedd7341ee | 3,133 | cpp | C++ | examples/serialize/vector_int_reader/vector_int_reader.cpp | paulhuggett/pstore2 | a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c | [
"Apache-2.0"
] | 11 | 2018-02-02T21:24:49.000Z | 2020-12-11T04:06:03.000Z | examples/serialize/vector_int_reader/vector_int_reader.cpp | SNSystems/pstore | 74e9dd960245d6bfc125af03ed964d8ad660a62d | [
"Apache-2.0"
] | 63 | 2018-02-05T17:24:59.000Z | 2022-03-22T17:26:28.000Z | examples/serialize/vector_int_reader/vector_int_reader.cpp | paulhuggett/pstore | 067be94d87c87fce524c8d76c6f47c347d8f1853 | [
"Apache-2.0"
] | 5 | 2020-01-13T22:47:11.000Z | 2021-05-14T09:31:15.000Z | //===- examples/serialize/vector_int_reader/vector_int_reader.cpp ---------===//
//* _ _ _ _ *
//* __ _____ ___| |_ ___ _ __ (_)_ __ | |_ _ __ ___ __ _ __| | ___ _ __ *
//* \ \ / / _ \/ __| __/ _ \| '__| | | '_ \| __| | '__/ _ \/ _` |/ _` |/ _ \ '__| *
//* \ V / __/ (__| || (_) | | | | | | | |_ | | | __/ (_| | (_| | __/ | *
//* \_/ \___|\___|\__\___/|_| |_|_| |_|\__| |_| \___|\__,_|\__,_|\___|_| *
//* *
//===----------------------------------------------------------------------===//
//
// Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
// See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
// information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include <iomanip>
#include "pstore/serialize/archive.hpp"
#include "pstore/serialize/standard_types.hpp"
#include "pstore/serialize/types.hpp"
#include "pstore/support/gsl.hpp"
#include "pstore/support/ios_state.hpp"
using namespace pstore;
namespace {
template <typename InputIterator>
std::ostream & dump (std::ostream & os, InputIterator begin, InputIterator end) {
pstore::ios_flags_saver const _{os};
auto separator = "";
os << std::setfill ('0') << std::hex;
std::for_each (begin, end, [&] (unsigned const v) {
os << separator << std::setw (2) << v;
separator = " ";
});
return os;
}
using container_type = std::vector<std::uint8_t>;
void read_one_int_at_a_time (container_type const & bytes) {
auto reader = serialize::archive::make_reader (std::begin (bytes));
int const v1 = serialize::read<int> (reader);
int const v2 = serialize::read<int> (reader);
std::cout << "Reading one int at a time produced " << v1 << ", " << v2 << '\n';
}
void read_an_array_of_ints (container_type const & bytes) {
auto reader = serialize::archive::make_reader (std::begin (bytes));
std::array<int, 2> arr;
serialize::read (reader, gsl::make_span<int> (arr));
std::cout << "Reading an array of ints produced " << arr[0] << ", " << arr[1] << '\n';
}
void read_a_series_of_ints (container_type const & bytes) {
auto reader = serialize::archive::make_reader (std::begin (bytes));
auto const v0 = serialize::read<int> (reader);
auto const v1 = serialize::read<int> (reader);
std::cout << "Reading a series of ints produced " << v0 << ", " << v1 << '\n';
}
} // namespace
int main () {
container_type const data{0x1e, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00};
std::cout << "Reading two ints from the following input data:\n";
dump (std::cout, std::begin (data), std::end (data));
std::cout << '\n';
read_one_int_at_a_time (data);
read_an_array_of_ints (data);
read_a_series_of_ints (data);
}
| 41.773333 | 94 | 0.529205 | [
"vector"
] |
7599b653ea8b71bd1d0a8820185d22387400d88e | 13,761 | cpp | C++ | src/mongo/util/text.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/util/text.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/util/text.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/util/text.h"
#include <boost/integer_traits.hpp>
#include <errno.h>
#include <iostream>
#include <memory>
#include <sstream>
#ifdef _WIN32
#include <io.h>
#endif
#include "mongo/platform/basic.h"
#include "mongo/util/allocator.h"
#include "mongo/util/str.h"
namespace mongo {
// --- StringSplitter ----
/** get next split string fragment */
std::string StringSplitter::next() {
const char* foo = strstr(_big, _splitter);
if (foo) {
std::string s(_big, foo - _big);
_big = foo + strlen(_splitter);
while (*_big && strstr(_big, _splitter) == _big)
_big++;
return s;
}
std::string s = _big;
_big += strlen(_big);
return s;
}
void StringSplitter::split(std::vector<std::string>& l) {
while (more()) {
l.push_back(next());
}
}
std::vector<std::string> StringSplitter::split() {
std::vector<std::string> l;
split(l);
return l;
}
std::string StringSplitter::join(const std::vector<std::string>& l, const std::string& split) {
std::stringstream ss;
for (unsigned i = 0; i < l.size(); i++) {
if (i > 0)
ss << split;
ss << l[i];
}
return ss.str();
}
std::vector<std::string> StringSplitter::split(const std::string& big,
const std::string& splitter) {
StringSplitter ss(big.c_str(), splitter.c_str());
return ss.split();
}
// --- utf8 utils ------
inline int leadingOnes(unsigned char c) {
if (c < 0x80)
return 0;
static const char _leadingOnes[128] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 - 0x8F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 - 0x99
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xA0 - 0xA9
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xB0 - 0xB9
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xC0 - 0xC9
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xD0 - 0xD9
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xE0 - 0xE9
4, 4, 4, 4, 4, 4, 4, 4, // 0xF0 - 0xF7
5, 5, 5, 5, // 0xF8 - 0xFB
6, 6, // 0xFC - 0xFD
7, // 0xFE
8, // 0xFF
};
return _leadingOnes[c & 0x7f];
}
bool isValidUTF8(StringData s) {
int left = 0; // how many bytes are left in the current codepoint
for (unsigned char c : s) {
const int ones = leadingOnes(c);
if (left) {
if (ones != 1)
return false; // should be a continuation byte
left--;
} else {
if (ones == 0)
continue; // ASCII byte
if (ones == 1)
return false; // unexpected continuation byte
if (c > 0xF4)
return false; // codepoint too large (< 0x10FFFF)
if (c == 0xC0 || c == 0xC1)
return false; // codepoints <= 0x7F shouldn't be 2 bytes
// still valid
left = ones - 1;
}
}
if (left != 0)
return false; // string ended mid-codepoint
return true;
}
#if defined(_WIN32)
std::string toUtf8String(const std::wstring& wide) {
if (wide.size() > boost::integer_traits<int>::const_max)
throw std::length_error("Wide string cannot be more than INT_MAX characters long.");
if (wide.size() == 0)
return "";
// Calculate necessary buffer size
int len = ::WideCharToMultiByte(
CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()), nullptr, 0, nullptr, nullptr);
// Perform actual conversion
if (len > 0) {
std::vector<char> buffer(len);
len = ::WideCharToMultiByte(CP_UTF8,
0,
wide.c_str(),
static_cast<int>(wide.size()),
&buffer[0],
static_cast<int>(buffer.size()),
nullptr,
nullptr);
if (len > 0) {
verify(len == static_cast<int>(buffer.size()));
return std::string(&buffer[0], buffer.size());
}
}
msgasserted(16091, str::stream() << "can't wstring to utf8: " << ::GetLastError());
return "";
}
std::wstring toWideStringFromStringData(StringData utf8String) {
int bufferSize = MultiByteToWideChar(CP_UTF8, // Code page
0, // Flags
utf8String.rawData(), // Input string
utf8String.size(), // Count, -1 for NUL-terminated
nullptr, // No output buffer
0 // Zero means "compute required size"
);
if (bufferSize == 0) {
return std::wstring();
}
std::unique_ptr<wchar_t[]> tempBuffer(new wchar_t[bufferSize]);
tempBuffer[0] = L'0';
MultiByteToWideChar(CP_UTF8, // Code page
0, // Flags
utf8String.rawData(), // Input string
utf8String.size(), // Count, -1 for NUL-terminated
tempBuffer.get(), // UTF-16 output buffer
bufferSize // Buffer size in wide characters
);
return std::wstring(tempBuffer.get(), bufferSize);
}
std::wstring toWideString(const char* utf8String) {
int bufferSize = MultiByteToWideChar(CP_UTF8, // Code page
0, // Flags
utf8String, // Input string
-1, // Count, -1 for NUL-terminated
nullptr, // No output buffer
0 // Zero means "compute required size"
);
if (bufferSize == 0) {
return std::wstring();
}
std::unique_ptr<wchar_t[]> tempBuffer(new wchar_t[bufferSize]);
tempBuffer[0] = 0;
MultiByteToWideChar(CP_UTF8, // Code page
0, // Flags
utf8String, // Input string
-1, // Count, -1 for NUL-terminated
tempBuffer.get(), // UTF-16 output buffer
bufferSize // Buffer size in wide characters
);
return std::wstring(tempBuffer.get());
}
/**
* Write a UTF-8 string to the Windows console in Unicode (UTF-16)
*
* @param utf8String UTF-8 input string
* @param utf8StringSize Number of bytes in UTF-8 string, no NUL terminator assumed
* @return true if all characters were displayed (including zero characters)
*/
bool writeUtf8ToWindowsConsole(const char* utf8String, unsigned int utf8StringSize) {
int bufferSize = MultiByteToWideChar(CP_UTF8, // Code page
0, // Flags
utf8String, // Input string
utf8StringSize, // Input string length
nullptr, // No output buffer
0 // Zero means "compute required size"
);
if (bufferSize == 0) {
return true;
}
std::unique_ptr<wchar_t[]> utf16String(new wchar_t[bufferSize]);
MultiByteToWideChar(CP_UTF8, // Code page
0, // Flags
utf8String, // Input string
utf8StringSize, // Input string length
utf16String.get(), // UTF-16 output buffer
bufferSize // Buffer size in wide characters
);
const wchar_t* utf16Pointer = utf16String.get();
size_t numberOfCharactersToWrite = bufferSize;
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
while (numberOfCharactersToWrite > 0) {
static const DWORD MAXIMUM_CHARACTERS_PER_PASS = 8 * 1024;
DWORD numberOfCharactersThisPass = static_cast<DWORD>(numberOfCharactersToWrite);
if (numberOfCharactersThisPass > MAXIMUM_CHARACTERS_PER_PASS) {
numberOfCharactersThisPass = MAXIMUM_CHARACTERS_PER_PASS;
}
DWORD numberOfCharactersWritten;
BOOL success = WriteConsoleW(consoleHandle,
utf16Pointer,
numberOfCharactersThisPass,
&numberOfCharactersWritten,
nullptr);
if (0 == success) {
DWORD dosError = GetLastError();
static bool errorMessageShown = false;
if (ERROR_GEN_FAILURE == dosError) {
if (!errorMessageShown) {
std::cout << "\n---\nUnicode text could not be correctly displayed.\n"
"Please change your console font to a Unicode font "
"(e.g. Lucida Console).\n---\n"
<< std::endl;
errorMessageShown = true;
}
// we can't display the text properly using a raster font,
// but we can display the bits that will display ...
_write(1, utf8String, utf8StringSize);
}
return false;
}
numberOfCharactersToWrite -= numberOfCharactersWritten;
utf16Pointer += numberOfCharactersWritten;
}
return true;
}
class WindowsCommandLine::Impl {
public:
Impl(int argc, wchar_t** argvW) : _strs(argc), _argv(argc + 1) {
for (int i = 0; i < argc; ++i)
_argv[i] = (_strs[i] = toUtf8String(argvW[i])).data();
}
char** argv() {
return _argv.data();
}
std::vector<std::string> _strs; // utf8 encoded
std::vector<char*> _argv; // [_strs..., nullptr]
};
WindowsCommandLine::WindowsCommandLine(int argc, wchar_t** argvW)
: _impl{std::make_unique<Impl>(argc, argvW)} {}
WindowsCommandLine::~WindowsCommandLine() = default;
char** WindowsCommandLine::argv() const {
return _impl->argv();
}
#endif // #if defined(_WIN32)
// See "Parsing C++ Command-Line Arguments (C++)"
// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
static void quoteForWindowsCommandLine(const std::string& arg, std::ostream& os) {
if (arg.empty()) {
os << "\"\"";
} else if (arg.find_first_of(" \t\"") == std::string::npos) {
os << arg;
} else {
os << '"';
std::string backslashes = "";
for (std::string::const_iterator iter = arg.begin(), end = arg.end(); iter != end; ++iter) {
switch (*iter) {
case '\\':
backslashes.push_back(*iter);
if (iter + 1 == end)
os << backslashes << backslashes;
break;
case '"':
os << backslashes << backslashes << "\\\"";
break;
default:
os << backslashes << *iter;
backslashes.clear();
break;
}
}
os << '"';
}
}
std::string constructUtf8WindowsCommandLine(const std::vector<std::string>& argv) {
if (argv.empty())
return "";
std::ostringstream commandLine;
auto iter = argv.begin();
const auto end = argv.end();
quoteForWindowsCommandLine(*iter, commandLine);
++iter;
for (; iter != end; ++iter) {
commandLine << ' ';
quoteForWindowsCommandLine(*iter, commandLine);
}
return commandLine.str();
}
} // namespace mongo
| 37.909091 | 100 | 0.512535 | [
"vector"
] |
b5c252218fc73ce829079639f81858dfc4a510ea | 3,257 | cpp | C++ | src/SolAR2D3DcorrespondencesFinderOpencv.cpp | ThibaudM/SolARModuleOpenCV | 8898694a429abb4b3a227b2463aef5a0b6aa5c07 | [
"Apache-2.0"
] | 3 | 2019-04-16T16:40:35.000Z | 2021-02-26T10:28:36.000Z | src/SolAR2D3DcorrespondencesFinderOpencv.cpp | ThibaudM/SolARModuleOpenCV | 8898694a429abb4b3a227b2463aef5a0b6aa5c07 | [
"Apache-2.0"
] | 7 | 2018-04-13T14:31:55.000Z | 2021-06-30T14:49:26.000Z | src/SolAR2D3DcorrespondencesFinderOpencv.cpp | ThibaudM/SolARModuleOpenCV | 8898694a429abb4b3a227b2463aef5a0b6aa5c07 | [
"Apache-2.0"
] | 4 | 2019-07-25T08:50:04.000Z | 2021-06-14T15:40:19.000Z | /**
* @copyright Copyright (c) 2017 B-com http://www.b-com.com/
*
* 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 "SolAR2D3DcorrespondencesFinderOpencv.h"
#include "core/Log.h"
namespace xpcf = org::bcom::xpcf;
XPCF_DEFINE_FACTORY_CREATE_INSTANCE(SolAR::MODULES::OPENCV::SolAR2D3DCorrespondencesFinderOpencv)
namespace SolAR {
using namespace datastructure;
using namespace api::storage;
namespace MODULES {
namespace OPENCV {
SolAR2D3DCorrespondencesFinderOpencv::SolAR2D3DCorrespondencesFinderOpencv():ComponentBase(xpcf::toUUID<SolAR2D3DCorrespondencesFinderOpencv>())
{
declareInterface<api::solver::pose::I2D3DCorrespondencesFinder>(this);
declareInjectable<IPointCloudManager>(m_pointCloudManager);
LOG_DEBUG("SolAR2D3DCorrespondencesFinder constructor");
}
FrameworkReturnCode SolAR2D3DCorrespondencesFinderOpencv::find(const SRef<Frame> lastFrame,
const SRef<Frame> currentFrame,
const std::vector<DescriptorMatch> & current_matches,
std::vector<Point3Df> & shared_3dpoint,
std::vector<Point2Df> & shared_2dpoint,
std::vector<std::pair<uint32_t,
SRef<CloudPoint>>> & corres2D3D,
std::vector<DescriptorMatch> & found_matches,
std::vector<DescriptorMatch> & remaining_matches)
{
const std::map<uint32_t, uint32_t> &mapVisibility = lastFrame->getVisibility();
const std::vector<Keypoint> ¤t_kpoints = currentFrame->getKeypoints();
for (int j = 0; j < current_matches.size(); ++j) {
SRef<CloudPoint> point3D;
std::map<unsigned int, unsigned int>::const_iterator it_cp = mapVisibility.find(current_matches[j].getIndexInDescriptorA());
if ((it_cp != mapVisibility.end()) && (m_pointCloudManager->getPoint(it_cp->second, point3D) == FrameworkReturnCode::_SUCCESS)) {
shared_3dpoint.push_back(Point3Df(point3D->getX(), point3D->getY(), point3D->getZ()));
shared_2dpoint.push_back(Point2Df(current_kpoints[current_matches[j].getIndexInDescriptorB()].getX(),
current_kpoints[current_matches[j].getIndexInDescriptorB()].getY()));
found_matches.push_back(current_matches[j]);
corres2D3D.push_back(std::make_pair(current_matches[j].getIndexInDescriptorB(), point3D));
}
else {
remaining_matches.push_back(current_matches[j]);
}
}
return FrameworkReturnCode::_SUCCESS;
}
}
}
}
| 46.528571 | 144 | 0.653055 | [
"vector"
] |
b5d5770ff79101d15b1170d60a3b3abecfea3179 | 4,234 | cpp | C++ | Dots/geometries/Greetings/FTA.cpp | xjorma/HoloGrail | 678db2a5f98261b0d8d6c3cdaffe481a42802845 | [
"MIT"
] | 6 | 2021-04-05T05:57:59.000Z | 2022-02-20T00:14:15.000Z | Dots/geometries/Greetings/FTA.cpp | xjorma/HoloGrail | 678db2a5f98261b0d8d6c3cdaffe481a42802845 | [
"MIT"
] | null | null | null | Dots/geometries/Greetings/FTA.cpp | xjorma/HoloGrail | 678db2a5f98261b0d8d6c3cdaffe481a42802845 | [
"MIT"
] | null | null | null | #include "demopch.h"
#include "./headers/geometries.h"
Geometry FTA = Geometry
(
{
{0.316115826368, -0.0500000007451, -0.0873069763184}, {0.316115826368, 0.0500000007451, -0.0873069763184}, {0.251831442118, -0.0500000007451, 0.044756539166}, {0.251831442118, 0.0500000007451, 0.044756539166}, {0.179438009858, -0.0500000007451, -0.0864792466164}, {0.179438009858, 0.0500000007451, -0.0864792466164}, {0.0769443139434, -0.0500000007451, -0.18310341239}, {0.0769443139434, 0.0500000007451, -0.18310341239},
{0.0758144110441, -0.0500000007451, -0.101988717914}, {0.0758144110441, 0.0500000007451, -0.101988717914}, {0.148403942585, -0.0500000007451, 0.0560992769897}, {0.148403942585, 0.0500000007451, 0.0560992769897}, {0.24375140667, -0.0500000007451, 0.0609946474433}, {0.24375140667, 0.0500000007451, 0.0609946474433}, {0.232773572206, -0.0500000007451, 0.089265525341}, {0.232773572206, 0.0500000007451, 0.089265525341},
{-0.296558618546, -0.0500000007451, 0.0895402431488}, {-0.296558618546, 0.0500000007451, 0.0895402431488}, {-0.424748748541, -0.0500000007451, 0.0905758365989}, {-0.424748748541, 0.0500000007451, 0.0905758365989}, {-0.424685776234, -0.0500000007451, 0.18202842772}, {-0.424685776234, 0.0500000007451, 0.18202842772}, {-0.29805675149, -0.0500000007451, 0.183227285743}, {-0.29805675149, 0.0500000007451, 0.183227285743},
{0.280862897635, -0.0500000007451, 0.182821184397}, {0.280862897635, 0.0500000007451, 0.182821184397}, {0.423978388309, -0.0500000007451, -0.0978576466441}, {0.423978388309, 0.0500000007451, -0.0978576466441}, {0.425131082535, -0.0500000007451, -0.183203667402}, {0.425131082535, 0.0500000007451, -0.183203667402}, {-0.159899353981, -0.0500000007451, -0.147569060326}, {-0.159899353981, 0.0500000007451, -0.147569060326},
{-0.176939859986, -0.0500000007451, -0.116478092968}, {-0.176939859986, 0.0500000007451, -0.116478092968}, {-0.177297711372, -0.0500000007451, 0.0586632341146}, {-0.177297711372, 0.0500000007451, 0.0586632341146}, {-0.0789318829775, -0.0500000007451, 0.058061670512}, {-0.0789318829775, 0.0500000007451, 0.058061670512}, {-0.0757446140051, -0.0500000007451, -0.0871344506741}, {-0.0757446140051, 0.0500000007451, -0.0871344506741},
{-0.0595717392862, -0.0500000007451, -0.0933843404055}, {-0.0595717392862, 0.0500000007451, -0.0933843404055}, {0.046091131866, -0.0500000007451, -0.0958243831992}, {0.046091131866, 0.0500000007451, -0.0958243831992}, {0.0456621386111, -0.0500000007451, -0.181811660528}, {0.0456621386111, 0.0500000007451, -0.181811660528}, {-0.0962288975716, -0.0500000007451, -0.183054104447}, {-0.0962288975716, 0.0500000007451, -0.183054104447},
{-0.424814999104, -0.0500000007451, -0.182247668505}, {-0.424814999104, 0.0500000007451, -0.182247668505}, {-0.42401894927, -0.0500000007451, 0.0573434829712}, {-0.42401894927, 0.0500000007451, 0.0573434829712}, {-0.218841403723, -0.0500000007451, 0.0579422153533}, {-0.218841403723, 0.0500000007451, 0.0579422153533}, {-0.207113593817, -0.0500000007451, 0.0519326478243}, {-0.207113593817, 0.0500000007451, 0.0519326478243},
{-0.209438890219, -0.0500000007451, -0.028389679268}, {-0.209438890219, 0.0500000007451, -0.028389679268}, {-0.325937598944, -0.0500000007451, -0.030520748347}, {-0.325937598944, 0.0500000007451, -0.030520748347}, {-0.327686309814, -0.0500000007451, -0.182658046484}, {-0.327686309814, 0.0500000007451, -0.182658046484}
},
{
{0, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 0}, {5, 1}, {2, 3}, {4, 5}, {0, 1}, {6, 8}, {7, 9}, {8, 10}, {9, 11}, {10, 12}, {11, 13}, {12, 14}, {13, 15}, {14, 16}, {15, 17}, {16, 18}, {17, 19}, {18, 20}, {19, 21}, {20, 22}, {21, 23}, {22, 24}, {23, 25}, {24, 26}, {25, 27}, {26, 28}, {27, 29}, {28, 6},
{29, 7}, {10, 11}, {12, 13}, {14, 15}, {18, 19}, {20, 21}, {24, 25}, {28, 29}, {6, 7}, {30, 32}, {31, 33}, {32, 34}, {33, 35}, {34, 36}, {35, 37}, {36, 38}, {37, 39}, {38, 40}, {39, 41}, {40, 42}, {41, 43}, {42, 44}, {43, 45}, {44, 46}, {45, 47}, {46, 30}, {47, 31}, {34, 35}, {36, 37}, {38, 39}, {42, 43}, {44, 45},
{48, 50}, {49, 51}, {50, 52}, {51, 53}, {52, 54}, {53, 55}, {54, 56}, {55, 57}, {56, 58}, {57, 59}, {58, 60}, {59, 61}, {60, 48}, {61, 49}, {50, 51}, {54, 55}, {56, 57}, {58, 59}, {60, 61}, {48, 49}
}
);
| 192.454545 | 436 | 0.679972 | [
"geometry"
] |
b5e23c5744a81373a6858dee8ed6b29f19929687 | 3,091 | hpp | C++ | include/jg/details/bucket_iterator.hpp | Jiwan/dense_hash_map | 74277fc4813028ae4a9e8d9176788eb8001177a6 | [
"MIT"
] | 15 | 2020-04-11T15:23:09.000Z | 2022-03-15T11:05:19.000Z | include/jg/details/bucket_iterator.hpp | Jiwan/dense_hash_map | 74277fc4813028ae4a9e8d9176788eb8001177a6 | [
"MIT"
] | 2 | 2021-01-08T05:04:54.000Z | 2022-02-13T05:30:51.000Z | include/jg/details/bucket_iterator.hpp | Jiwan/dense_hash_map | 74277fc4813028ae4a9e8d9176788eb8001177a6 | [
"MIT"
] | 5 | 2020-04-11T15:23:15.000Z | 2022-02-25T22:21:00.000Z | #ifndef JG_BUCKET_ITERATOR_HPP
#define JG_BUCKET_ITERATOR_HPP
#include "node.hpp"
#include <iterator>
#include <vector>
namespace jg::details
{
template <class Key, class T, class Container, bool isConst, bool projectToConstKey>
class bucket_iterator
{
using nodes_container_type = std::conditional_t<isConst, const Container, Container>;
using node_index_type = node_index_t<Key, T>;
using projected_type = std::pair<std::conditional_t<projectToConstKey, const Key, Key>, T>;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = std::conditional_t<isConst, const projected_type, projected_type>;
using difference_type = std::ptrdiff_t;
using reference = value_type&;
using pointer = value_type*;
constexpr bucket_iterator() = default;
constexpr explicit bucket_iterator(nodes_container_type& nodes_container)
: nodes_container(&nodes_container)
{}
constexpr bucket_iterator(node_index_type index, nodes_container_type& nodes_container)
: nodes_container(&nodes_container), current_node_index_(index)
{}
constexpr auto operator*() const noexcept -> reference
{
if constexpr (projectToConstKey)
{
return (*nodes_container)[current_node_index_].pair.const_key_pair();
}
else
{
return (*nodes_container)[current_node_index_].pair.pair();
}
}
constexpr auto operator++() noexcept -> bucket_iterator&
{
current_node_index_ = (*nodes_container)[current_node_index_].next;
return *this;
}
constexpr auto operator++(int) noexcept -> bucket_iterator
{
auto old = (*this);
++(*this);
return old;
}
constexpr auto operator-> () const noexcept -> pointer
{
if constexpr (projectToConstKey)
{
return &(*nodes_container)[current_node_index_].pair.const_key_pair();
}
else
{
return &(*nodes_container)[current_node_index_].pair.pair();
}
}
constexpr auto current_node_index() const -> node_index_type { return current_node_index_; }
private:
nodes_container_type* nodes_container;
node_index_type current_node_index_ = node_end_index<Key, T>;
};
template <class Key, class T, class Container, bool isConst, bool projectToConstKey, bool isConst2>
constexpr auto operator==(
const bucket_iterator<Key, T, Container, isConst, projectToConstKey>& lhs,
const bucket_iterator<Key, T, Container, isConst2, projectToConstKey>& rhs) noexcept -> bool
{
return lhs.current_node_index() == rhs.current_node_index();
}
template <class Key, class T, class Container, bool isConst, bool projectToConstKey, bool isConst2>
constexpr auto operator!=(
const bucket_iterator<Key, T, Container, isConst, projectToConstKey>& lhs,
const bucket_iterator<Key, T, Container, isConst2, projectToConstKey>& rhs) noexcept -> bool
{
return lhs.current_node_index() != rhs.current_node_index();
}
} // namespace jg::details
#endif // JG_BUCKET_ITERATOR_HPP
| 31.540816 | 99 | 0.700097 | [
"vector"
] |
b5e498b88f3f762ea9f962b862b35e05810c84c2 | 12,850 | cpp | C++ | symbolics/test/matrix.cpp | brutzl/pymbs | fb7c91435f56b5c4d460f82f081d5d1960fea886 | [
"MIT"
] | null | null | null | symbolics/test/matrix.cpp | brutzl/pymbs | fb7c91435f56b5c4d460f82f081d5d1960fea886 | [
"MIT"
] | null | null | null | symbolics/test/matrix.cpp | brutzl/pymbs | fb7c91435f56b5c4d460f82f081d5d1960fea886 | [
"MIT"
] | null | null | null | /*
This file is part of PyMbs.
PyMbs is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
PyMbs 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 PyMbs.
If not, see <http://www.gnu.org/licenses/>.
Copyright 2011, 2012 Carsten Knoll, Christian Schubert,
Jens Frenkel, Sebastian Voigt
*/
#include <iostream>
#include "Symbolics.h"
using namespace Symbolics;
int main( int argc, char *argv[])
{
BasicPtr as(new Symbol("a"));
BasicPtr bs(new Symbol("b"));
BasicPtr cs(new Symbol("c"));
BasicPtr ds(new Symbol("d"));
BasicPtr es(new Symbol("e"));
BasicPtr fs(new Symbol("f"));
BasicPtr gs(new Symbol("g"));
Shape s;
Matrix c( s );
c.set(0,as);
Matrix v( Shape(3) );
Matrix m( Shape(2,3) );
try {
#pragma region Skalar
// Skalar anlegen
if (c.getShape() != Shape(0,1,1)) return -2;
if (c.getType() != Type_Matrix) return -3;
if (c(0) != as) return -4;
#pragma endregion
} catch (IndexError) { return -1001; };
try {
#pragma region Vektor
// int-Vektor anlegen
v = as,bs,cs;
if (v.getShape() != Shape(1,3,1)) return -10;
if (v.getType() != Type_Matrix) return -11;
if (v(0) != as) return -12;
if (v(1) != bs) return -13;
if (v(2) != cs) return -14;
try {
v(-1);
return -16;
} catch (IndexError) {}
catch (...) { return - 17; };
try {
v(3);
return -18;
} catch (IndexError) {}
catch (...) { return - 19; };
#pragma endregion
} catch (IndexError) { return -1002; };
try {
#pragma region Matrix
// int-Matrix anlegen
m = as,bs,cs,
ds,es,fs;
if (m.getShape() != Shape(2,2,3)) return -32;
if (m.getType() != Type_Matrix) return -33;
if (m(0,0) != as) return -34;
if (m(0,1) != bs) return -35;
if (m(0,2) != cs) return -36;
if (m(1,0) != ds) return -37;
if (m(1,1) != es) return -38;
if (m(1,2) != fs) return -39;
try {
m(-1,-1);
return -40;
} catch (IndexError) {}
catch (...) { return -41; };
try {
m(-1,0);
return -42;
} catch (IndexError) {}
catch (...) { return -43; };
try {
m(0,-1);
return -44;
} catch (IndexError) {}
catch (...) { return -45; };
try {
m(2,2);
return -46;
} catch (IndexError) {}
catch (...) { return -47; };
try {
m(1,3);
return -48;
} catch (IndexError) {}
catch (...) { return -49; };
try {
m(2,3);
return -50;
} catch (IndexError) {}
catch (...) { return -51; };
#pragma endregion
} catch (IndexError) { return -1003; };
try {
#pragma region Rechnen mit Konstanten (Skalar)
// Skalar
Matrix cplus( c + c );
if (!cplus.is_Scalar()) return -100;
if (cplus(0) != c(0) + c(0)) return -101;
Matrix cminus( c - c );
if (!cminus.is_Scalar()) return -102;
if (cminus(0) != c(0) - c(0)) return -103;
Matrix cmul( c * c );
if (!cmul.is_Scalar()) return -108;
if (cmul(0) != c(0)*c(0)) return -109;
#pragma endregion
} catch (IndexError) { return -1004; };
try {
#pragma region Vektor/Skalar
// Vektor +- Skalar
Matrix cplusvs( v + c );
if (cplusvs.getShape() != v.getShape()) return -110;
if (cplusvs(0) != v(0) + c(0)) return -111;
if (cplusvs(1) != v(1) + c(0)) return -112;
if (cplusvs(2) != v(2) + c(0)) return -113;
Matrix cminusvs( v - c );
if (cminusvs.getShape() != v.getShape()) return -115;
if (cminusvs(0) != v(0) - c(0)) return -116;
if (cminusvs(1) != v(1) - c(0)) return -117;
if (cminusvs(2) != v(2) - c(0)) return -118;
// Skalar +- Vektor
Matrix cplussv( c + v );
if (cplussv.getShape() != v.getShape()) return -120;
if (cplussv(0) != v(0) + c(0)) return -121;
if (cplussv(1) != v(1) + c(0)) return -122;
if (cplussv(2) != v(2) + c(0)) return -123;
Matrix cminussv( c - v );
if (cminussv.getShape() != v.getShape()) return -125;
if (cminussv(0) != c(0) - v(0)) return -126;
if (cminussv(1) != c(0) - v(1)) return -127;
if (cminussv(2) != c(0) - v(2)) return -128;
// Vektor +- Vektor
Matrix cplusvv( v + v );
if (cplusvv.getShape() != v.getShape()) return -130;
if (cplusvv(0) != v(0) + v(0)) return -131;
if (cplusvv(1) != v(1) + v(1)) return -132;
if (cplusvv(2) != v(2) + v(2)) return -133;
Matrix cminusvv( v - v );
if (cminusvv.getShape() != v.getShape()) return -135;
if (cminusvv(0) != v(0) - v(0)) return -136;
if (cminusvv(1) != v(1) - v(1)) return -137;
if (cminusvv(2) != v(2) - v(2)) return -138;
// Skalar * Vektor, Vektor*Skalar
Matrix cmulsv( c * v );
if (cmulsv.getShape() != v.getShape()) return -140;
std::cout << cmulsv(1)->toString() << std::endl;
std::cout << (v(1) * c(0))->toString() << std::endl;
if (cmulsv(0) != v(0) * c(0)) return -141;
if (cmulsv(1) != v(1) * c(0)) return -142;
if (cmulsv(2) != v(2) * c(0)) return -143;
Matrix cmulvs( v * c );
if (cmulvs.getShape() != v.getShape()) return -145;
if (cmulvs(0) != v(0) * c(0)) return -146;
if (cmulvs(1) != v(1) * c(0)) return -147;
if (cmulvs(2) != v(2) * c(0)) return -148;
// Vektor*Vektor
Matrix cmulvv( v.transpose() * v );
if (cmulvv.getShape() != Shape() ) return -150;
if (cmulvv(0) != as*as + bs*bs + cs*cs) return -151;
#pragma endregion
} catch (IndexError) { return -1005; };
try {
#pragma region Matrix/Skalar
// Skalar +- Matrix
Matrix cplussm( c + m );
if (cplussm.getShape() != m.getShape()) return -160;
if (cplussm(0,0) != m(0,0) + c(0)) return -161;
if (cplussm(0,1) != m(0,1) + c(0)) return -162;
if (cplussm(0,2) != m(0,2) + c(0)) return -163;
if (cplussm(1,0) != m(1,0) + c(0)) return -164;
if (cplussm(1,1) != m(1,1) + c(0)) return -165;
if (cplussm(1,2) != m(1,2) + c(0)) return -166;
Matrix cminussm( c - m );
if (cminussm.getShape() != m.getShape()) return -167;
if (cminussm(0,0) != c(0) - m(0,0)) return -168;
if (cminussm(0,1) != c(0) - m(0,1)) return -169;
if (cminussm(0,2) != c(0) - m(0,2)) return -170;
if (cminussm(1,0) != c(0) - m(1,0)) return -171;
if (cminussm(1,1) != c(0) - m(1,1)) return -172;
if (cminussm(1,2) != c(0) - m(1,2)) return -173;
// Matrix +- Skalar
Matrix cplusms( m + c );
if (cplusms.getShape() != m.getShape()) return -180;
if (cplusms(0,0) != m(0,0) + c(0)) return -181;
if (cplusms(0,1) != m(0,1) + c(0)) return -182;
if (cplusms(0,2) != m(0,2) + c(0)) return -183;
if (cplusms(1,0) != m(1,0) + c(0)) return -184;
if (cplusms(1,1) != m(1,1) + c(0)) return -185;
if (cplusms(1,2) != m(1,2) + c(0)) return -186;
Matrix cminusms( m - c );
if (cminusms.getShape() != m.getShape()) return -187;
if (cminusms(0,0) != m(0,0) - c(0)) return -188;
if (cminusms(0,1) != m(0,1) - c(0)) return -189;
if (cminusms(0,2) != m(0,2) - c(0)) return -190;
if (cminusms(1,0) != m(1,0) - c(0)) return -191;
if (cminusms(1,1) != m(1,1) - c(0)) return -192;
if (cminusms(1,2) != m(1,2) - c(0)) return -193;
// Matrix * Skalar, Skalar * Matrix
Matrix cmulsm( c * m );
if (cmulsm.getShape() != m.getShape()) return -200;
if (cmulsm(0,0) != m(0,0) * c(0)) return -201;
if (cmulsm(0,1) != m(0,1) * c(0)) return -202;
if (cmulsm(0,2) != m(0,2) * c(0)) return -203;
if (cmulsm(1,0) != m(1,0) * c(0)) return -204;
if (cmulsm(1,1) != m(1,1) * c(0)) return -205;
if (cmulsm(1,2) != m(1,2) * c(0)) return -206;
Matrix cmulms( m * c );
if (cmulms.getShape() != m.getShape()) return -207;
if (cmulms(0,0) != m(0,0) * c(0)) return -208;
if (cmulms(0,1) != m(0,1) * c(0)) return -209;
if (cmulms(0,2) != m(0,2) * c(0)) return -210;
if (cmulms(1,0) != m(1,0) * c(0)) return -211;
if (cmulms(1,1) != m(1,1) * c(0)) return -212;
if (cmulms(1,2) != m(1,2) * c(0)) return -213;
#pragma endregion
} catch (IndexError) { return -1006; };
try {
#pragma region Matrix/Vektor
// Matrix * Vektor, Vektor * Matrix
Matrix cmulmv( m * v );
if (cmulmv.getShape() != Shape(1,2,1)) return -220;
if (cmulmv(0) != (((m(0,0)*v(0)) + m(0,1)*v(1)) + m(0,2)*v(2)) ) return -221;
if (cmulmv(1) != (((m(1,0)*v(0)) + m(1,1)*v(1)) + m(1,2)*v(2)) ) return -222;
try {
m.transpose()*v;
return -223;
} catch (ShapeError) {}
catch (...) { return -224; };
Matrix cmulvm( v.transpose() * m.transpose() );
if (cmulvm.getShape() != Shape(1,1,2)) return -230;
if (cmulvm(0) != (((m(0,0)*v(0)) + m(0,1)*v(1)) + m(0,2)*v(2)) ) return -231;
if (cmulvm(1) != (((v(0)*m(1,0)) + v(1)*m(1,1)) + v(2)*m(1,2)) ) return -232;
try {
v * m;
return -233;
} catch (ShapeError) {}
catch (...) { return -234; };
#pragma endregion
} catch (IndexError) { return -1007; };
try {
#pragma region Matrix/Matrix
// Matrix*Matrix
Matrix cmulmm( m * m.transpose() );
if (cmulmm.getShape() != Shape(2,2,2)) return -240;
if (cmulmm(0,0) != (((m(0,0)*m(0,0)) + m(0,1)*m(0,1)) + m(0,2)*m(0,2)) ) return -241;
if (cmulmm(0,1) != (((m(0,0)*m(1,0)) + m(0,1)*m(1,1)) + m(0,2)*m(1,2)) ) return -242;
if (cmulmm(1,0) != (((m(1,0)*m(0,0)) + m(1,1)*m(0,1)) + m(1,2)*m(0,2)) ) return -243;
if (cmulmm(1,1) != (((m(1,0)*m(1,0)) + m(1,1)*m(1,1)) + m(1,2)*m(1,2)) ) return -244;
try {
m*m;
return -245;
} catch (ShapeError) {}
catch (...) { return -246; };
#pragma endregion
} catch (IndexError) { return -1008; };
#pragma region Vergleich
// Scalar == Scalar, Scalar < Scalar
BasicPtrVec vecas;
vecas.push_back(as);
Matrix c1(vecas,Shape());
BasicPtrVec vecbs;
vecbs.push_back(bs);
Matrix c2(vecbs,Shape());
if (c != c) return -1100;
if (c != c1) return -1101;
if (c < c1) return -1102;
if (c2 < c1) return -1103;
// Vector == Vector, Vector < Vector
Matrix cv1( Shape(3) );
cv1 = as,bs,cs;
Matrix cv2( Shape(2) );
cv2 = as,bs;
Matrix cv3( Shape(3) );
cv3 = as,bs,ds;
if (v != v) return -1108;
if (v != cv1) return -1109;
if (v < cv1) return -1110;
if (cv3 < v) return -1111;
if (cv1 < cv2) return -1112;
// Vector == Scalar, Vector < Scalar
if (v == c) return -1122;
if (v < c) return -1123;
#pragma endregion
#pragma region TypeCast
Int *cintp = new Int(1);
BasicPtr cint(cintp);
Real *cdblp = new Real(1);
BasicPtr cdbl(cdblp);
BasicPtr cint2 = new Int(2);
BasicPtr cdbl2 = new Real(2.0);
BasicPtr cint3 = new Int(3);
BasicPtr cdbl3 = new Real(3.0);
BasicPtr cint4 = new Int(4);
BasicPtr cdbl4 = new Real(4.0);
BasicPtr cint5 = new Int(5);
BasicPtr cdbl5 = new Real(5.0);
BasicPtr cint6 = new Int(6);
BasicPtr cdbl6 = new Real(6.0);
Matrix cvint( Shape(3) );
cvint = 1,2,3;
Matrix cvdbl( Shape(3) );
cvdbl = 1.0,2.0,3.0;
Matrix cmint( Shape(2,3) );
cmint = 1,2,3,
4,5,6;
Matrix cmdbl( Shape(2,3) );
cmdbl = 1.0,2.0,3.0,
4.0,5.0,6.0;
BasicPtrVec cintvec;
cintvec.push_back(cint);
Matrix cintmatrix(cintvec, Shape());
Matrix mint(cintvec, Shape());
if (cintmatrix != mint) return -1200;
BasicPtrVec cdblvec;
cdblvec.push_back(cdbl);
Matrix cdblmatrix(cdblvec, Shape());
Matrix mdbl(cdblvec, Shape());
if (cdblmatrix != mdbl) return -1201;
Matrix cvintmatrix(cvint);
Matrix cvintmat( Shape(3));
cvintmat = cint,cint2,cint3;
if (cvintmatrix != cvintmat) return -1203;
Matrix cvdblmatrix(cvdbl);
Matrix cvdblmat( Shape(3));
cvdblmat = cdbl,cdbl2,cdbl3;
if (cvdblmatrix != cvdblmat) return -1204;
Matrix cmintmatrix(cmint);
Matrix cmintmat( Shape(2,3));
cmintmat = cint,cint2,cint3,
cint4,cint5,cint6;
if (cmintmatrix != cmintmat) return -1205;
Matrix cmdblmatrix(cmdbl);
Matrix cmdblmat( Shape(2,3));
cmdblmat = cdbl,cdbl2,cdbl3,
cdbl4,cdbl5,cdbl6;
if (cmdblmatrix != cmdblmat) return -1206;
#pragma endregion
#pragma region Derivative
BasicPtr dercmdblmatrix = cmdblmatrix.der();
if (!Util::is_Zero(dercmdblmatrix)) return -1300;
#pragma endregion
return 0;
} | 30.963855 | 89 | 0.539767 | [
"shape",
"vector"
] |
b5e86b9a833d110af323b404876f0425a65fa194 | 11,744 | cpp | C++ | src/CoreInfo.cpp | leiradel/CheevosTool | a7d0145c7617caf63d42b134a831707f10c1d27b | [
"MIT"
] | null | null | null | src/CoreInfo.cpp | leiradel/CheevosTool | a7d0145c7617caf63d42b134a831707f10c1d27b | [
"MIT"
] | null | null | null | src/CoreInfo.cpp | leiradel/CheevosTool | a7d0145c7617caf63d42b134a831707f10c1d27b | [
"MIT"
] | null | null | null | #include "CoreInfo.h"
#include <imgui.h>
#include <stdio.h>
static void table(int columns, ...)
{
ImGui::Columns(columns, NULL, true);
va_list args;
va_start(args, columns);
for (;;)
{
const char* name = va_arg(args, const char*);
if (name == NULL)
{
break;
}
ImGui::Separator();
ImGui::Text("%s", name);
ImGui::NextColumn();
for (int col = 1; col < columns; col++)
{
switch (va_arg(args, int))
{
case 's': ImGui::Text("%s", va_arg(args, const char*)); break;
case 'd': ImGui::Text("%d", va_arg(args, int)); break;
case 'u': ImGui::Text("%u", va_arg(args, unsigned)); break;
case 'f': ImGui::Text("%f", va_arg(args, double)); break;
case 'b': ImGui::Text("%s", va_arg(args, int) ? "true" : "false"); break;
}
ImGui::NextColumn();
}
}
va_end(args);
ImGui::Columns(1);
ImGui::Separator();
}
void drawCoreInfo(libretro::CoreManager const* const core)
{
if (ImGui::CollapsingHeader("Basic Information"))
{
static const char* pixel_formats[] =
{
"0RGB1555", "XRGB8888", "RGB565"
};
enum retro_pixel_format ndx = core->getPixelFormat();
const char* pixel_format = "Unknown";
if (ndx != RETRO_PIXEL_FORMAT_UNKNOWN)
{
pixel_format = pixel_formats[ndx];
}
table(
2,
"Api Version", 'u', core->getApiVersion(),
"Region", 's', core->getRegion() == RETRO_REGION_NTSC ? "NTSC" : "PAL",
"Rotation", 'u', core->getRotation() * 90,
"Performance level", 'u', core->getPerformanceLevel(),
"Pixel Format", 's', pixel_format,
"Supports no Game", 'b', core->getSupportsNoGame(),
"Supports Achievements", 'b', core->getSupportAchievements(),
"Save RAM Size", 'u', core->getMemorySize(RETRO_MEMORY_SAVE_RAM),
"RTC Size", 'u', core->getMemorySize(RETRO_MEMORY_RTC),
"System RAM Size", 'u', core->getMemorySize(RETRO_MEMORY_SYSTEM_RAM),
"Video RAM Size", 'u', core->getMemorySize(RETRO_MEMORY_VIDEO_RAM),
NULL
);
}
if (ImGui::CollapsingHeader("retro_system_info"))
{
libretro::SystemInfo const& info = core->getSystemInfo();
table(
2,
"library_name", 's', info.libraryName,
"library_version", 's', info.libraryVersion,
"valid_extensions", 's', info.validExtensions,
"need_fullpath", 'b', info.needFullpath,
"block_extract", 'b', info.blockExtract,
NULL
);
}
if (ImGui::CollapsingHeader("retro_system_av_info"))
{
libretro::SystemAVInfo const& info = core->getSystemAVInfo();
table(
2,
"base_width", 'u', info.geometry.baseWidth,
"base_height", 'u', info.geometry.baseHeight,
"max_width", 'u', info.geometry.maxWidth,
"max_height", 'u', info.geometry.maxHeight,
"aspect_ratio", 'f', info.geometry.aspectRatio,
"fps", 'f', info.timing.fps,
"sample_rate", 'f', info.timing.sampleRate,
NULL
);
}
if (ImGui::CollapsingHeader("retro_input_descriptor"))
{
std::vector<libretro::InputDescriptor> const& desc = core->getInputDescriptors();
ImVec2 min = ImGui::GetWindowContentRegionMin();
ImVec2 max = ImGui::GetWindowContentRegionMax();
max.x -= min.x;
max.y = ImGui::GetItemsLineHeightWithSpacing();
ImGui::BeginChild("##empty", max);
ImGui::Columns(5, NULL, true);
ImGui::Separator();
ImGui::Text("port");
ImGui::NextColumn();
ImGui::Text("device");
ImGui::NextColumn();
ImGui::Text("index");
ImGui::NextColumn();
ImGui::Text("id");
ImGui::NextColumn();
ImGui::Text("description");
ImGui::NextColumn();
ImGui::Columns( 1 );
ImGui::Separator();
ImGui::EndChild();
max.y = ImGui::GetItemsLineHeightWithSpacing() * (desc.size() < 16 ? desc.size() : 16);
ImGui::BeginChild("retro_input_descriptor", max);
ImGui::Columns(5, NULL, true);
for (auto const& element : desc)
{
static const char* device_names[] =
{
"None", "Joypad", "Mouse", "Keyboard", "Lightgun", "Analog", "Pointer"
};
static const char* button_names[] =
{
"B", "Y", "Select", "Start", "Up", "Down", "Left",
"Right", "A", "X", "L", "R", "L2", "R2", "L3", "R3"
};
ImGui::Separator();
ImGui::Text("%u", element.port);
ImGui::NextColumn();
ImGui::Text("(%u) %s", element.device, device_names[element.device]);
ImGui::NextColumn();
ImGui::Text("%u", element.index);
ImGui::NextColumn();
ImGui::Text("(%2u) %s", element.id, button_names[element.id]);
ImGui::NextColumn();
ImGui::Text("%s", element.description.c_str());
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::EndChild();
}
if (ImGui::CollapsingHeader("retro_controller_info"))
{
std::vector<libretro::ControllerInfo> const& info = core->getControllerInfo();
ImGui::Columns(3, NULL, true);
ImGui::Separator();
ImGui::Text("port");
ImGui::NextColumn();
ImGui::Text("desc");
ImGui::NextColumn();
ImGui::Text("id");
ImGui::NextColumn();
unsigned port = 0;
for (auto const& element : info)
{
for (auto const& element2 : element.types)
{
static const char* device_names[] =
{
"None", "Joypad", "Mouse", "Keyboard", "Lightgun", "Analog", "Pointer"
};
ImGui::Separator();
ImGui::Text("%u", port);
ImGui::NextColumn();
ImGui::Text("%s", element2.desc.c_str());
ImGui::NextColumn();
ImGui::Text("(0x%04X) %s", element2.id, device_names[element2.id & RETRO_DEVICE_MASK]);
ImGui::NextColumn();
}
port++;
}
ImGui::Columns(1);
ImGui::Separator();
}
if (ImGui::CollapsingHeader("retro_variable"))
{
std::vector<libretro::Variable> const& vars = core->getVariables();
ImGui::Columns(2, NULL, true);
ImGui::Separator();
ImGui::Text("key");
ImGui::NextColumn();
ImGui::Text("value");
ImGui::NextColumn();
for (auto const& element : vars)
{
ImGui::Separator();
ImGui::Text("%s", element.key.c_str());
ImGui::NextColumn();
ImGui::Text("%s", element.value.c_str());
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
}
if (ImGui::CollapsingHeader("retro_subsystem_info"))
{
std::vector<libretro::SubsystemInfo> const& info = core->getSubsystemInfo();
for (auto const& element : info)
{
ImGui::Columns(3, NULL, true);
ImGui::Separator();
ImGui::Text("desc");
ImGui::NextColumn();
ImGui::Text("ident");
ImGui::NextColumn();
ImGui::Text("id");
ImGui::NextColumn();
ImGui::Separator();
ImGui::Text("%s", element.desc.c_str());
ImGui::NextColumn();
ImGui::Text("%s", element.ident.c_str());
ImGui::NextColumn();
ImGui::Text("%u", element.id);
ImGui::NextColumn();
ImGui::Columns(1);
ImGui::Separator();
unsigned index2 = 0;
for (auto const& element2 : element.roms)
{
ImGui::Indent();
char title[64];
snprintf(title, sizeof(title), "retro_subsystem_rom_info[%u]", index2++);
if (ImGui::CollapsingHeader(title))
{
ImGui::Columns(5, NULL, true);
ImGui::Separator();
ImGui::Text("desc" );
ImGui::NextColumn();
ImGui::Text("valid_extensions");
ImGui::NextColumn();
ImGui::Text("need_fullpath");
ImGui::NextColumn();
ImGui::Text("block_extract");
ImGui::NextColumn();
ImGui::Text("required");
ImGui::NextColumn();
ImGui::Separator();
ImGui::Text("%s", element2.desc.c_str());
ImGui::NextColumn();
ImGui::Text("%s", element2.validExtensions.c_str());
ImGui::NextColumn();
ImGui::Text("%s", element2.needFullpath ? "true" : "false");
ImGui::NextColumn();
ImGui::Text("%s", element2.blockExtract ? "true" : "false");
ImGui::NextColumn();
ImGui::Text("%s", element2.required ? "true" : "false");
ImGui::NextColumn();
ImGui::Columns(1);
ImGui::Separator();
ImGui::Indent();
unsigned index3 = 0;
for (auto const& element3 : element2.memory)
{
char title[64];
snprintf(title, sizeof(title), "retro_subsystem_memory_info[%u]", index3++);
ImGui::Columns(3, NULL, true);
ImGui::Separator();
ImGui::Text("");
ImGui::NextColumn();
ImGui::Text("extension");
ImGui::NextColumn();
ImGui::Text("type");
ImGui::NextColumn();
ImGui::Separator();
ImGui::Text("%s", title);
ImGui::NextColumn();
ImGui::Text("%s", element3.extension.c_str());
ImGui::NextColumn();
ImGui::Text("0x%08X", element3.type);
ImGui::NextColumn();
}
ImGui::Unindent();
}
ImGui::Unindent();
}
}
}
if (ImGui::CollapsingHeader("retro_memory_map"))
{
std::vector<libretro::MemoryDescriptor> const& mmap = core->getMemoryMap();
ImGui::Columns(8, NULL, true);
ImGui::Separator();
ImGui::Text("flags");
ImGui::NextColumn();
ImGui::Text("ptr");
ImGui::NextColumn();
ImGui::Text("offset");
ImGui::NextColumn();
ImGui::Text("start");
ImGui::NextColumn();
ImGui::Text("select");
ImGui::NextColumn();
ImGui::Text("disconnect");
ImGui::NextColumn();
ImGui::Text("len");
ImGui::NextColumn();
ImGui::Text("addrspace");
ImGui::NextColumn();
for (auto const& element : mmap)
{
char flags[7];
flags[0] = 'M';
if ((element.flags & RETRO_MEMDESC_MINSIZE_8) == RETRO_MEMDESC_MINSIZE_8)
{
flags[1] = '8';
}
else if ((element.flags & RETRO_MEMDESC_MINSIZE_4) == RETRO_MEMDESC_MINSIZE_4)
{
flags[1] = '4';
}
else if ((element.flags & RETRO_MEMDESC_MINSIZE_2) == RETRO_MEMDESC_MINSIZE_2)
{
flags[1] = '2';
}
else
{
flags[1] = '1';
}
flags[2] = 'A';
if ((element.flags & RETRO_MEMDESC_ALIGN_8) == RETRO_MEMDESC_ALIGN_8)
{
flags[3] = '8';
}
else if ((element.flags & RETRO_MEMDESC_ALIGN_4) == RETRO_MEMDESC_ALIGN_4)
{
flags[3] = '4';
}
else if ((element.flags & RETRO_MEMDESC_ALIGN_2) == RETRO_MEMDESC_ALIGN_2)
{
flags[3] = '2';
}
else
{
flags[3] = '1';
}
flags[4] = element.flags & RETRO_MEMDESC_BIGENDIAN ? 'B' : 'b';
flags[5] = element.flags & RETRO_MEMDESC_CONST ? 'C' : 'c';
flags[6] = 0;
ImGui::Separator();
ImGui::Text("%s", flags);
ImGui::NextColumn();
ImGui::Text("%p", element.ptr);
ImGui::NextColumn();
ImGui::Text("0x%08X", (unsigned)element.offset);
ImGui::NextColumn();
ImGui::Text("0x%08X", (unsigned)element.start);
ImGui::NextColumn();
ImGui::Text("0x%08X", (unsigned)element.select);
ImGui::NextColumn();
ImGui::Text("0x%08X", (unsigned)element.disconnect);
ImGui::NextColumn();
ImGui::Text("0x%08X", (unsigned)element.len);
ImGui::NextColumn();
ImGui::Text("%s", element.addrspace.c_str());
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
}
}
| 27.122402 | 95 | 0.555092 | [
"geometry",
"vector"
] |
b5ebbd37bc4df7680a200fcf6886d992e2b0c0cb | 847 | cpp | C++ | SOLVER/src/core/boundary/solid_fluid/SolidFluidCoupling1D.cpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | SOLVER/src/core/boundary/solid_fluid/SolidFluidCoupling1D.cpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | SOLVER/src/core/boundary/solid_fluid/SolidFluidCoupling1D.cpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | //
// SolidFluidCoupling1D.cpp
// AxiSEM3D
//
// Created by Kuangdai Leng on 1/30/19.
// Copyright © 2019 Kuangdai Leng. All rights reserved.
//
// solid-fluid boundary condition in 1D
#include "SolidFluidCoupling1D.hpp"
#include "PointWindow.hpp"
// constructor
SolidFluidCoupling1D::
SolidFluidCoupling1D(const std::shared_ptr<PointWindow> &spw,
const std::shared_ptr<PointWindow> &fpw,
double ns_unassmb, double nz_unassmb,
double ns_assmb, double nz_assmb,
double massFluid):
SolidFluidCoupling(spw, fpw),
mNormalS_UnassembledMPI(ns_unassmb),
mNormalZ_UnassembledMPI(nz_unassmb),
mNormalS_AssembledMPI_InvMassFluid(ns_assmb / massFluid),
mNormalZ_AssembledMPI_InvMassFluid(nz_assmb / massFluid) {
checkCompatibility(mSolidPointWindow->getNr());
}
| 30.25 | 61 | 0.714286 | [
"solid"
] |
b5f432399351e3e105f1cd24bdb36654daf47507 | 420 | cpp | C++ | array/961_N-repeated_element_in_size_2N_array.cpp | rspezialetti/leetcode | 4614ffe2a4923aae02f93096b6200239e6f201c1 | [
"MIT"
] | 1 | 2019-08-21T21:25:34.000Z | 2019-08-21T21:25:34.000Z | array/961_N-repeated_element_in_size_2N_array.cpp | rspezialetti/leetcode | 4614ffe2a4923aae02f93096b6200239e6f201c1 | [
"MIT"
] | null | null | null | array/961_N-repeated_element_in_size_2N_array.cpp | rspezialetti/leetcode | 4614ffe2a4923aae02f93096b6200239e6f201c1 | [
"MIT"
] | null | null | null | class Solution {
public:
int repeatedNTimes(vector<int>& A) {
map<int, int> repetitions;
int val = 0;
for(size_t i = 0; i < A.size(); ++i)
{
repetitions[A[i]]++;
if(repetitions[A[i]] == A.size() * 0.5)
{
val = A[i];
break;
}
}
return val;
}
};
| 19.090909 | 51 | 0.345238 | [
"vector"
] |
b5f934671ab00c60dc8b305843460caa12c8f398 | 626 | cpp | C++ | acmicpc/17218.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/17218.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/17218.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
#include <vector>
using namespace std;
#define MAX 41
int dp[MAX][MAX];
int main()
{
vector<char> ans;
string a, b;
cin >> a >> b;
for (int i=1; i<=a.length(); ++i) {
for (int j=1; j<=b.length(); ++j) {
if (a[i-1] == b[j-1])
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
int i = a.length();
int j = b.length();
while (i && j) {
if (dp[i][j] == dp[i-1][j]) {
i--;
} else if (dp[i][j] == dp[i][j-1]) {
j--;
} else {
ans.push_back(a[i-1]);
i--;
j--;
}
}
for (int i=ans.size()-1; i>=0; i--)
cout << ans[i];
return 0;
}
| 15.268293 | 43 | 0.455272 | [
"vector"
] |
bd00c1a4f80cb93322bb3be8cfe97a382a5dceef | 7,606 | cpp | C++ | Immortal/Scene/Scene.cpp | DaShi-Git/Immortal | e3345b4ff2a2b9d215c682db2b4530e24cc3b203 | [
"Apache-2.0"
] | 1 | 2022-01-07T09:52:18.000Z | 2022-01-07T09:52:18.000Z | Immortal/Scene/Scene.cpp | DaShi-Git/Immortal | e3345b4ff2a2b9d215c682db2b4530e24cc3b203 | [
"Apache-2.0"
] | null | null | null | Immortal/Scene/Scene.cpp | DaShi-Git/Immortal | e3345b4ff2a2b9d215c682db2b4530e24cc3b203 | [
"Apache-2.0"
] | null | null | null | #include "impch.h"
#include "Scene.h"
#include "Framework/Application.h"
#include "Render/Render.h"
#include "Render/Render2D.h"
#include "Object.h"
#include "Component.h"
#include "GameObject.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
namespace Immortal
{
struct TransformUniformBuffer
{
Matrix4 viewProjectionMatrix;
Matrix4 skyProjectionMatrix;
Matrix4 sceneRotationMatrix;
};
struct ShadingUniformBuffer
{
struct {
Vector4 direction;
Vector4 radiance;
} lights[3];
Vector4 eyePosition;
};
Scene::Scene(const std::string &debugName, bool isEditorScene) :
debugName{ debugName }
{
entity = registry.create();
registry.emplace<TransformComponent>(entity);
meshes.skybox = std::make_shared<Mesh>("assets/meshes/skybox.obj");
// textures.skybox.reset(Render::Create<TextureCube>("assets/textures/environment.hdr"));
uniforms.transform.reset(Render::Create<Buffer>(sizeof(TransformUniformBuffer), 0));
uniforms.shading.reset(Render::Create<Buffer>(sizeof(ShadingUniformBuffer), 1));
renderTarget.reset(Render::CreateRenderTarget({
Resolutions::FHD.Width, Resolutions::FHD.Height,
{
{ Format::RGBA8 },
{ Format::Depth }
}
}));
renderTarget->Set(Color{ 0.10980392f, 0.10980392f, 0.10980392f, 1 });
pipelines.tonemap = nullptr;
}
Scene::~Scene()
{
registry.clear();
}
void Scene::OnUpdate()
{
}
void Scene::OnEvent()
{
}
void Scene::OnRenderRuntime()
{
// Update Script
{
registry.view<NativeScriptComponent>().each([=](auto o, NativeScriptComponent &script)
{
if (script.Status == NativeScriptComponent::Status::Ready)
{
script.OnRuntime();
}
});
}
SceneCamera *primaryCamera = nullptr;
Matrix4 cameraTransform;
{
auto view = registry.view<TransformComponent, CameraComponent>();
for (auto &o : view)
{
auto [transform, camera] = view.get<TransformComponent, CameraComponent>(o);
if (camera.Primary)
{
primaryCamera = &camera.Camera;
cameraTransform = transform;
break;
}
}
}
// Only renderer when we have a primary Camera
if (!primaryCamera)
{
primaryCamera = dynamic_cast<SceneCamera*>(&observerCamera);
primaryCamera->SetViewportSize(viewportSize);
observerCamera.OnUpdate(Application::DeltaTime());
}
else
{
primaryCamera->SetTransform(cameraTransform);
}
{
Render::Begin(renderTarget);
{
Render2D::BeginScene(dynamic_cast<const Camera&>(*primaryCamera));
auto group = registry.group<TransformComponent>(entt::get<SpriteRendererComponent>);
for (auto o : group)
{
auto [transform, sprite] = group.get<TransformComponent, SpriteRendererComponent>(o);
Render2D::DrawSprite(transform.Transform(), sprite, (int)o);
}
Render2D::EndScene();
}
{
TransformUniformBuffer transformUniforms;
transformUniforms.viewProjectionMatrix = primaryCamera->ViewProjection();
transformUniforms.skyProjectionMatrix = primaryCamera->Projection() * Matrix4(Vector::Matrix3(primaryCamera->View()));
transformUniforms.sceneRotationMatrix = Matrix4(Vector::Matrix3(primaryCamera->View()));
uniforms.transform->Update(sizeof(TransformUniformBuffer), &transformUniforms);
}
{
ShadingUniformBuffer shadingUniforms;
shadingUniforms.eyePosition = primaryCamera->View()[3];
for (int i = 0; i < SL_ARRAY_LENGTH(shadingUniforms.lights); ++i)
{
const Light &light = environments.light.lights[i];
shadingUniforms.lights[i].direction = Vector4{ light.Direction, 0.0f };
Vector4 finalLight = Vector4{};
if (light.Enabled)
{
finalLight = Vector4{ light.Radiance, 0.0f };
}
shadingUniforms.lights[i].radiance = finalLight;
}
uniforms.shading->Update(sizeof(ShadingUniformBuffer), &shadingUniforms);
}
{
auto view = registry.view<TransformComponent, MeshComponent, MaterialComponent>();
for (auto o : view)
{
auto [transform, mesh, material] = view.get<TransformComponent, MeshComponent, MaterialComponent>(o);
auto &shader = Render::Get<Shader, ShaderName::PBR>();
Render::Submit(shader, mesh.Mesh, transform.Transform());
}
}
Render::End();
}
}
void Scene::OnRenderEditor(const EditorCamera &editorCamera)
{
Render::Begin(renderTarget);
{
Render2D::BeginScene(dynamic_cast<const Camera&>(editorCamera));
auto group = registry.group<TransformComponent>(entt::get<SpriteRendererComponent>);
for (auto o : group)
{
auto [transform, sprite] = group.get<TransformComponent, SpriteRendererComponent>(o);
Render2D::DrawSprite(transform.Transform(), sprite, (int)o);
}
Render2D::EndScene();
}
{
TransformUniformBuffer transformUniforms;
transformUniforms.viewProjectionMatrix = editorCamera.ViewProjection();
transformUniforms.skyProjectionMatrix = editorCamera.Projection() * Matrix4(Vector::Matrix3(editorCamera.View()));
transformUniforms.sceneRotationMatrix = Matrix4{ Matrix3{ editorCamera.View() } };
uniforms.shading->Update(sizeof(TransformUniformBuffer), &transformUniforms);
}
{
ShadingUniformBuffer shadingUniforms;
shadingUniforms.eyePosition = editorCamera.View()[3];
for (int i = 0; i < SL_ARRAY_LENGTH(shadingUniforms.lights); ++i)
{
const Light &light = environments.light.lights[i];
shadingUniforms.lights[i].direction = Vector4{ light.Direction, 0.0f };
Vector4 finalLight{};
if (light.Enabled)
{
finalLight = Vector4{ light.Radiance, 0.0f };
}
shadingUniforms.lights[i].radiance = finalLight;
}
uniforms.shading->Update(sizeof(ShadingUniformBuffer), &shadingUniforms);
}
auto view = registry.view<TransformComponent, MeshComponent, MaterialComponent>();
for (auto &o : view)
{
auto [transform, mesh, material] = view.get<TransformComponent, MeshComponent, MaterialComponent>(o);
auto &shader = Render::Get<Shader, ShaderName::PBR>();
Render::Submit(shader, mesh.Mesh, transform.Transform());
}
Render::End();
}
Object Scene::CreateObject(const std::string &name)
{
auto o = Object{ registry.create(), this };
o.AddComponent<TransformComponent>();
auto &idComponent = o.AddComponent<IDComponent>();
o.AddComponent<TagComponent>(name);
return o;
}
void Scene::DestroyObject(Object & o)
{
registry.destroy(o);
}
void Scene::SetViewportSize(const Vector2 &size)
{
viewportSize = size;
renderTarget->Resize(size);
}
Object Scene::PrimaryCameraObject()
{
auto view = registry.view<CameraComponent>();
for (auto o : view)
{
const auto &camera = view.get<CameraComponent>(o);
if (camera.Primary)
{
return Object{ o, this };
}
}
return Object{};
}
}
| 29.253846 | 131 | 0.615698 | [
"mesh",
"render",
"object",
"vector",
"transform"
] |
bd022e23a8448a2d024e29f0be00f247863962dd | 2,097 | cc | C++ | components/service/ucloud/multimediaai/src/model/UpdateTemplateRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | components/service/ucloud/multimediaai/src/model/UpdateTemplateRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | components/service/ucloud/multimediaai/src/model/UpdateTemplateRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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 <alibabacloud/multimediaai/model/UpdateTemplateRequest.h>
using AlibabaCloud::Multimediaai::Model::UpdateTemplateRequest;
UpdateTemplateRequest::UpdateTemplateRequest() :
RpcServiceRequest("multimediaai", "2019-08-10", "UpdateTemplate")
{
setMethod(HttpRequest::Method::Post);
}
UpdateTemplateRequest::~UpdateTemplateRequest()
{}
std::string UpdateTemplateRequest::getTemplateId()const
{
return templateId_;
}
void UpdateTemplateRequest::setTemplateId(const std::string& templateId)
{
templateId_ = templateId;
setParameter("TemplateId", templateId);
}
int UpdateTemplateRequest::getType()const
{
return type_;
}
void UpdateTemplateRequest::setType(int type)
{
type_ = type;
setParameter("Type", std::to_string(type));
}
std::string UpdateTemplateRequest::getContent()const
{
return content_;
}
void UpdateTemplateRequest::setContent(const std::string& content)
{
content_ = content;
setParameter("Content", content);
}
std::string UpdateTemplateRequest::getTemplateName()const
{
return templateName_;
}
void UpdateTemplateRequest::setTemplateName(const std::string& templateName)
{
templateName_ = templateName;
setParameter("TemplateName", templateName);
}
bool UpdateTemplateRequest::getIsDefault()const
{
return isDefault_;
}
void UpdateTemplateRequest::setIsDefault(bool isDefault)
{
isDefault_ = isDefault;
setParameter("IsDefault", isDefault ? "true" : "false");
}
| 24.670588 | 77 | 0.746304 | [
"model"
] |
bd062accfbd5f87eaed82313d515e90aa14e788b | 4,354 | hpp | C++ | conjecture_prover.hpp | nwoeanhinnogaehr/lgo | c59470e107e27c7d2174da5352bd4639edabf1e2 | [
"MIT"
] | null | null | null | conjecture_prover.hpp | nwoeanhinnogaehr/lgo | c59470e107e27c7d2174da5352bd4639edabf1e2 | [
"MIT"
] | 11 | 2016-12-25T19:14:10.000Z | 2017-03-14T01:52:03.000Z | conjecture_prover.hpp | nwoeanhinnogaehr/lgo | c59470e107e27c7d2174da5352bd4639edabf1e2 | [
"MIT"
] | null | null | null | #pragma once
#include "ab.hpp"
// helper to build a class hierarchy from a variadic list of types
template <template <pos_t, typename, template <pos_t, typename> typename>
typename Interior,
pos_t size, typename Impl, template <pos_t, typename> typename First,
template <pos_t, typename> typename... Rest>
struct ManyImplWrapper : Interior<size, ManyImplWrapper<Interior, size, Impl, Rest...>, First> {};
template <template <pos_t, typename, template <pos_t, typename> typename>
typename Interior,
pos_t size, typename Impl, template <pos_t, typename> typename First>
struct ManyImplWrapper<Interior, size, Impl, First> : Interior<size, Impl, First> {};
// search for nodes which conflict with conjecture. example usage:
// ConjectureProver<size, Minimax<size>, AlphaBeta, PruningConjecture1, PruningConjecture2> prover;
// State<size> state;
// prover.search(state);
template <pos_t size, typename Impl, template <pos_t, typename> typename Conjecture>
struct ConjectureProverImplWrapper : Impl {
typedef typename Impl::minimax_t minimax_t;
typedef typename Impl::return_t return_t;
Conjecture<size, Impl> conj;
AlphaBeta<size, Conjecture<size, Impl>> conj_search;
std::stack<optional<return_t>> conjected;
return_t init_node(State<size> &state, minimax_t &alpha, minimax_t &beta, size_t depth,
bool &terminal) {
if (conj.diverges(state))
conjected.emplace(conj_search.search(state, alpha, beta, depth));
else
conjected.emplace();
return Impl::init_node(state, alpha, beta, depth, terminal);
}
void on_exit(const State<size> &state, minimax_t alpha, minimax_t beta, size_t depth,
const return_t &value, bool terminal) {
optional<return_t> expected = conjected.top();
conjected.pop();
if (expected && !(*expected == value)) {
std::cout << "At board " << state.board << " with player " << state.to_play
<< " at depth " << depth << std::endl;
}
Impl::on_exit(state, alpha, beta, depth, value, terminal);
}
};
template <pos_t size, typename Impl, template <pos_t, typename> typename Search,
template <pos_t, typename> typename... Conjectures>
using ConjectureProver =
Search<size, ManyImplWrapper<ConjectureProverImplWrapper, size, Impl, Conjectures...>>;
// do search using pruning as specified by conjecture(s). example usage:
// PrunedSearch<size, Minimax<size>, AlphaBeta, PruningConjecture1, PruningConjecture2, ...> solver;
// State<size> state;
// solver.search(state);
template <pos_t size, typename Impl, template <pos_t, typename> typename Conjecture>
struct PrunedSearchImplWrapper : Impl {
typedef typename Impl::minimax_t minimax_t;
typedef typename Impl::return_t return_t;
Conjecture<size, Impl> conj;
return_t init_node(State<size> &state, minimax_t &alpha, minimax_t &beta, size_t depth,
bool &terminal) {
if (optional<return_t> conjected = conj.apply(state, alpha, beta)) {
terminal = true;
return *conjected;
}
return Impl::init_node(state, alpha, beta, depth, terminal);
}
};
template <pos_t size, typename Impl, template <pos_t, typename> typename Search,
template <pos_t, typename> typename... Conjectures>
using PrunedSearch =
Search<size, ManyImplWrapper<PrunedSearchImplWrapper, size, Impl, Conjectures...>>;
// conjectures below
template <pos_t size, typename Impl> struct NullConjecture : Impl {
bool diverges(const State<size> &state) const {
return false;
}
};
template <pos_t size, typename Impl> struct Cell2Conjecture : Impl {
bool diverges(const State<size> &state) const {
return state.board.get(0) == EMPTY && state.board.get(1) == EMPTY &&
!state.board.is_captured(0) && !state.board.is_captured(1);
}
void gen_moves(const State<size> &state, std::vector<Move> &moves) const {
Impl::gen_moves(state, moves);
if (diverges(state)) {
for (size_t i = 0; i < moves.size(); i++) {
if (moves[i].position == 0 && !moves[i].is_pass) {
moves.erase(moves.begin() + i);
break;
}
}
}
}
};
| 44.428571 | 100 | 0.654341 | [
"vector"
] |
bd0d2cf3013c8ef371bd1aa0b15d38e423bdcdcc | 6,318 | cpp | C++ | sources/DBhasher.cpp | NickBabakin/lab-10-kv-storage | 195d492ec307d768cccc009b3b9abf9713d4b742 | [
"MIT"
] | null | null | null | sources/DBhasher.cpp | NickBabakin/lab-10-kv-storage | 195d492ec307d768cccc009b3b9abf9713d4b742 | [
"MIT"
] | null | null | null | sources/DBhasher.cpp | NickBabakin/lab-10-kv-storage | 195d492ec307d768cccc009b3b9abf9713d4b742 | [
"MIT"
] | null | null | null | //Copyright [2021] <nickgeo.winner@gmail.com>
#include "DBhasher.hpp"
DBhasher::DBhasher(std::string _kDBpath, std::string _new_path,
const size_t& _threads_count, std::string _log_level)
: threads_count(_threads_count)
, src_path(std::move(_kDBpath))
, new_path(std::move(_new_path))
, src_db(nullptr)
, new_db(nullptr)
, stop_hash(false)
, stop_read(false)
, stop_write(false)
, pieces_to_hash(0)
, pieces_to_write(0)
, pieces_to_read(0)
, log_level(std::move(_log_level))
{
data_to_hash = new safe_queue<data_piece>;
data_to_write = new safe_queue<data_piece>;
}
void DBhasher::perform() {
logger::logging_init(log_level);
get_descriptors();
rocksdb::Status status;
status =
rocksdb::DB::Open(rocksdb::DBOptions(), src_path, descriptors,
&src_handles, &src_db);
assert(status.ok());
BOOST_LOG_TRIVIAL(info) << "Source db " << src_db
<< " opened successfully" << std::endl;
//print_db(src_database);
start_reading();
start_hashing();
create_new_db();
status = rocksdb::DB::Open(rocksdb::DBOptions(), new_path,
descriptors, &new_handles, &new_db);
assert(status.ok());
BOOST_LOG_TRIVIAL(info) << "New db " << new_db
<< " created and opened successfully" << std::endl;
start_writing();
global_work.lock();
BOOST_LOG_TRIVIAL(info) << "Done processing databases" << std::endl;
//print_db(new_database);
close_both_db();
global_work.unlock();
}
void DBhasher::print_db(database db) {
rocksdb::DB* cur_db;
std::vector<rocksdb::ColumnFamilyHandle*> cur_handles;
if (db == new_database) {
cur_db = new_db;
cur_handles = new_handles;
} else {
cur_db = src_db;
cur_handles = src_handles;
}
for (auto & handle : cur_handles){
std::cout << "Column : " << handle->GetName();
std::cout << std::endl;
std::unique_ptr<rocksdb::Iterator> it(
cur_db->NewIterator(rocksdb::ReadOptions(), handle));
for (it->SeekToFirst(); it->Valid(); it->Next()) {
std::cout << it->key().ToString() << " : "
<< it->value().ToString() << std::endl;
}
std::cout << std::endl;
}
}
void DBhasher::get_descriptors() {
std::vector <std::string> families;
rocksdb::Status status =
rocksdb::DB::ListColumnFamilies(rocksdb::DBOptions(),
src_path, &families);
assert(status.ok());
descriptors.reserve(families.size());
for (const std::string &family : families) {
descriptors.emplace_back(family, rocksdb::ColumnFamilyOptions());
}
}
void DBhasher::create_new_db() {
rocksdb::Status status;
rocksdb::Options options;
options.create_if_missing = true;
status = rocksdb::DB::Open(options, new_path, &new_db);
assert(status.ok());
rocksdb::ColumnFamilyHandle* cf;
for (const auto &descriptor : descriptors){
status = new_db->CreateColumnFamily(rocksdb::ColumnFamilyOptions(),
descriptor.name, &cf);
delete cf;
}
assert(status.ok());
delete new_db;
}
void DBhasher::start_reading() {
static const auto reading_func = [this](rocksdb::ColumnFamilyHandle* handle){
++pieces_to_read;
std::unique_ptr<rocksdb::Iterator> it(
src_db->NewIterator(rocksdb::ReadOptions(), handle));
for (it->SeekToFirst(); it->Valid(); it->Next()) {
data_to_hash->push(data_piece
{ handle,
it->key().ToString(),
it->value().ToString()});
++pieces_to_hash;
}
--pieces_to_read;
if ((pieces_to_read == 0) && (stop_read)){
stop_hash = true;
}
};
ThreadPool pool_read(threads_count); // treads_count = 4
for (auto& handle : src_handles){ // src_handles.size() = 10
pool_read.enqueue(reading_func, handle);
}
BOOST_LOG_TRIVIAL(info) << "Reading started" << std::endl;
stop_read = true;
}
void DBhasher::start_hashing() {
static const auto hashing_func = [this]{
while (!(stop_hash && (pieces_to_hash <= 0))){
if (!data_to_hash->is_empty()){
data_piece data = data_to_hash->pop();
std::string old_value = data.value;
data.value = picosha2::hash256_hex_string(data.key + data.value);
BOOST_LOG_TRIVIAL(trace) << "Calculated hash: " << std::endl
<< "From column \"" << data.handle->GetName()
<< "\"" << data.key << " + " << old_value
<< " = "
<< data.value << std::endl;
data_to_write->push(std::move(data));
--pieces_to_hash;
++pieces_to_write;
}
}
stop_write = true;
};
ThreadPool pool_hash(threads_count);
for (size_t i = 0; i < threads_count; ++i){
pool_hash.enqueue(hashing_func);
}
BOOST_LOG_TRIVIAL(info) << "Hashing started" << std::endl;
}
void DBhasher::start_writing() {
static const auto writing_func = [this]{
global_work.lock_shared();
rocksdb::WriteBatch batch;
while (!(stop_write && (pieces_to_write <= 0))){
if (!data_to_write->is_empty()){
data_piece data;
try { data = data_to_write->pop(); }
catch (...){
continue;
}
batch.Put(data.handle, rocksdb::Slice(data.key),
rocksdb::Slice(data.value));
--pieces_to_write;
}
}
rocksdb::Status status = new_db->Write(rocksdb::WriteOptions(), &batch);
assert(status.ok());
global_work.unlock_shared();
};
ThreadPool pool_write(threads_count);
for (size_t i = 0; i < threads_count; ++i){
pool_write.enqueue(writing_func);
}
BOOST_LOG_TRIVIAL(info) << "Writing started" << std::endl;
}
void DBhasher::close_both_db() {
rocksdb::Status status;
for (auto &handle : src_handles) {
status = src_db->DestroyColumnFamilyHandle(handle);
assert(status.ok());
}
delete src_db;
for (auto &handle : new_handles) {
status = new_db->DestroyColumnFamilyHandle(handle);
assert(status.ok());
}
delete new_db;
BOOST_LOG_TRIVIAL(info) << "Both databases closed successfully" << std::endl;
}
DBhasher::~DBhasher() {
delete data_to_hash;
delete data_to_write;
}
| 31.59 | 79 | 0.606046 | [
"vector"
] |
bd121ac4f8448787a8b3452bb2117409805ad463 | 10,798 | hpp | C++ | src/TimeStepper/Optimizer.hpp | asmaloney/IPC | fcf72a951c072d0ea1755ccf27cbb03df0f2f8ea | [
"MIT"
] | 9 | 2021-11-03T18:39:59.000Z | 2022-03-11T09:19:14.000Z | src/TimeStepper/Optimizer.hpp | Kirkice/IPC | ad40d232c09360cd4851b5badbc899df37b851a2 | [
"MIT"
] | 2 | 2021-11-03T18:47:13.000Z | 2022-02-28T19:41:49.000Z | src/TimeStepper/Optimizer.hpp | Kirkice/IPC | ad40d232c09360cd4851b5badbc899df37b851a2 | [
"MIT"
] | 2 | 2021-11-03T18:57:40.000Z | 2021-12-22T06:43:37.000Z | //
// Optimizer.hpp
// IPC
//
// Created by Minchen Li on 8/31/17.
//
#ifndef Optimizer_hpp
#define Optimizer_hpp
#include "Types.hpp"
#include "Energy.hpp"
#include "AnimScripter.hpp"
#include "Config.hpp"
#include "LinSysSolver.hpp"
#include "SpatialHash.hpp"
#include "OSQPWrapper.h"
#ifdef USE_GUROBI
#include <Gurobi.h>
#endif
#include <fstream>
namespace IPC {
// a class for solving an optimization problem
template <int dim>
class Optimizer {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
friend class Mesh<dim>;
protected: // referenced data
const Mesh<dim>& data0; // initial guess
const std::vector<Energy<dim>*>& energyTerms; // E_0, E_1, E_2, ...
const std::vector<double>& energyParams; // a_0, a_1, a_2, ...
// E = \sum_i a_i E_i
Config animConfig;
protected: // owned data
bool mute;
int globalIterNum;
double relGL2Tol;
Mesh<dim> result; // intermediate results of each iteration
bool useGD = false;
// SPD solver for solving the linear system for search directions
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>*linSysSolver, *dampingMtr;
bool solveWithQP; ///< @brief Use QP with nonlinear contact constraints.
bool solveWithSQP; ///< @brief Use Sequential QP with nonlinear contact constraints.
bool solveQPSuccess; ///< @brief Was the previous QP solve successful?
OSQP OSQPSolver;
#ifdef USE_GUROBI
Eigen::GurobiSparse gurobiQPSolver;
#endif
Eigen::SparseMatrix<double> P_QP;
std::vector<double*> elemPtr_P_QP;
Eigen::VectorXd dual_QP;
std::vector<int> constraintStartInds;
std::vector<std::vector<int>> activeSet, activeSet_next;
std::vector<std::vector<int>> activeSet_lastH;
std::vector<Eigen::VectorXd> lambda_lastH;
bool solveIP, solveFric;
double mu_IP, dHatEps, dHat;
double fbNormTol, bboxDiagSize2, dTolRel, dTol, dHatTarget;
double fricDHat, fricDHatThres, fricDHat0, fricDHatTarget;
std::vector<std::vector<MMCVID>> MMActiveSet, MMActiveSet_next;
std::unordered_map<MMCVID, double, MMCVIDHash> mesh_mmcvid_to_toi;
std::vector<std::vector<MMCVID>> paraEEMMCVIDSet;
std::vector<std::vector<std::pair<int, int>>> paraEEeIeJSet;
std::vector<std::vector<std::pair<int, int>>> MMActiveSet_CCD;
std::vector<std::vector<MMCVID>> MMActiveSet_lastH;
std::vector<Eigen::VectorXd> MMLambda_lastH;
std::vector<std::vector<Eigen::Vector2d>> MMDistCoord;
std::vector<std::vector<Eigen::Matrix<double, 3, 2>>> MMTanBasis;
Eigen::VectorXi n_collPairs_sum, n_collPairs_max, n_convCollPairs_sum, n_convCollPairs_max;
int n_collPairs_total_max, n_convCollPairs_total_max;
SpatialHash<dim> sh;
std::vector<std::pair<int, int>> closeConstraintID;
std::vector<std::pair<int, MMCVID>> closeMConstraintID;
std::vector<double> closeConstraintVal, closeMConstraintVal;
double CN_MBC, rho_DBC;
std::vector<std::set<int>> vNeighbor_IP;
bool m_projectDBC;
std::set<Triplet> initSF;
Eigen::VectorXd gradient; // energy gradient computed in each iteration
Eigen::VectorXd searchDir; // search direction comptued in each iteration
double lastEnergyVal; // for output and line search
double targetGRes;
std::vector<Eigen::VectorXd> gradient_ET;
std::vector<double> energyVal_ET;
std::ofstream file_iterStats;
std::ofstream file_sysE, file_sysM, file_sysL;
int numOfLineSearch;
protected: // dynamic information
Eigen::VectorXd velocity;
Eigen::MatrixXd xTilta, dx_Elastic, acceleration;
double dt, dtSq;
Eigen::Matrix<double, dim, 1> gravity, gravityDtSq;
int frameAmt;
AnimScripter<dim> animScripter;
int innerIterAmt;
std::vector<AutoFlipSVD<Eigen::Matrix<double, dim, dim>>> svd;
std::vector<Eigen::Matrix<double, dim, dim>> F;
double beta_NM; // \in [1/4,1/2], default 1/4
double gamma_NM; // \in [0,1], default 1/2
public: // constructor and destructor
Optimizer(const Mesh<dim>& p_data0,
const std::vector<Energy<dim>*>& p_energyTerms,
const std::vector<double>& p_energyParams,
bool p_mute = false,
const Eigen::MatrixXd& UV_bnds = Eigen::MatrixXd(),
const Eigen::MatrixXi& E = Eigen::MatrixXi(),
const Eigen::VectorXi& bnd = Eigen::VectorXi(),
const Config& animConfig = Config());
virtual ~Optimizer(void);
public: // API
virtual void setTime(double duration, double dt);
virtual void updateTargetGRes(void);
// precompute preconditioning matrix and factorize for fast solve, prepare initial guess
virtual void precompute(void);
// solve the optimization problem that minimizes E using a hill-climbing method,
// the final result will be in result
virtual int solve(int maxIter = 100);
virtual void updatePrecondMtrAndFactorize(void);
virtual void getFaceFieldForVis(Eigen::VectorXd& field);
virtual Mesh<dim>& getResult(void);
virtual int getIterNum(void) const;
virtual int getInnerIterAmt(void) const;
virtual void setRelGL2Tol(double p_relTol = 1.0e-2);
virtual double getDt(void) const;
virtual void setAnimScriptType(AnimScriptType animScriptType,
const std::string& meshSeqFolderPath);
virtual void saveStatus(const std::string& appendStr = "");
virtual void outputCollStats(std::ostream& out);
virtual void checkGradient(void);
virtual void checkHessian(void);
protected: // helper functions
/// @breif Compute the intial values for P_QP
virtual void precomputeQPObjective(
const LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSys,
Eigen::SparseMatrix<double>& P,
std::vector<double*>& elemPtr_P) const;
/// @brief Update the elements of P_QP
virtual void updateQPObjective(
const LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSys,
const std::vector<double*>& elemPtr_P) const;
/// @brief Clear the next active set.
virtual void clearActiveSet();
/// @brief Update the active set used by the SQP and QP solvers.
virtual bool updateActiveSet_QP();
/// @brief Count the number of constraints in the active set.
virtual int countConstraints();
/// @brief Compute the QP inequality constraints \f$Ax \geq b\f$
virtual void computeQPInequalityConstraint(
const Mesh<dim>& mesh,
const std::vector<CollisionObject<dim>*>& collisionObjects,
const std::vector<std::vector<int>>& activeSet,
const int num_vars,
std::vector<int>& constraintStartInds,
Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b) const;
/// @brief Solve the QP of the objective and collision constraints.
virtual bool solveQP(
const Mesh<dim>& mesh,
const std::vector<CollisionObject<dim>*>& collisionObjects,
const std::vector<std::vector<int>>& activeSet,
const LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSys,
Eigen::SparseMatrix<double>& P,
const std::vector<double*>& elemPtr_P,
Eigen::VectorXd& gradient,
OSQP& OSQPSolver,
#ifdef USE_GUROBI
Eigen::GurobiSparse& gurobiQPSolver,
#endif
std::vector<int>& constraintStartInds,
Eigen::VectorXd& searchDir,
Eigen::VectorXd& dual,
QPSolverType qpSolverType) const;
/// @brief Solve the QP using OSQP.
virtual bool solveQP_OSQP(
Eigen::SparseMatrix<double>& Q, Eigen::VectorXd& c,
Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b,
OSQP& QPSolver, Eigen::VectorXd& x, Eigen::VectorXd& dual) const;
#ifdef USE_GUROBI
/// @brief Solve the QP using Gurobi.
virtual bool solveQP_Gurobi(
const Eigen::SparseMatrix<double>& Q, const Eigen::VectorXd& c,
const Eigen::SparseMatrix<double>& A, const Eigen::VectorXd& b,
Eigen::GurobiSparse& QPSolver,
Eigen::VectorXd& x, Eigen::VectorXd& dual) const;
#endif
virtual void computeQPResidual(const Mesh<dim>& mesh,
const std::vector<CollisionObject<dim>*>& collisionObjects,
const std::vector<std::vector<int>>& activeSet,
const std::vector<int>& constraintStartInds,
const Eigen::VectorXd& gradient,
const Eigen::VectorXd& dual,
Eigen::VectorXd& grad_KKT,
Eigen::VectorXd& constraintVal,
Eigen::VectorXd& fb);
virtual void initX(int option, std::vector<std::vector<int>>& p_activeSet_next);
virtual void computeXTilta(void);
virtual bool fullyImplicit(void);
virtual bool fullyImplicit_IP(void);
virtual bool solveSub_IP(double mu, std::vector<std::vector<int>>& AHat,
std::vector<std::vector<MMCVID>>& MMAHat);
virtual void initMu_IP(double& mu);
virtual void upperBoundMu(double& mu);
virtual void suggestMu(double& mu);
virtual void initSubProb_IP(void);
virtual void computeSearchDir(int k, bool projectDBC = true);
virtual void postLineSearch(double alpha);
// solve for new configuration in the next iteration
//NOTE: must compute current gradient first
virtual bool solve_oneStep(void);
virtual void computeConstraintSets(const Mesh<dim>& data, bool rehash = true);
virtual void buildConstraintStartInds(const std::vector<std::vector<int>>& activeSet,
std::vector<int>& constraintStartInds);
virtual void buildConstraintStartIndsWithMM(const std::vector<std::vector<int>>& activeSet,
const std::vector<std::vector<MMCVID>>& MMActiveSet,
std::vector<int>& constraintStartInds);
virtual bool lineSearch(double& stepSize, double armijoParam = 0.0, double lowerBound = 0.0);
virtual void stepForward(const Eigen::MatrixXd& dataV0,
Mesh<dim>& data, double stepSize) const;
virtual void computeEnergyVal(const Mesh<dim>& data,
int redoSVD, double& energyVal);
virtual void computeGradient(const Mesh<dim>& data,
bool redoSVD, Eigen::VectorXd& gradient, bool projectDBC = true);
virtual void computePrecondMtr(const Mesh<dim>& data,
bool redoSVD,
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* p_linSysSolver,
bool updateDamping = false, bool projectDBC = true);
virtual void computeDampingMtr(const Mesh<dim>& data,
bool redoSVD,
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* p_dampingMtr,
bool projectDBC = true);
virtual void setupDampingMtr(const Mesh<dim>& data,
bool redoSVD,
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* p_dampingMtr);
virtual void computeSystemEnergy(std::vector<double>& sysE,
std::vector<Eigen::Matrix<double, 1, dim>>& sysM,
std::vector<Eigen::Matrix<double, 1, dim>>& sysL);
virtual void initStepSize(const Mesh<dim>& data, double& stepSize);
};
} // namespace IPC
#endif /* Optimizer_hpp */
| 38.702509 | 97 | 0.696981 | [
"mesh",
"vector"
] |
bd144e5e41d63296fb1e78360ccc59497f9ef657 | 13,040 | cpp | C++ | src/gui/circle.cpp | vlabella/GLE | ff6b424fda75d674c6a9f270ccdade3ab149e24f | [
"BSD-3-Clause"
] | 3 | 2022-03-03T06:48:33.000Z | 2022-03-13T21:18:11.000Z | src/gui/circle.cpp | vlabella/GLE | ff6b424fda75d674c6a9f270ccdade3ab149e24f | [
"BSD-3-Clause"
] | 1 | 2022-03-14T13:01:29.000Z | 2022-03-14T13:13:23.000Z | src/gui/circle.cpp | vlabella/GLE | ff6b424fda75d674c6a9f270ccdade3ab149e24f | [
"BSD-3-Clause"
] | 1 | 2021-12-21T23:14:06.000Z | 2021-12-21T23:14:06.000Z | /***********************************************************************************
* QGLE - A Graphical Interface to GLE *
* Copyright (C) 2006 A. S. Budden & J. Struyf *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
* *
* Also add information on how to contact you by electronic and paper mail. *
***********************************************************************************/
#include "circle.h"
// The constructor for the circle object
GLECircle::GLECircle(double resolution, QSize imageSize, GLEDrawingArea *area) :
GLEDrawingObject(resolution, imageSize, area)
{
// Make sure the circle is updated if a point changes or
// the image size changes
connect(this, SIGNAL(pointChanged()),
this, SLOT(updateCircle()));
connect(this, SIGNAL(imageChanged()),
this, SLOT(updateCircle()));
connect(this, SIGNAL(propertyChanged(int)),
this, SLOT(updateFromProperty(int)));
amove = false;
// More to be added
validProperties
<< FillColour
<< LineColour
<< LineWidth
<< LineStyle;
properties[FillColour] = propertyDescriptions[FillColour].defaultValue;
properties[LineColour] = propertyDescriptions[LineColour].defaultValue;
properties[LineWidth] = propertyDescriptions[LineWidth].defaultValue;
properties[LineStyle] = propertyDescriptions[LineStyle].defaultValue;
}
void GLECircle::createOTracks()
{
if (isSet(CentrePoint) && isSet(Radius))
{
// We need to know the page size to be able to do this!
}
}
void GLECircle::updateFromProperty(int)
{
GLEEllipseDO* obj = (GLEEllipseDO*)getGLEObject();
GLEPropertyStore* obj_prop = obj->getProperties();
obj_prop->setRealProperty(GLEDOPropertyLineWidth, getProperty(LineWidth).toDouble());
QColor color = getProperty(LineColour).value<QColor>();
GLEColor* gle_color = obj->getProperties()->getColorProperty(GLEDOPropertyColor);
gle_color->setRGB255(color.red(), color.green(), color.blue());
QGLE::qtToGLEString(getProperty(LineStyle).toString(), obj_prop->getStringProperty(GLEDOPropertyLineStyle));
GLEColor* gle_fill = obj->getProperties()->getColorProperty(GLEDOPropertyFillColor);
if (properties[FillColour].value<QColor>().isValid()) {
QColor fill = getProperty(FillColour).value<QColor>();
gle_fill->setRGB255(fill.red(), fill.green(), fill.blue());
} else {
gle_fill->setTransparent(true);
}
((GLEDrawingArea*)parent())->setDirtyAndSave();
}
// Update the painter path
void GLECircle::updateCircle()
{
QPointF p;
QPair<QPointF,int> snap;
// Only do this if both the centre and radius have been set
if (isSet(CentrePoint) && isSet(Radius))
{
// This is guaranteed to have been created in the constructor
// of GLEDrawingObject
delete(paintPath);
// Create a new path starting at circleCentre
paintPath = new QPainterPath(getQtPoint(CentrePoint));
// Add the circle based on the qrect
paintPath->addEllipse(circleRect());
// Update GLE object
GLEEllipseDO* circle = (GLEEllipseDO*)getGLEObject();
if (circle != NULL) {
circle->setCenter(QGLE::QPointFToGLEPoint(getGLEPoint(CentrePoint)));
circle->setRadius(getGLELength(Radius));
}
// Now we add the osnap handles
osnapHandles.clear();
for(int i=0;i<360;i+=90)
{
p.setX(getQtLength(Radius)*cos(QGLE::degreesToRadians(i)));
p.setY(getQtLength(Radius)*sin(QGLE::degreesToRadians(i)));
p += getQtPoint(CentrePoint);
snap.first = p;
snap.second = QGLE::QuadrantSnap;
osnapHandles.append(snap);
}
snap.first = getQtPoint(CentrePoint);
snap.second = QGLE::CentreSnap;
osnapHandles.append(snap);
}
}
void GLECircle::addRelativeOSnaps(QPointF p)
{
if (isSet(CentrePoint) && isSet(Radius))
{
relativeOSnaps.clear();
QList<QPointF> perpendiculars = getPerpendiculars(p);
QPointF ppt;
foreach(ppt, perpendiculars)
{
relativeOSnaps.append(QPair<QPointF,int>(ppt, QGLE::PerpendicularSnap));
}
QList<QPointF> tangents = getTangents(p);
QPointF tpt;
foreach(tpt, tangents)
{
relativeOSnaps.append(QPair<QPointF,int>(tpt, QGLE::TangentSnap));
}
}
}
QList<QPointF> GLECircle::getTangents(QPointF p)
{
QList<QPointF> tangents;
QPointF np;
if (!isInside(p))
{
double angleToCentre = QGLE::angleBetweenTwoPoints(p,getQtPoint(CentrePoint));
double radius = getQtLength(Radius);
// Now we need the tangential ones
double distanceToCentre = QGLE::distance(p, getQtPoint(CentrePoint));
double angleOffset = asin(radius/distanceToCentre);
double distanceToTangent = sqrt(pow(distanceToCentre,2)-pow(radius,2));
angleToCentre = QGLE::angleBetweenTwoPoints(p,getQtPoint(CentrePoint));
double angle = angleToCentre + angleOffset;
np = p + QPointF(distanceToTangent*cos(angle),distanceToTangent*sin(angle));
tangents.append(np);
angle = angleToCentre - angleOffset;
np = p + QPointF(distanceToTangent*cos(angle),distanceToTangent*sin(angle));
tangents.append(np);
}
return(tangents);
}
bool GLECircle::hasTangents()
{
return(true);
}
QList<QPointF> GLECircle::getPerpendiculars(QPointF p)
{
QList<QPointF> perpendiculars;
// The first perpendicular osnap is defined as the nearest point
QPointF np;
distanceToPoint(p,&np);
perpendiculars.append(np);
// The second perpendicular osnap is diametrically opposite the first one
double angleToCentre = QGLE::angleBetweenTwoPoints(np,getQtPoint(CentrePoint));
double radius = getQtLength(Radius);
double diameter = 2*radius;
np = np + QPointF(diameter*cos(angleToCentre),diameter*sin(angleToCentre));
perpendiculars.append(np);
return(perpendiculars);
}
bool GLECircle::hasPerpendiculars()
{
return(true);
}
void GLECircle::draw(QPainter *p)
{
if (isSet(CentrePoint) && isSet(Radius))
{
p->save();
QPen cpen;
setSimplePenProperties(cpen);
p->setPen(cpen);
if (properties[FillColour].value<QColor>().isValid())
p->setBrush(QBrush(properties[FillColour].value<QColor>()));
else
p->setBrush(Qt::NoBrush);
p->drawEllipse(circleRect());
p->restore();
}
}
double GLECircle::distanceToPoint(const QPointF& p, QPointF *nearestPoint)
{
QPointF c = getQtPoint(CentrePoint);
if (nearestPoint)
{
double r = getQtLength(Radius);
double theta = QGLE::angleBetweenTwoPoints(c,p);
nearestPoint->setX(r*cos(theta)+c.x());
nearestPoint->setY(r*sin(theta)+c.y());
}
// Calculations in QT coordinates
return(fabs(QGLE::distance(c,p)-getQtLength(Radius)));
}
// Set a point (start or end in the case of a line)
void GLECircle::setPoint(int pointChoice, const QPointF& p, bool update)
{
double radius;
switch(pointChoice)
{
// Note that circumference point also runs
// the centre point code: this is intentional
case CircumferencePoint:
if (!isSet(CentrePoint))
return;
radius = QGLE::distance(QGLE::absQtToGLE(p,dpi,pixmap.height()),getGLEPoint(CentrePoint));
if (QGLE::relGLEToQt(radius,dpi) > MINIMUM_CIRCLE_RADIUS)
pointHash[Radius] = QPointF(radius, 0);
else
pointHash.remove(Radius);
case CentrePoint:
pointHash[pointChoice] = QGLE::absQtToGLE(p, dpi, pixmap.height());
break;
case Radius:
pointHash[pointChoice] = QGLE::relQtToGLE(p, dpi);
}
if (update) updateCircle();
}
QRectF GLECircle::circleRect()
{
// Work in Qt coordinates
QPointF c = getQtPoint(CentrePoint);
double r = getQtLength(Radius);
return(QRectF(c.x() - r,
c.y() - r,
2*r, 2*r));
}
QList<QPointF> GLECircle::intersections(double qtm, double qtc, bool vertical)
{
QPointF one, two;
// For circles, we'll deal with points individually:
if (vertical)
{
one.setX(qtm);
two.setX(qtm);
one.setY(0.0);
two.setY(1.0);
}
else
{
one.setX(0.0);
one.setY(qtc);
two.setX(1.0);
two.setY(qtm + qtc);
}
return(intersections(one,two));
}
QList<QPointF> GLECircle::intersections(QPointF qtp1, QPointF qtp2)
{
QList<QPointF> pointArray;
if (!(isSet(CentrePoint) && isSet(Radius)))
return(pointArray);
QPointF cp = getQtPoint(CentrePoint);
double r = getQtLength(Radius);
double a,b,c;
double bac;
double u;
QPointF p;
a = pow((qtp2.x() - qtp1.x()),2) + pow((qtp2.y() - qtp1.y()),2);
b = 2 * ( (qtp2.x() - qtp1.x())*(qtp1.x()-cp.x()) + (qtp2.y()-qtp1.y())*(qtp1.y()-cp.y()));
c = pow(cp.x(),2)+pow(cp.y(),2)+pow(qtp1.x(),2)+pow(qtp1.y(),2)
- 2*(cp.x()*qtp1.x()+cp.y()*qtp1.y()) - pow(r,2);
bac = pow(b,2)-4*a*c;
if (bac == 0.0)
{
u = - b / (2*a);
p.setX(qtp1.x()+u*(qtp2.x()-qtp1.x()));
p.setY(qtp1.y()+u*(qtp2.y()-qtp1.y()));
pointArray.append(p);
}
else if (bac > 0.0)
{
u = (-b + sqrt(bac))/(2*a);
p.setX(qtp1.x() + u*(qtp2.x()-qtp1.x()));
p.setY(qtp1.y() + u*(qtp2.y()-qtp1.y()));
pointArray.append(p);
u = (-b - sqrt(bac))/(2*a);
p.setX(qtp1.x() + u*(qtp2.x()-qtp1.x()));
p.setY(qtp1.y() + u*(qtp2.y()-qtp1.y()));
pointArray.append(p);
}
return(pointArray);
}
QList<QPointF> GLECircle::intersections(QPointF qtp1, double angle)
{
// This intersection code must determine the intersections in
// a particular direction from a start point
// First get a list based on an infinite line:
QPointF qtp2 = qtp1 + QPointF(1.0*cos(angle),1.0*sin(angle));
QList<QPointF> allIntersections = intersections(qtp1,qtp2);
// Now go through the list and determine which are in the right
// direction
QList<QPointF> correctIntersections;
QPointF pt;
double ptAngle;
foreach(pt, allIntersections)
{
ptAngle = QGLE::angleBetweenTwoPoints(qtp1, pt);
if (QGLE::quadrant(ptAngle) == QGLE::quadrant(angle))
correctIntersections.append(pt);
}
return(correctIntersections);
}
bool GLECircle::isInside(QPointF p)
{
QPointF cp = getQtPoint(CentrePoint);
if (QGLE::distance(cp,p) < getQtLength(Radius))
return(true);
else
return(false);
}
bool GLECircle::findScaleOrigin(const QPointF&, QPointF* origin, int handle)
{
if (handle == GLEDrawingArea::TopLeft || handle == GLEDrawingArea::TopRight || handle == GLEDrawingArea::BottomLeft || handle == GLEDrawingArea::BottomRight)
{
*origin = getQtPoint(CentrePoint, true);
return true;
}
return false;
}
int GLECircle::supportedTransformMode()
{
return TransformModeConstrained;
}
void GLECircle::linearTransform(const GLELinearEquation& ex, const GLELinearEquation& ey)
{
// Make sure we have a circumference point at 45 degrees
// QPointF cp = getQtPoint(CentrePoint, true);
// double radius = getQtLength(Radius, true);
// QPointF edgePoint = cp + QPointF(
// radius*cos(QGLE::degreesToRadians(45)),
// radius*sin(QGLE::degreesToRadians(45)));
// It would probably be much more sensible to do this after
// converting it to an ellipse.
pointHash.clear();
double radius = getQtLength(Radius, true);
double fac = ex.getA();
if (fac == 1.0) fac = ey.getA();
setLength(Radius, radius * fac, false);
linearTransformPt(CentrePoint, ex, ey, false);
if (storedPointHash.contains(CircumferencePoint))
{
linearTransformPt(CircumferencePoint, ex, ey, false);
}
updateCircle();
}
void GLECircle::moveBy(QPointF offset)
{
pointHash.clear();
double radius = getQtLength(Radius);
setLength(Radius, radius, false);
// Moves relative to storedPointHash
QPointF pt = getQtPoint(CentrePoint, true);
setPoint(CentrePoint, pt + offset, false);
if (storedPointHash.contains(CircumferencePoint))
{
QPointF pt = getQtPoint(CircumferencePoint, true);
setPoint(CircumferencePoint, pt + offset, false);
}
updateCircle();
}
void GLECircle::rotateBy(double radians)
{
double radius = getQtLength(Radius);
pointHash.clear();
setPoint(Radius, QPointF(radius,0.0));
QPointF c = getQtPoint(CentrePoint, true);
c = QGLE::rotateAboutPoint(c, radians, basePoint);
setPoint(CentrePoint, c);
if (storedPointHash.contains(CircumferencePoint))
{
QPointF pt = getQtPoint(CircumferencePoint, true);
setPoint(CircumferencePoint, QGLE::rotateAboutPoint(pt, radians, basePoint));
}
}
| 29.502262 | 158 | 0.667025 | [
"object"
] |
bd29aea730daa90eef20928725e84e69ae1c0e38 | 1,339 | cpp | C++ | src/audio_analyzer/sound_quality2_preparation.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | 12 | 2021-07-07T14:37:20.000Z | 2022-03-07T16:43:47.000Z | src/audio_analyzer/sound_quality2_preparation.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | null | null | null | src/audio_analyzer/sound_quality2_preparation.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | 3 | 2021-04-03T13:36:02.000Z | 2021-12-28T20:21:10.000Z | #include "gflags/gflags.h"
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/filesystem.hpp>
#include "bakuage/sound_quality2.h"
DECLARE_string(analysis_data_dir);
DECLARE_string(sound_quality2_cache);
DECLARE_string(sound_quality2_cache_archiver);
void PrepareSoundQuality2() {
using boost::filesystem::recursive_directory_iterator;
bakuage::SoundQuality2Calculator calculator;
recursive_directory_iterator last;
std::vector<std::string> paths;
for (recursive_directory_iterator itr(FLAGS_analysis_data_dir); itr != last; ++itr) {
const std::string path = itr->path().string();
if (!bakuage::StrEndsWith(path, ".json")) continue;
paths.emplace_back(path);
}
calculator.PrepareFromPaths(paths.begin(), paths.end());
if (FLAGS_sound_quality2_cache_archiver == "binary") {
std::ofstream ofs(FLAGS_sound_quality2_cache, std::ios::binary);
boost::archive::binary_oarchive oa(ofs);
oa << calculator;
} else if (FLAGS_sound_quality2_cache_archiver == "text") {
std::ofstream ofs(FLAGS_sound_quality2_cache);
boost::archive::text_oarchive oa(ofs);
oa << calculator;
} else {
throw std::logic_error("unknown archive type " + FLAGS_sound_quality2_cache_archiver);
}
}
| 31.880952 | 94 | 0.718447 | [
"vector"
] |
bd4b78ec19bb68fbab199018e2f4f1c45e96b415 | 17,216 | cc | C++ | src/gxf.cc | diekhans/gencode-backmap | dc365a1bf8bd9c0fe2f4ada4116ff2f214e53306 | [
"Apache-2.0"
] | 8 | 2016-06-07T05:05:39.000Z | 2021-02-19T04:52:09.000Z | src/gxf.cc | diekhans/gencode-backmap | dc365a1bf8bd9c0fe2f4ada4116ff2f214e53306 | [
"Apache-2.0"
] | 4 | 2016-05-08T15:11:40.000Z | 2020-11-12T23:59:56.000Z | src/gxf.cc | diekhans/gencode-backmap | dc365a1bf8bd9c0fe2f4ada4116ff2f214e53306 | [
"Apache-2.0"
] | 5 | 2018-02-28T04:50:08.000Z | 2021-12-05T20:31:18.000Z | #include "gxf.hh"
#include "jkinclude.hh"
#include "FIOStream.hh"
#include <typeinfo>
#include <string>
#include <vector>
#include <cassert>
#include "typeOps.hh"
#include <stdexcept>
const string GxfFeature::GENE = "gene";
const string GxfFeature::TRANSCRIPT = "transcript";
const string GxfFeature::EXON = "exon";
const string GxfFeature::CDS = "CDS";
const string GxfFeature::START_CODON = "start_codon";
const string GxfFeature::UTR = "UTR";
const string GxfFeature::FIVE_PRIME_UTR = "five_prime_UTR";
const string GxfFeature::THREE_PRIME_UTR = "three_prime_UTR";
const string GxfFeature::STOP_CODON = "stop_codon";
const string GxfFeature::STOP_CODON_REDEFINED_AS_SELENOCYSTEINE = "stop_codon_redefined_as_selenocysteine";
// standard attribute names
const string GxfFeature::ID_ATTR = "ID";
const string GxfFeature::PARENT_ATTR = "Parent";
const string GxfFeature::GENE_ID_ATTR = "gene_id";
const string GxfFeature::GENE_NAME_ATTR = "gene_name";
const string GxfFeature::GENE_TYPE_ATTR = "gene_type";
const string GxfFeature::GENE_STATUS_ATTR = "gene_status";
const string GxfFeature::GENE_HAVANA_ATTR = "havana_gene";
const string GxfFeature::TRANSCRIPT_ID_ATTR = "transcript_id";
const string GxfFeature::TRANSCRIPT_NAME_ATTR = "transcript_name";
const string GxfFeature::TRANSCRIPT_TYPE_ATTR = "transcript_type";
const string GxfFeature::TRANSCRIPT_STATUS_ATTR = "transcript_status";
const string GxfFeature::TRANSCRIPT_HAVANA_ATTR = "havana_transcript";
const string GxfFeature::EXON_ID_ATTR = "exon_id";
const string GxfFeature::EXON_NUMBER_ATTR = "exon_number";
const string GxfFeature::TAG_ATTR = "tag";
const string GxfFeature::SOURCE_HAVANA = "HAVANA";
const string GxfFeature::SOURCE_ENSEMBL = "ENSEMBL";
const string GxfFeature::PAR_Y_SUFFIX = "_PAR_Y";
/* is a value quotes */
static bool isQuoted(const string& s) {
return ((s.size() > 1) and (s[0] == '"') and (s[s.size()-1] == '"'));
}
/* is a value a integrate or float */
static bool isNumeric(const string& s) {
int dotCount = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '.') {
dotCount++;
} else if (!isdigit(s[i])) {
return false;
}
}
if (dotCount > 1) {
return false;
}
return true;
}
/* strip optional quotes */
static string stripQuotes(const string& s) {
if (isQuoted(s)) {
return s.substr(1, s.size()-2);
} else {
return s;
}
}
/* is this an attribute that must be hacked to be unique in GTF? */
static bool isParIdNonUniqAttr(const string& name) {
return (name == GxfFeature::GENE_ID_ATTR) or (name == GxfFeature::TRANSCRIPT_ID_ATTR);
}
/* Get format from file name, or error */
GxfFormat gxfFormatFromFileName(const string& fileName) {
if (stringEndsWith(fileName, ".gff3") or stringEndsWith(fileName, ".gff3.gz")
or (fileName == "/dev/null")) {
return GFF3_FORMAT;
} else if (stringEndsWith(fileName, ".gtf") or stringEndsWith(fileName, ".gtf.gz")) {
return GTF_FORMAT;
} else if (fileName == "/dev/null") {
return DEV_NULL_FORMAT;
} else {
errAbort(toCharStr("Error: expected file with extension of .gff3, .gff3.gz, .gtf, or .gtf.gz: " + fileName));
return GXF_UNKNOWN_FORMAT;
}
}
/* construct a new feature object */
GxfFeature::GxfFeature(const string& seqid, const string& source, const string& type,
int start, int end, const string& score, const string& strand,
const string& phase, const AttrVals& attrs):
fSeqid(seqid), fSource(source), fType(type),
fStart(start), fEnd(end),
fScore(score), fStrand(strand),
fPhase(phase), fAttrs(attrs) {
assert(strand.size() == 1);
assert(phase.size() == 1);
}
/* return base columns (excluding attributes) as a string */
string GxfFeature::baseColumnsAsString() const {
return fSeqid + "\t" + fSource + "\t" + fType + "\t" + to_string(fStart) + "\t"
+ to_string(fEnd) + "\t" + fScore + "\t" + fStrand + "\t" + fPhase + "\t";
}
/* get the id based on feature type, or empty string if it doesn't have an
* id */
const string& GxfFeature::getTypeId() const {
if (fType == GxfFeature::GENE) {
return getAttrValue(GxfFeature::GENE_ID_ATTR, emptyString);
} else if (fType == GxfFeature::TRANSCRIPT) {
return getAttrValue(GxfFeature::TRANSCRIPT_ID_ATTR, emptyString);
} else if (fType == GxfFeature::EXON) {
return getAttrValue(GxfFeature::EXON_ID_ATTR, emptyString);
} else {
return emptyString;
}
}
/* get the havana id based on feature type, or empty string if it doesn't have an
* id */
const string& GxfFeature::getHavanaTypeId() const {
if (fType == GxfFeature::GENE) {
return getAttrValue(GxfFeature::GENE_HAVANA_ATTR, emptyString);
} else if (fType == GxfFeature::TRANSCRIPT) {
return getAttrValue(GxfFeature::TRANSCRIPT_HAVANA_ATTR, emptyString);
} else {
return emptyString;
}
}
/* get the name based on feature type, or empty string if it doesn't have an
* id */
const string& GxfFeature::getTypeName() const {
if (fType == GxfFeature::GENE) {
return getAttrValue(GxfFeature::GENE_NAME_ATTR, emptyString);
} else if (fType == GxfFeature::TRANSCRIPT) {
return getAttrValue(GxfFeature::TRANSCRIPT_NAME_ATTR, emptyString);
} else {
return emptyString;
}
}
/* get the biotype based on feature type, or empty string if it doesn't have an
* id */
const string& GxfFeature::getTypeBiotype() const {
static const string emptyString;
if (fType == GxfFeature::GENE) {
return getAttrValue(GxfFeature::GENE_TYPE_ATTR, emptyString);
} else if (fType == GxfFeature::TRANSCRIPT) {
return getAttrValue(GxfFeature::TRANSCRIPT_TYPE_ATTR, emptyString);
} else {
return emptyString;
}
}
/* Parse for GFF 3 */
class Gff3Parser: public GxfParser {
private:
/* is this a multi-valued attribute? */
/* parse ID=ENSG00000223972.5 */
static void parseAttr(const string& attrStr,
AttrVals& attrVals) {
size_t i = attrStr.find('=');
if (i == string::npos) {
throw invalid_argument("Invalid GFF3 attribute \"" + attrStr + "\"");
}
string name = attrStr.substr(0,i);
string value = attrStr.substr(i+1);
StringVector values = stringSplit(stripQuotes(value), ',');
AttrVal* attrVal = new AttrVal(name, values[0]);
attrVals.push_back(attrVal);
for (int i = 1; i < values.size(); i++) {
attrVal->addVal(values[i]);
}
}
/* parse: ID=ENSG00000223972.5;gene_id=ENSG00000223972.5 */
static AttrVals parseAttrs(const string& attrsStr) {
AttrVals attrVals;
StringVector parts = stringSplit(attrsStr,';');
// `;' is a separator
for (size_t i = 0; i < parts.size(); i++) {
string part = stringTrim(parts[i]);
if (part.size() > 0) {
parseAttr(part, attrVals);
}
}
return attrVals;
}
public:
/* constructor */
Gff3Parser(const string& fileName):
GxfParser(fileName) {
}
/* get the format being parser */
virtual GxfFormat getFormat() const {
return GFF3_FORMAT;
}
/* parse a feature */
virtual GxfFeature* parseFeature(const StringVector& columns) {
return new GxfFeature(columns[0], columns[1], columns[2],
stringToInt(columns[3]), stringToInt(columns[4]),
columns[5], columns[6], columns[7], parseAttrs(columns[8]));
}
};
/* Parse for GTF */
class GtfParser: public GxfParser {
private:
/* if a value has a non-unique hack, remove it */
static string removeParUniqHack(const string& value) {
if (stringStartsWith(value, "ENSGR") or stringStartsWith(value, "ENSTR")) {
return value.substr(0, 4) + "0" + value.substr(5);
} else if (stringEndsWith(value, GxfFeature::PAR_Y_SUFFIX)) {
return value.substr(0, value.size() - GxfFeature::PAR_Y_SUFFIX.size());
} else {
return value;
}
}
/* parse ID=ENSG00000223972.5 */
static void parseAttr(const string& attrStr,
AttrVals& attrVals) {
size_t i = attrStr.find(' ');
if (i == string::npos) {
throw invalid_argument("Invalid GTF attribute \"" + attrStr + "\"");
}
string name = attrStr.substr(0,i);
string value = stripQuotes(attrStr.substr(i+1));
if (isParIdNonUniqAttr(name)) {
value = removeParUniqHack(value);
}
int idx = attrVals.findIdx(name);
if (idx >= 0) {
attrVals[idx]->addVal(value);
} else {
attrVals.push_back(new AttrVal(name, value));
}
}
/* parse: gene_id "ENSG00000223972.5"; gene_type "transcribed_unprocessed_pseudogene"; */
static AttrVals parseAttrs(const string& attrsStr) {
AttrVals attrVals;
StringVector parts = stringSplit(attrsStr,';');
// last will be empty, since `;' is a terminator
for (size_t i = 0; i < parts.size()-1; i++) {
parseAttr(stringTrim(parts[i]), attrVals);
}
return attrVals;
}
public:
/* constructor */
GtfParser(const string& fileName):
GxfParser(fileName) {
}
/* get the format being parser */
virtual GxfFormat getFormat() const {
return GTF_FORMAT;
}
/* parse a feature */
virtual GxfFeature* parseFeature(const StringVector& columns) {
return new GxfFeature(columns[0], columns[1], columns[2],
stringToInt(columns[3]), stringToInt(columns[4]),
columns[5], columns[6], columns[7], parseAttrs(columns[8]));
}
};
/* split a feature line of GFF3 or GTF */
StringVector GxfParser::splitFeatureLine(const string& line) const {
StringVector columns = stringSplit(line, '\t');
if (columns.size() != 9) {
invalid_argument("invalid row, expected 9 columns: " + line);
}
return columns;
}
/* constructor that opens file, which maybe compressed. */
GxfParser::GxfParser(const string& fileName):
fIn(new FIOStream(fileName)) {
}
/* destructor */
GxfParser::~GxfParser() {
delete fIn;
}
/* Read the next record */
GxfRecord* GxfParser::read() {
string line;
if (not fIn->readLine(line)) {
return NULL;
}
try {
if ((line.size() > 0) and line[0] != '#') {
return parseFeature(splitFeatureLine(line));
} else {
return new GxfLine(line);
}
} catch (exception& e) {
throw runtime_error("Error: " + string(e.what()) + ": " + line);
}
}
/* Read the next record, either queued by push() or from the file , use
* instanceOf to determine the type. Return NULL on EOF.
*/
GxfRecord* GxfParser::next() {
if (not fPending.empty()) {
GxfRecord* rec = fPending.front();
fPending.pop();
return rec;
} else {
return read();
}
}
/* Factory to create a parser. file maybe compressed. If gxfFormat is
* unknown, guess from filename*/
GxfParser *GxfParser::factory(const string& fileName,
GxfFormat gxfFormat) {
if (gxfFormat==GXF_UNKNOWN_FORMAT) {
gxfFormat = gxfFormatFromFileName(fileName);
}
if (gxfFormat == GFF3_FORMAT) {
return new Gff3Parser(fileName);
} else {
return new GtfParser(fileName);
}
}
/* Write for GFF3 */
class Gff3Writer: public GxfWriter {
public:
/* format an attribute */
static string formatAttr(const AttrVal* attrVal) {
string strAttr = attrVal->getName() + "=";
for (int i = 0; i < attrVal->getVals().size(); i++) {
if (i > 0) {
strAttr += ",";
}
strAttr += attrVal->getVals()[i];
}
return strAttr;
}
/* format attributes */
static string formatAttrs(const AttrVals& attrVals) {
string strAttrs;
for (size_t i = 0; i < attrVals.size(); i++) {
if (i > 0) {
strAttrs += ";"; // separator
}
strAttrs += formatAttr(attrVals[i]);
}
return strAttrs;
}
/* constructor */
Gff3Writer(const string& fileName):
GxfWriter(fileName) {
write("##gff-version 3");
}
/* get the format being parser */
virtual GxfFormat getFormat() const {
return GFF3_FORMAT;
}
/* format a feature line */
virtual string formatFeature(const GxfFeature* feature) {
return feature->baseColumnsAsString() + formatAttrs(feature->getAttrs());
}
};
/* Write for GTF */
class GtfWriter: public GxfWriter {
public:
ParIdHackMethod fParIdHackMethod;
/* modify an id in the PAR */
string addParUniqHack(const string& id) const {
if (fParIdHackMethod == PAR_ID_HACK_OLD) {
assert(id[5] == '0');
return id.substr(0, 4) + "R" + id.substr(5);
} else {
return id + "_PAR_Y";
}
}
/* format an attribute */
string formatAttr(const string& name,
const string& val,
bool isParY) const {
// n.b. this is not general, doesn't handle embedded quotes
bool numericAttr = isNumeric(val);
string strAttr = name + " ";
if (!numericAttr) {
strAttr += "\"";
}
if ((!numericAttr) and isParY and isParIdNonUniqAttr(name)) {
strAttr += addParUniqHack(val);
} else {
strAttr += val;
}
if (!numericAttr) {
strAttr += "\"";
}
return strAttr;
}
/* format an attribute and values */
string formatAttr(const AttrVal* attrVal,
bool isParY) const {
string strAttr;
for (int i = 0; i < attrVal->getVals().size(); i++) {
if (i > 0) {
strAttr += " "; // same formatting as GENCODE
}
strAttr += formatAttr(attrVal->getName(), attrVal->getVals()[i], isParY) + ";";
}
return strAttr;
}
/* should this attribute be included */
bool includeAttr(const AttrVal* attrVal) const {
// drop GFF3 linkage attributes
return not ((attrVal->getName() == GxfFeature::ID_ATTR)
or (attrVal->getName() == GxfFeature::PARENT_ATTR)
or (attrVal->getName() == "remap_original_id"));
}
/* format attribute */
string formatAttrs(const AttrVals& attrVals,
bool isParY) const {
string strAttrs;
for (int i = 0; i < attrVals.size(); i++) {
if (includeAttr(attrVals[i])) {
if (strAttrs.size() > 0) {
strAttrs += " "; // same formatting as GENCODE
}
strAttrs += formatAttr(attrVals[i], isParY);
}
}
return strAttrs;
}
/* constructor */
GtfWriter(const string& fileName,
ParIdHackMethod parIdHackMethod):
GxfWriter(fileName),
fParIdHackMethod(parIdHackMethod) {
}
/* get the format being parser */
virtual GxfFormat getFormat() const {
return GTF_FORMAT;
}
/* format a feature line */
virtual string formatFeature(const GxfFeature* feature) {
return feature->baseColumnsAsString() + formatAttrs(feature->getAttrs(), feature->isParY());
}
};
/* constructor that opens file */
GxfWriter::GxfWriter(const string& fileName):
fOut(new FIOStream(fileName, ios::out)) {
}
/* destructor */
GxfWriter::~GxfWriter() {
delete fOut;
}
/* Factory to create a writer. file maybe compressed. If gxfFormat is
* unknown, guess from filename*/
GxfWriter *GxfWriter::factory(const string& fileName,
ParIdHackMethod parIdHackMethod,
GxfFormat gxfFormat) {
if (gxfFormat==GXF_UNKNOWN_FORMAT) {
gxfFormat = gxfFormatFromFileName(fileName);
}
if (gxfFormat == GFF3_FORMAT) {
return new Gff3Writer(fileName);
} else {
return new GtfWriter(fileName, parIdHackMethod);
}
}
/* copy a file to output, normally used for a header */
void GxfWriter::copyFile(const string& inFile) {
FIOStream inFh(inFile);
string line;
while (inFh.readLine(line)) {
write(line);
}
}
/* write one GxF record. */
void GxfWriter::write(const GxfRecord* gxfRecord) {
if (instanceOf(gxfRecord, GxfFeature)) {
*fOut << formatFeature(dynamic_cast<const GxfFeature*>(gxfRecord)) << endl;
} else {
*fOut << gxfRecord->toString() << endl;
}
}
/* write one GxF line. */
void GxfWriter::write(const string& line) {
*fOut << line << endl;
}
/* return feature as a string */
string GxfFeature::toString() const {
// just use GFF3 format, this is for debugging, not output
return baseColumnsAsString() + Gff3Writer::formatAttrs(getAttrs());
}
| 32.05959 | 117 | 0.60316 | [
"object",
"vector"
] |
32e50fb40722b6c7daf38b0c68bd958534840488 | 5,699 | hpp | C++ | measurer/hotspot-measurer/hotspot/src/share/vm/memory/oopFactory.hpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | measurer/hotspot-measurer/hotspot/src/share/vm/memory/oopFactory.hpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | measurer/hotspot-measurer/hotspot/src/share/vm/memory/oopFactory.hpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_MEMORY_OOPFACTORY_HPP
#define SHARE_VM_MEMORY_OOPFACTORY_HPP
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "memory/universe.hpp"
#include "oops/klassOop.hpp"
#include "oops/objArrayKlass.hpp"
#include "oops/oop.hpp"
#include "oops/typeArrayKlass.hpp"
#include "utilities/growableArray.hpp"
// oopFactory is a class used for creating new objects.
class vframeArray;
class oopFactory: AllStatic {
public:
// Basic type leaf array allocation
static typeArrayOop new_boolArray (int length, TRAPS) { return typeArrayKlass::cast(Universe::boolArrayKlassObj ())->allocate(length, CHECK_NULL); }
static typeArrayOop new_charArray (int length, TRAPS) { return typeArrayKlass::cast(Universe::charArrayKlassObj ())->allocate(length, CHECK_NULL); }
static typeArrayOop new_singleArray(int length, TRAPS) { return typeArrayKlass::cast(Universe::singleArrayKlassObj())->allocate(length, CHECK_NULL); }
static typeArrayOop new_doubleArray(int length, TRAPS) { return typeArrayKlass::cast(Universe::doubleArrayKlassObj())->allocate(length, CHECK_NULL); }
static typeArrayOop new_byteArray (int length, TRAPS) { return typeArrayKlass::cast(Universe::byteArrayKlassObj ())->allocate(length, CHECK_NULL); }
static typeArrayOop new_shortArray (int length, TRAPS) { return typeArrayKlass::cast(Universe::shortArrayKlassObj ())->allocate(length, CHECK_NULL); }
static typeArrayOop new_intArray (int length, TRAPS) { return typeArrayKlass::cast(Universe::intArrayKlassObj ())->allocate(length, CHECK_NULL); }
static typeArrayOop new_longArray (int length, TRAPS) { return typeArrayKlass::cast(Universe::longArrayKlassObj ())->allocate(length, CHECK_NULL); }
// create java.lang.Object[]
static objArrayOop new_objectArray(int length, TRAPS) {
return objArrayKlass::
cast(Universe::objectArrayKlassObj())->allocate(length, CHECK_NULL);
}
static typeArrayOop new_charArray (const char* utf8_str, TRAPS);
static typeArrayOop new_permanent_charArray (int length, TRAPS);
static typeArrayOop new_permanent_byteArray (int length, TRAPS); // used for class file structures
static typeArrayOop new_permanent_shortArray(int length, TRAPS); // used for class file structures
static typeArrayOop new_permanent_intArray (int length, TRAPS); // used for class file structures
static typeArrayOop new_typeArray(BasicType type, int length, TRAPS);
// Constant pools
static constantPoolOop new_constantPool (int length,
bool is_conc_safe,
TRAPS);
static constantPoolCacheOop new_constantPoolCache(int length,
TRAPS);
// Instance classes
static klassOop new_instanceKlass(Symbol* name,
int vtable_len, int itable_len,
int static_field_size,
unsigned int nonstatic_oop_map_count,
ReferenceType rt, TRAPS);
// Methods
private:
static constMethodOop new_constMethod(int byte_code_size,
int compressed_line_number_size,
int localvariable_table_length,
int checked_exceptions_length,
bool is_conc_safe,
TRAPS);
public:
// Set is_conc_safe for methods which cannot safely be
// processed by concurrent GC even after the return of
// the method.
static methodOop new_method(int byte_code_size,
AccessFlags access_flags,
int compressed_line_number_size,
int localvariable_table_length,
int checked_exceptions_length,
bool is_conc_safe,
TRAPS);
// Method Data containers
static methodDataOop new_methodData(methodHandle method, TRAPS);
// System object arrays
static objArrayOop new_system_objArray(int length, TRAPS);
// Regular object arrays
static objArrayOop new_objArray(klassOop klass, int length, TRAPS);
// For compiled ICs
static compiledICHolderOop new_compiledICHolder(methodHandle method, KlassHandle klass, TRAPS);
};
#endif // SHARE_VM_MEMORY_OOPFACTORY_HPP
| 49.556522 | 155 | 0.665731 | [
"object"
] |
32e9d2591441903b66ce7e4e23269d813b20c096 | 1,085 | cpp | C++ | aws-cpp-sdk-kafka/source/model/ServerlessClientAuthentication.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-kafka/source/model/ServerlessClientAuthentication.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-kafka/source/model/ServerlessClientAuthentication.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/kafka/model/ServerlessClientAuthentication.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Kafka
{
namespace Model
{
ServerlessClientAuthentication::ServerlessClientAuthentication() :
m_saslHasBeenSet(false)
{
}
ServerlessClientAuthentication::ServerlessClientAuthentication(JsonView jsonValue) :
m_saslHasBeenSet(false)
{
*this = jsonValue;
}
ServerlessClientAuthentication& ServerlessClientAuthentication::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("sasl"))
{
m_sasl = jsonValue.GetObject("sasl");
m_saslHasBeenSet = true;
}
return *this;
}
JsonValue ServerlessClientAuthentication::Jsonize() const
{
JsonValue payload;
if(m_saslHasBeenSet)
{
payload.WithObject("sasl", m_sasl.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace Kafka
} // namespace Aws
| 18.083333 | 94 | 0.742857 | [
"model"
] |
32ea2805e6d5b3a08d7ac1972f60cbf3ad8c238d | 8,928 | cpp | C++ | rootex/core/resource_files/model_resource_file.cpp | LASTEXILE-CH/Rootex | 685b9bb5763bbc35041f3a5f193a43b3156394a6 | [
"MIT"
] | 1 | 2021-03-29T09:46:28.000Z | 2021-03-29T09:46:28.000Z | rootex/core/resource_files/model_resource_file.cpp | LASTEXILE-CH/Rootex | 685b9bb5763bbc35041f3a5f193a43b3156394a6 | [
"MIT"
] | null | null | null | rootex/core/resource_files/model_resource_file.cpp | LASTEXILE-CH/Rootex | 685b9bb5763bbc35041f3a5f193a43b3156394a6 | [
"MIT"
] | null | null | null | #include "model_resource_file.h"
#include "resource_loader.h"
#include "image_resource_file.h"
#include "renderer/material_library.h"
#include "renderer/mesh.h"
#include "renderer/vertex_buffer.h"
#include "renderer/index_buffer.h"
#include "assimp/Importer.hpp"
#include "assimp/postprocess.h"
#include "assimp/scene.h"
#include "meshoptimizer.h"
ModelResourceFile::ModelResourceFile(const FilePath& path)
: ResourceFile(Type::Model, path)
{
reimport();
}
void ModelResourceFile::reimport()
{
ResourceFile::reimport();
Assimp::Importer modelLoader;
const aiScene* scene = modelLoader.ReadFile(
getPath().generic_string(),
aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SplitLargeMeshes | aiProcess_GenBoundingBoxes | aiProcess_OptimizeMeshes | aiProcess_CalcTangentSpace | aiProcess_RemoveComponent | aiProcess_PreTransformVertices);
if (!scene)
{
ERR("Model could not be loaded: " + getPath().generic_string());
ERR("Assimp: " + modelLoader.GetErrorString());
return;
}
m_Meshes.clear();
for (int i = 0; i < scene->mNumMeshes; i++)
{
const aiMesh* mesh = scene->mMeshes[i];
Vector<VertexData> vertices;
vertices.reserve(mesh->mNumVertices);
VertexData vertex;
ZeroMemory(&vertex, sizeof(VertexData));
for (unsigned int v = 0; v < mesh->mNumVertices; v++)
{
vertex.m_Position.x = mesh->mVertices[v].x;
vertex.m_Position.y = mesh->mVertices[v].y;
vertex.m_Position.z = mesh->mVertices[v].z;
if (mesh->mNormals)
{
vertex.m_Normal.x = mesh->mNormals[v].x;
vertex.m_Normal.y = mesh->mNormals[v].y;
vertex.m_Normal.z = mesh->mNormals[v].z;
}
if (mesh->mTextureCoords)
{
if (mesh->mTextureCoords[0])
{
// Assuming the model has texture coordinates and taking only the first texture coordinate in case of multiple texture coordinates
vertex.m_TextureCoord.x = mesh->mTextureCoords[0][v].x;
vertex.m_TextureCoord.y = mesh->mTextureCoords[0][v].y;
}
}
if (mesh->mTangents)
{
vertex.m_Tangent.x = mesh->mTangents[v].x;
vertex.m_Tangent.y = mesh->mTangents[v].y;
vertex.m_Tangent.z = mesh->mTangents[v].z;
}
vertices.push_back(vertex);
}
Vector<unsigned int> indices;
indices.reserve(mesh->mNumFaces);
aiFace* face = nullptr;
for (unsigned int f = 0; f < mesh->mNumFaces; f++)
{
face = &mesh->mFaces[f];
//Model already triangulated by aiProcess_Triangulate so no need to check
indices.push_back(face->mIndices[0]);
indices.push_back(face->mIndices[1]);
indices.push_back(face->mIndices[2]);
}
meshopt_optimizeVertexCache(indices.data(), indices.data(), indices.size(), vertices.size());
Vector<Vector<unsigned int>> lods;
float lodLevels[MAX_LOD_COUNT - 1] = { 0.8f, 0.50f, 0.3f, 0.10f };
for (int i = 0; i < MAX_LOD_COUNT - 1; i++)
{
float threshold = lodLevels[i];
size_t targetIndexCount = indices.size() * threshold;
Vector<unsigned int> lod(indices.size());
float lodError = 0.0f;
size_t finalLODIndexCount = meshopt_simplifySloppy(
&lod[0],
indices.data(),
indices.size(),
&vertices[0].m_Position.x,
vertices.size(),
sizeof(VertexData),
targetIndexCount);
lod.resize(finalLODIndexCount);
lods.push_back(lod);
}
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
aiColor3D color(0.0f, 0.0f, 0.0f);
float alpha = 1.0f;
if (AI_SUCCESS != material->Get(AI_MATKEY_COLOR_DIFFUSE, color))
{
WARN("Material does not have color: " + String(material->GetName().C_Str()));
}
if (AI_SUCCESS != material->Get(AI_MATKEY_OPACITY, alpha))
{
WARN("Material does not have alpha: " + String(material->GetName().C_Str()));
}
Ref<BasicMaterial> extractedMaterial;
String materialPath(material->GetName().C_Str());
if (materialPath == "DefaultMaterial" || materialPath == "None" || materialPath.empty())
{
materialPath = MaterialLibrary::s_DefaultMaterialPath;
}
else
{
materialPath = "game/assets/materials/" + String(material->GetName().C_Str()) + ".rmat";
}
if (OS::IsExists(materialPath))
{
extractedMaterial = std::dynamic_pointer_cast<BasicMaterial>(MaterialLibrary::GetMaterial(materialPath));
}
else
{
MaterialLibrary::CreateNewMaterialFile(materialPath, "BasicMaterial");
extractedMaterial = std::dynamic_pointer_cast<BasicMaterial>(MaterialLibrary::GetMaterial(materialPath));
extractedMaterial->setColor({ color.r, color.g, color.b, alpha });
for (int i = 0; i < material->GetTextureCount(aiTextureType_DIFFUSE); i++)
{
aiString diffuseStr;
material->GetTexture(aiTextureType_DIFFUSE, i, &diffuseStr);
bool isEmbedded = *diffuseStr.C_Str() == '*';
if (!isEmbedded)
{
// Texture is given as a path
String texturePath = diffuseStr.C_Str();
Ref<ImageResourceFile> image = ResourceLoader::CreateImageResourceFile(getPath().parent_path().generic_string() + "/" + texturePath);
if (image)
{
extractedMaterial->setDiffuseTexture(image);
}
else
{
WARN("Could not set material diffuse texture: " + texturePath);
}
}
else
{
WARN("Embedded diffuse texture found in material: " + extractedMaterial->getFullName() + ". Embedded textures are unsupported.");
}
}
for (int i = 0; i < material->GetTextureCount(aiTextureType_NORMALS); i++)
{
aiString normalStr;
material->GetTexture(aiTextureType_NORMALS, i, &normalStr);
bool isEmbedded = *normalStr.C_Str() == '*';
if (isEmbedded)
{
String texturePath = normalStr.C_Str();
Ref<ImageResourceFile> image = ResourceLoader::CreateImageResourceFile(getPath().parent_path().generic_string() + "/" + texturePath);
if (image)
{
extractedMaterial->setNormalTexture(image);
}
else
{
WARN("Could not set material normal map texture: " + texturePath);
}
}
else
{
WARN("Embedded normal texture found in material: " + extractedMaterial->getFullName() + ". Embedded textures are unsupported.");
}
}
for (int i = 0; i < material->GetTextureCount(aiTextureType_SPECULAR); i++)
{
aiString specularStr;
material->GetTexture(aiTextureType_SPECULAR, i, &specularStr);
bool isEmbedded = *specularStr.C_Str() == '*';
if (isEmbedded)
{
String texturePath = specularStr.C_Str();
Ref<ImageResourceFile> image = ResourceLoader::CreateImageResourceFile(getPath().parent_path().generic_string() + "/" + texturePath);
if (image)
{
extractedMaterial->setSpecularTexture(image);
}
else
{
WARN("Could not set material specular map texture: " + texturePath);
}
}
else
{
WARN("Embedded specular texture found in material: " + extractedMaterial->getFullName() + ". Embedded textures are unsupported.");
}
}
for (int i = 0; i < material->GetTextureCount(aiTextureType_LIGHTMAP); i++)
{
aiString lightmapStr;
material->GetTexture(aiTextureType_LIGHTMAP, i, &lightmapStr);
bool isEmbedded = *lightmapStr.C_Str() == '*';
if (isEmbedded)
{
String texturePath = lightmapStr.C_Str();
Ref<ImageResourceFile> image = ResourceLoader::CreateImageResourceFile(getPath().parent_path().generic_string() + "/" + texturePath);
if (image)
{
extractedMaterial->setLightmapTexture(image);
}
else
{
WARN("Could not set material lightmap texture: " + texturePath);
}
}
else
{
WARN("Embedded lightmaptexture found in material: " + extractedMaterial->getFullName() + ". Embedded textures are unsupported.");
}
}
}
Mesh extractedMesh;
extractedMesh.m_VertexBuffer.reset(new VertexBuffer(vertices));
extractedMesh.addLOD(std::make_shared<IndexBuffer>(indices), 1.0f);
for (int i = 0; i < MAX_LOD_COUNT - 1; i++)
{
if (!lods[i].empty())
{
extractedMesh.addLOD(std::make_shared<IndexBuffer>(lods[i]), lodLevels[i]);
}
}
Vector3 max = { mesh->mAABB.mMax.x, mesh->mAABB.mMax.y, mesh->mAABB.mMax.z };
Vector3 min = { mesh->mAABB.mMin.x, mesh->mAABB.mMin.y, mesh->mAABB.mMin.z };
Vector3 center = (max + min) / 2.0f;
extractedMesh.m_BoundingBox.Center = center;
extractedMesh.m_BoundingBox.Extents = (max - min) / 2.0f;
extractedMesh.m_BoundingBox.Extents.x = abs(extractedMesh.m_BoundingBox.Extents.x);
extractedMesh.m_BoundingBox.Extents.y = abs(extractedMesh.m_BoundingBox.Extents.y);
extractedMesh.m_BoundingBox.Extents.z = abs(extractedMesh.m_BoundingBox.Extents.z);
bool found = false;
for (auto& materialModels : getMeshes())
{
if (materialModels.first == extractedMaterial)
{
found = true;
materialModels.second.push_back(extractedMesh);
break;
}
}
if (!found && extractedMaterial)
{
getMeshes().push_back(Pair<Ref<Material>, Vector<Mesh>>(extractedMaterial, { extractedMesh }));
}
}
}
| 30.47099 | 237 | 0.677531 | [
"mesh",
"vector",
"model"
] |
32ed2b38f0781c4228e95b5fba80e120f38a6b98 | 472 | cpp | C++ | cxx-idioms/map_keys_to_vector.cpp | lsix/talks | e8c0d68b87bfd5d587fe7b82d7fa1fde82f27ded | [
"MIT"
] | 8 | 2015-01-28T09:40:45.000Z | 2019-02-27T16:54:28.000Z | cxx-idioms/map_keys_to_vector.cpp | lsix/talks | e8c0d68b87bfd5d587fe7b82d7fa1fde82f27ded | [
"MIT"
] | 2 | 2015-05-02T10:35:19.000Z | 2019-06-14T15:56:00.000Z | cxx-idioms/map_keys_to_vector.cpp | lsix/talks | e8c0d68b87bfd5d587fe7b82d7fa1fde82f27ded | [
"MIT"
] | 6 | 2015-04-21T21:26:02.000Z | 2019-06-13T20:46:01.000Z | #include<iostream>
#include<map>
#include<vector>
#include<algorithm>
int main() {
std::map<int, float> const map{{0,1.},{1,3.}, {2, 9.}};
std::vector<int> keys;
keys.reserve(map.size());
// {{{
std::transform(map.begin(), map.end(),
std::back_inserter(keys),
[](auto&& kv) { return kv.first; }
);
// }}}
std::cout << keys[0] << ' ' << keys[1] << ' ' << keys[2] << std::endl;
return 0;
}
// vim: foldmethod=marker
| 22.47619 | 72 | 0.514831 | [
"vector",
"transform"
] |
32ed367198ce0a654be2f25a07d54ca7e51a0a2c | 731 | hpp | C++ | simulation/extern_include/MatlabCppSharedLib/matlab_application.hpp | seanny1986/gym-aero | bb8e7f299ca83029c300fa85e423be90fc9c11e1 | [
"MIT"
] | 5 | 2018-11-21T11:52:49.000Z | 2021-04-14T03:13:31.000Z | simulation/extern_include/MatlabCppSharedLib/matlab_application.hpp | seanny1986/gym-aero | bb8e7f299ca83029c300fa85e423be90fc9c11e1 | [
"MIT"
] | 3 | 2018-08-24T03:12:36.000Z | 2019-09-29T06:21:32.000Z | simulation/extern_include/MatlabCppSharedLib/matlab_application.hpp | seanny1986/gym-aero | bb8e7f299ca83029c300fa85e423be90fc9c11e1 | [
"MIT"
] | 4 | 2018-08-10T07:02:30.000Z | 2022-03-09T07:20:16.000Z | /* Copyright 2017 The MathWorks, Inc. */
#ifndef MATLAB_APPLICATION_HPP
#define MATLAB_APPLICATION_HPP
#include "cppsharedlib_factory.hpp"
namespace matlab {
namespace cpplib {
class MATLABApplication {
public:
~MATLABApplication();
private:
MATLABApplication(const MATLABApplicationMode mode, const std::vector<std::u16string>& options);
friend std::shared_ptr<MATLABApplication> initMATLABApplication(
const MATLABApplicationMode mode,
const std::vector<std::u16string>& options);
MATLABApplicationMode _mode;
std::vector<std::u16string> _options;
};
}
}
#endif // MATLAB_APPLICATION_HPP
| 27.074074 | 108 | 0.653899 | [
"vector"
] |
32f8c9f9aaa0f27336195008f810e68224023a53 | 9,038 | cpp | C++ | postgres/src/v20170312/model/CreateReadOnlyGroupRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | postgres/src/v20170312/model/CreateReadOnlyGroupRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | postgres/src/v20170312/model/CreateReadOnlyGroupRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* 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 <tencentcloud/postgres/v20170312/model/CreateReadOnlyGroupRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Postgres::V20170312::Model;
using namespace std;
CreateReadOnlyGroupRequest::CreateReadOnlyGroupRequest() :
m_masterDBInstanceIdHasBeenSet(false),
m_nameHasBeenSet(false),
m_projectIdHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_subnetIdHasBeenSet(false),
m_replayLagEliminateHasBeenSet(false),
m_replayLatencyEliminateHasBeenSet(false),
m_maxReplayLagHasBeenSet(false),
m_maxReplayLatencyHasBeenSet(false),
m_minDelayEliminateReserveHasBeenSet(false),
m_securityGroupIdsHasBeenSet(false)
{
}
string CreateReadOnlyGroupRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_masterDBInstanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MasterDBInstanceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_masterDBInstanceId.c_str(), allocator).Move(), allocator);
}
if (m_nameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Name";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator);
}
if (m_projectIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProjectId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_projectId, allocator);
}
if (m_vpcIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VpcId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_vpcId.c_str(), allocator).Move(), allocator);
}
if (m_subnetIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SubnetId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_subnetId.c_str(), allocator).Move(), allocator);
}
if (m_replayLagEliminateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ReplayLagEliminate";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_replayLagEliminate, allocator);
}
if (m_replayLatencyEliminateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ReplayLatencyEliminate";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_replayLatencyEliminate, allocator);
}
if (m_maxReplayLagHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MaxReplayLag";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_maxReplayLag, allocator);
}
if (m_maxReplayLatencyHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MaxReplayLatency";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_maxReplayLatency, allocator);
}
if (m_minDelayEliminateReserveHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MinDelayEliminateReserve";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_minDelayEliminateReserve, allocator);
}
if (m_securityGroupIdsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SecurityGroupIds";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_securityGroupIds.begin(); itr != m_securityGroupIds.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateReadOnlyGroupRequest::GetMasterDBInstanceId() const
{
return m_masterDBInstanceId;
}
void CreateReadOnlyGroupRequest::SetMasterDBInstanceId(const string& _masterDBInstanceId)
{
m_masterDBInstanceId = _masterDBInstanceId;
m_masterDBInstanceIdHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::MasterDBInstanceIdHasBeenSet() const
{
return m_masterDBInstanceIdHasBeenSet;
}
string CreateReadOnlyGroupRequest::GetName() const
{
return m_name;
}
void CreateReadOnlyGroupRequest::SetName(const string& _name)
{
m_name = _name;
m_nameHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::NameHasBeenSet() const
{
return m_nameHasBeenSet;
}
uint64_t CreateReadOnlyGroupRequest::GetProjectId() const
{
return m_projectId;
}
void CreateReadOnlyGroupRequest::SetProjectId(const uint64_t& _projectId)
{
m_projectId = _projectId;
m_projectIdHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::ProjectIdHasBeenSet() const
{
return m_projectIdHasBeenSet;
}
string CreateReadOnlyGroupRequest::GetVpcId() const
{
return m_vpcId;
}
void CreateReadOnlyGroupRequest::SetVpcId(const string& _vpcId)
{
m_vpcId = _vpcId;
m_vpcIdHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::VpcIdHasBeenSet() const
{
return m_vpcIdHasBeenSet;
}
string CreateReadOnlyGroupRequest::GetSubnetId() const
{
return m_subnetId;
}
void CreateReadOnlyGroupRequest::SetSubnetId(const string& _subnetId)
{
m_subnetId = _subnetId;
m_subnetIdHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::SubnetIdHasBeenSet() const
{
return m_subnetIdHasBeenSet;
}
uint64_t CreateReadOnlyGroupRequest::GetReplayLagEliminate() const
{
return m_replayLagEliminate;
}
void CreateReadOnlyGroupRequest::SetReplayLagEliminate(const uint64_t& _replayLagEliminate)
{
m_replayLagEliminate = _replayLagEliminate;
m_replayLagEliminateHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::ReplayLagEliminateHasBeenSet() const
{
return m_replayLagEliminateHasBeenSet;
}
uint64_t CreateReadOnlyGroupRequest::GetReplayLatencyEliminate() const
{
return m_replayLatencyEliminate;
}
void CreateReadOnlyGroupRequest::SetReplayLatencyEliminate(const uint64_t& _replayLatencyEliminate)
{
m_replayLatencyEliminate = _replayLatencyEliminate;
m_replayLatencyEliminateHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::ReplayLatencyEliminateHasBeenSet() const
{
return m_replayLatencyEliminateHasBeenSet;
}
uint64_t CreateReadOnlyGroupRequest::GetMaxReplayLag() const
{
return m_maxReplayLag;
}
void CreateReadOnlyGroupRequest::SetMaxReplayLag(const uint64_t& _maxReplayLag)
{
m_maxReplayLag = _maxReplayLag;
m_maxReplayLagHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::MaxReplayLagHasBeenSet() const
{
return m_maxReplayLagHasBeenSet;
}
uint64_t CreateReadOnlyGroupRequest::GetMaxReplayLatency() const
{
return m_maxReplayLatency;
}
void CreateReadOnlyGroupRequest::SetMaxReplayLatency(const uint64_t& _maxReplayLatency)
{
m_maxReplayLatency = _maxReplayLatency;
m_maxReplayLatencyHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::MaxReplayLatencyHasBeenSet() const
{
return m_maxReplayLatencyHasBeenSet;
}
uint64_t CreateReadOnlyGroupRequest::GetMinDelayEliminateReserve() const
{
return m_minDelayEliminateReserve;
}
void CreateReadOnlyGroupRequest::SetMinDelayEliminateReserve(const uint64_t& _minDelayEliminateReserve)
{
m_minDelayEliminateReserve = _minDelayEliminateReserve;
m_minDelayEliminateReserveHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::MinDelayEliminateReserveHasBeenSet() const
{
return m_minDelayEliminateReserveHasBeenSet;
}
vector<string> CreateReadOnlyGroupRequest::GetSecurityGroupIds() const
{
return m_securityGroupIds;
}
void CreateReadOnlyGroupRequest::SetSecurityGroupIds(const vector<string>& _securityGroupIds)
{
m_securityGroupIds = _securityGroupIds;
m_securityGroupIdsHasBeenSet = true;
}
bool CreateReadOnlyGroupRequest::SecurityGroupIdsHasBeenSet() const
{
return m_securityGroupIdsHasBeenSet;
}
| 27.809231 | 104 | 0.742974 | [
"vector",
"model"
] |
32fd90e688bf808aae9d41cce09009cf9a6304c5 | 1,857 | hpp | C++ | engine/src/engine/gui/Statusbar.hpp | CaptureTheBanana/CaptureTheBanana | 1398bedc80608e502c87b880c5b57d272236f229 | [
"MIT"
] | 1 | 2018-08-14T05:45:29.000Z | 2018-08-14T05:45:29.000Z | engine/src/engine/gui/Statusbar.hpp | CaptureTheBanana/CaptureTheBanana | 1398bedc80608e502c87b880c5b57d272236f229 | [
"MIT"
] | null | null | null | engine/src/engine/gui/Statusbar.hpp | CaptureTheBanana/CaptureTheBanana | 1398bedc80608e502c87b880c5b57d272236f229 | [
"MIT"
] | null | null | null | // This file is part of CaptureTheBanana++.
//
// Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md)
// This file is licensed under the MIT license; see LICENSE file in the root of this
// project for details.
#ifndef ENGINE_GUI_STATUSBAR_HPP
#define ENGINE_GUI_STATUSBAR_HPP
#include <map>
#include <vector>
#include "engine/graphics/Rect.hpp"
#include "engine/graphics/SDLRenderable.hpp"
namespace ctb {
namespace engine {
class Label;
class Player;
/// The in-game GUI for scores, health and more information
class Statusbar : public SDLRenderable {
public:
Statusbar();
/// Renders the status bar
void render() override;
void setupUI();
~Statusbar() override;
private:
/// The width of the combo of one player and the score and health label
static int entryWidth;
/// Set the frame rate for the blinking
void setFPS(int fps);
/// Sets the black rectangle over the current level and make it blink
void updateCurrentLevelRect();
/// All labels
std::vector<Label*> m_labels;
/// Maps the player to his/her score label for easy access
std::map<Player*, Label*> m_scoreLabels;
/// Maps the player to his/her health label for easy access
std::map<Player*, Label*> m_healthLabels;
/// Maps the heart label to the player
std::map<Player*, Label*> m_heartLabels;
/// All rects used for the level indicator
std::vector<Rect*> m_rects;
/// The one rect that causes the blink effekt for the current level
Rect* m_currentLevelRect;
/// Whether to show the rect or not. Used for blinking
bool m_currentLevelRectShow;
/// Ticks count when the last frame was rendered
Uint32 m_lastRenderTicks;
/// Timeout between frames
Uint32 m_frameTimeout;
};
} // namespace engine
} // namespace ctb
#endif
| 24.116883 | 84 | 0.698977 | [
"render",
"vector"
] |
fd041fd60332d1aae29f2fbb3495fe3af56693d4 | 318 | cpp | C++ | STL/algorithm/transform5.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 5 | 2019-09-17T09:12:15.000Z | 2021-05-29T10:54:39.000Z | STL/algorithm/transform5.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | null | null | null | STL/algorithm/transform5.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 2 | 2021-07-26T06:36:12.000Z | 2022-01-23T15:20:30.000Z | // transform.cpp -- use function fo algorithm
#include"iostream"
#include"algorithm"
#include"cctype"
#include"string"
int main(int argc, char *argv[])
{
using namespace std;
string s("hello world");
cout<<s<<endl;
transform(s.begin(), s.end(), s.begin(), toupper);
cout<<s<<endl;
return 0;
} | 19.875 | 54 | 0.641509 | [
"transform"
] |
fd07568fc52e69b812f135ff15aa6ee6ba566f1a | 2,461 | cc | C++ | components/service/ucloud/ivision/src/model/SearchFaceRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | components/service/ucloud/ivision/src/model/SearchFaceRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | components/service/ucloud/ivision/src/model/SearchFaceRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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 <alibabacloud/ivision/model/SearchFaceRequest.h>
using AlibabaCloud::Ivision::Model::SearchFaceRequest;
SearchFaceRequest::SearchFaceRequest() :
RpcServiceRequest("ivision", "2019-03-08", "SearchFace")
{
setMethod(HttpRequest::Method::Get);
}
SearchFaceRequest::~SearchFaceRequest()
{}
std::string SearchFaceRequest::getContent()const
{
return content_;
}
void SearchFaceRequest::setContent(const std::string& content)
{
content_ = content;
setParameter("Content", content);
}
std::string SearchFaceRequest::getDataType()const
{
return dataType_;
}
void SearchFaceRequest::setDataType(const std::string& dataType)
{
dataType_ = dataType;
setParameter("DataType", dataType);
}
float SearchFaceRequest::getProbabilityThreshold()const
{
return probabilityThreshold_;
}
void SearchFaceRequest::setProbabilityThreshold(float probabilityThreshold)
{
probabilityThreshold_ = probabilityThreshold;
setParameter("ProbabilityThreshold", std::to_string(probabilityThreshold));
}
std::string SearchFaceRequest::getShowLog()const
{
return showLog_;
}
void SearchFaceRequest::setShowLog(const std::string& showLog)
{
showLog_ = showLog;
setParameter("ShowLog", showLog);
}
std::string SearchFaceRequest::getGroupId()const
{
return groupId_;
}
void SearchFaceRequest::setGroupId(const std::string& groupId)
{
groupId_ = groupId;
setParameter("GroupId", groupId);
}
int SearchFaceRequest::getCount()const
{
return count_;
}
void SearchFaceRequest::setCount(int count)
{
count_ = count;
setParameter("Count", std::to_string(count));
}
long SearchFaceRequest::getOwnerId()const
{
return ownerId_;
}
void SearchFaceRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
| 23 | 77 | 0.73913 | [
"model"
] |
fd07585f49889788c9fa6937e0f3aba663da95fa | 28,604 | cpp | C++ | framework_c++/jugimap/jmTimelineAnimationInstance.cpp | Jugilus/jugimapAPI | 93fba7827b16169f858f7bd88c87236c5cf27183 | [
"MIT"
] | 8 | 2020-11-23T23:34:39.000Z | 2022-02-23T12:14:02.000Z | framework_c++/jugimap/jmTimelineAnimationInstance.cpp | Jugilus/jugimapAPI | 93fba7827b16169f858f7bd88c87236c5cf27183 | [
"MIT"
] | null | null | null | framework_c++/jugimap/jmTimelineAnimationInstance.cpp | Jugilus/jugimapAPI | 93fba7827b16169f858f7bd88c87236c5cf27183 | [
"MIT"
] | 3 | 2019-12-19T13:44:43.000Z | 2020-05-15T01:02:10.000Z | #include "jmSourceGraphics.h"
#include "jmLayers.h"
#include "jmSprites.h"
#include "jmVectorShapes.h"
#include "jmFrameAnimation.h"
#include "jmUtilities.h"
#include "jmTimelineAnimationInstance.h"
namespace jugimap{
AnimationTrackState::AnimationTrackState(AnimationTrack* _animation, AnimationMemberState *_tAnimationsStatesSet)
{
animationTrack = _animation;
tp = animationTrack->GetTrackParameters();
animationMemberState = _tAnimationsStatesSet;
kind = animationTrack->GetKind();
stateKey = CreateAnimationKey(animationTrack);
disabled = animationTrack->IsDisabled(); // initial disabled
}
AnimationTrackState::~AnimationTrackState()
{
if(stateKey){
delete stateKey;
stateKey = nullptr;
}
if(frameAnimationPlayer){
delete frameAnimationPlayer;
frameAnimationPlayer = nullptr;
}
if(frameAnimationInstances){
for(FrameAnimationInstance* fai : *frameAnimationInstances){
delete fai;
}
delete frameAnimationInstances;
}
if(timelineAnimationPlayer){
delete timelineAnimationPlayer;
timelineAnimationPlayer = nullptr;
}
if(timelineAnimationInstances){
for(TimelineAnimationInstance* tai : *timelineAnimationInstances){
delete tai;
}
delete timelineAnimationInstances;
}
}
AnimationTrackKind AnimationTrackState::GetKind()
{
assert(animationTrack);
return animationTrack->GetKind();
}
int AnimationTrackState::Update(int _animationTime, int _flags)
{
int returnFlag = 0;
assert(stateKey);
//if(animationTrack->IsDisabled()){
if(disabled){
if(frameAnimationPlayer && frameAnimationPlayer->GetState()!=AnimationPlayerState::IDLE){
AnimationInstance *ai = frameAnimationPlayer->GetAnimationInstance(); assert(ai);
ai->ResetAnimatedProperties();
frameAnimationPlayer->Stop();
}else if(timelineAnimationPlayer && timelineAnimationPlayer->GetState()!=AnimationPlayerState::IDLE){
AnimationInstance *ai = timelineAnimationPlayer->GetAnimationInstance(); assert(ai);
ai->ResetAnimatedProperties();
timelineAnimationPlayer->Stop();
}
return returnFlag;
}
SetActiveKeys(_animationTime);
if(activeStartKey && activeEndKey==nullptr){
stateKey->CopyFrom(activeStartKey);
}else if(activeStartKey==nullptr && activeEndKey){
stateKey->CopyFrom(activeEndKey);
}else if(activeStartKey && activeEndKey){
double p = (_animationTime- activeStartKey->GetTime())/double(activeEndKey->GetTime() - activeStartKey->GetTime());
p = activeStartKey->GetEasing().GetValue(p);
stateKey->CopyFrom(activeStartKey, activeEndKey, p);
}else{
return returnFlag;
}
if(animationMemberState==nullptr) return returnFlag; // kind==KeyAnimationKind::CONTROLLER
if (kind==AnimationTrackKind::PATH_MOVEMENT){
if(path && path->GetName()!=tp.pathNameID){
path = nullptr;
}
if(path==nullptr && tp.pathNameID != ""){
//path = CurrentMap->FindVectorShapeOfNameID(dpCurrent.pathNameID);
Map *map = nullptr;
if(animationMemberState->sprite){
map = animationMemberState->sprite->GetLayer()->GetMap();
}else if(animationMemberState->sprites){
map = animationMemberState->sprites->front()->GetLayer()->GetMap();
}
assert(map);
path = FindVectorShapeWithName(map, tp.pathNameID);
}
}else if (kind==AnimationTrackKind::FRAME_CHANGE){
if(sourceObject==nullptr){
FindSourceObject();
}
}else if (kind==AnimationTrackKind::FRAME_ANIMATION){
if(sourceObject==nullptr){
FindSourceObject();
}
if(_flags & AnimationPlayerFlags::SKIP_SUBPLAYER_UPDATING){
if(frameAnimationPlayer && frameAnimationPlayer->GetAnimationInstance()){
frameAnimationPlayer->GetAnimationInstance()->Update(0, _flags);
}
}else{
returnFlag |= ManageSubFrameAnimation();
}
}else if (kind==AnimationTrackKind::TIMELINE_ANIMATION){
if(sourceObject==nullptr){
FindSourceObject();
}
if(_flags & AnimationPlayerFlags::SKIP_SUBPLAYER_UPDATING){
if(timelineAnimationPlayer && timelineAnimationPlayer->GetAnimationInstance()){
timelineAnimationPlayer->GetAnimationInstance()->Update(0, _flags);
//timelineAnimationPlayer->GetMainAnimationInstance()->Update(0);
}
}else{
returnFlag |= ManageSubTimelineAnimation();
}
}else if (kind==AnimationTrackKind::META){
// empty
}
return returnFlag;
}
void AnimationTrackState::SetActiveKeys(int _animationTime)
{
std::vector<AnimationKey*> &keys = animationTrack->GetAnimationKeys();
activeStartKey = nullptr;
activeEndKey = nullptr;
if(keys.empty()) return;
if(keys.size()==1){
activeStartKey = keys[0];
activeEndKey = nullptr;
}else{
if(_animationTime <= keys[0]->GetTime()){
activeStartKey = keys[0];
activeEndKey = nullptr;
}else if(_animationTime >= keys[keys.size()-1]->GetTime()){
activeStartKey = nullptr;
activeEndKey = keys[keys.size()-1];
}else{
for(int i=0; i<keys.size()-1; i++){
if(_animationTime >= keys[i]->GetTime() && _animationTime <= keys[i+1]->GetTime()){
activeStartKey = keys[i];
activeEndKey = keys[i+1];
}
}
}
}
}
int AnimationTrackState::ManageSubTimelineAnimation()
{
int returnFlag = 0;
if(timelineAnimationPlayer==nullptr){
timelineAnimationPlayer = new AnimationQueuePlayer();
FindSourceObject();
//---- create animation instances
timelineAnimationInstances = new std::vector<TimelineAnimationInstance*>();
for(AnimationKey * tak : animationTrack->GetAnimationKeys()){
AKTimelineAnimation * ta = static_cast<AKTimelineAnimation*>(tak);
if(ta->animationName!=""){
if(FindTimelineAnimationInstance(ta->animationName)==nullptr){
CreateAndStoreTimelineAnimationInstance(ta->animationName);
}
}
}
}
AKTimelineAnimation * k = static_cast<AKTimelineAnimation*>(stateKey);
if(k->animationName==""){
int flags = ( k->discardAnimationsQueue)? AnimationPlayerFlags::DISCARD_ANIMATION_QUEUE : 0;
returnFlag |= timelineAnimationPlayer->Play(&dummyNoAnimationInstance, flags);
}else if(timelineAnimationPlayer->GetAnimationInstance()==nullptr ||
timelineAnimationPlayer->GetAnimationInstance()->GetAnimation()->GetName() != k->animationName)
{
TimelineAnimationInstance* ai = FindTimelineAnimationInstance(k->animationName);
if(ai==nullptr){ // this happens in editor when we add keys with new animations, otherwise not
ai = CreateAndStoreTimelineAnimationInstance(k->animationName);
}
assert(ai);
ai->SetCompleteLoops(k->completeLoops);
ai->SetSpeedFactor(k->fSpeed);
int flags = ( k->discardAnimationsQueue)? AnimationPlayerFlags::DISCARD_ANIMATION_QUEUE : 0;
returnFlag |= timelineAnimationPlayer->Play(ai, flags);
}
//----
returnFlag |= timelineAnimationPlayer->Update();
return returnFlag;
}
int AnimationTrackState::ManageSubFrameAnimation()
{
int returnFlag = 0;
if(frameAnimationPlayer==nullptr){
frameAnimationPlayer = new AnimationQueuePlayer();
FindSourceObject();
//---- create animation instances
frameAnimationInstances = new std::vector<FrameAnimationInstance*>();
for(AnimationKey * tak : animationTrack->GetAnimationKeys()){
AKFrameAnimation * ta = static_cast<AKFrameAnimation*>(tak);
if(ta->animationName!=""){
if(FindFrameAnimationInstance(ta->animationName)==nullptr){
CreateAndStoreFrameAnimationInstance(ta->animationName);
}
}
}
}
AKFrameAnimation * k = static_cast<AKFrameAnimation*>(stateKey);
if(k->animationName==""){
frameAnimationPlayer->Stop();
int flags = ( k->discardAnimationsQueue)? AnimationPlayerFlags::DISCARD_ANIMATION_QUEUE : 0;
returnFlag |= frameAnimationPlayer->Play(&dummyNoAnimationInstance, flags);
}else if(frameAnimationPlayer->GetAnimationInstance()==nullptr ||
frameAnimationPlayer->GetAnimationInstance()->GetAnimation()->GetName() != k->animationName)
{
frameAnimationPlayer->Stop();
FrameAnimationInstance * ai = FindFrameAnimationInstance(k->animationName);
if(ai==nullptr){ // this happens in editor when we add keys with new animations, otherwise not
ai = CreateAndStoreFrameAnimationInstance(k->animationName);
}
assert(ai);
ai->SetCompleteLoops(k->completeLoops);
ai->SetSpeedFactor(k->fSpeed);
int flags = ( k->discardAnimationsQueue)? AnimationPlayerFlags::DISCARD_ANIMATION_QUEUE : 0;
returnFlag |= frameAnimationPlayer->Play(ai, flags);
}
returnFlag |= frameAnimationPlayer->Update();
return returnFlag;
}
void AnimationTrackState::FindSourceObject()
{
if(animationMemberState->sprite){
sourceObject = animationMemberState->sprite->GetSourceSprite();
}else if(animationMemberState->sprites){
sourceObject = animationMemberState->sprites->front()->GetSourceSprite();
}
}
Map* AnimationTrackState::FindMap()
{
if(animationMemberState->sprite){
return animationMemberState->sprite->GetLayer()->GetMap();
}else if(animationMemberState->sprites){
return animationMemberState->sprites->front()->GetLayer()->GetMap();
}
return nullptr;
}
TimelineAnimationInstance* AnimationTrackState::FindTimelineAnimationInstance(const std::string& _name)
{
for(TimelineAnimationInstance* tai : *timelineAnimationInstances){
if(tai->GetAnimation()->GetName()==_name){
return tai;
}
}
return nullptr;
}
TimelineAnimationInstance* AnimationTrackState::CreateAndStoreTimelineAnimationInstance(const std::string& _name)
{
//--- find timeline animation
TimelineAnimation * animation = nullptr;
for(int i=0; i<sourceObject->GetTimelineAnimations().size(); i++){
if(sourceObject->GetTimelineAnimations().at(i)->GetName() == _name){
animation = sourceObject->GetTimelineAnimations().at(i);
}
}
TimelineAnimationInstance* animationInstance = nullptr;
if(animation){
// EAnimatedJugiSprites *as = static_cast<EAnimatedJugiSprites *>(animationMemberState->animatedSprites);
if(animationMemberState->sprite){
animationInstance = new TimelineAnimationInstance(animation, animationMemberState->sprite);
}else if(animationMemberState->sprites){
animationInstance = new TimelineAnimationInstance(animation, *animationMemberState->sprites);
}else{
assert(false);
}
timelineAnimationInstances->push_back(animationInstance);
}
return animationInstance;
}
FrameAnimationInstance* AnimationTrackState::FindFrameAnimationInstance(const std::string& _name)
{
for(FrameAnimationInstance* fai : *frameAnimationInstances){
if(fai->GetAnimation()->GetName()==_name){
return fai;
}
}
return nullptr;
}
FrameAnimationInstance* AnimationTrackState::CreateAndStoreFrameAnimationInstance(const std::string& _name)
{
FrameAnimation * animation = nullptr;
for(int i=0; i<sourceObject->GetFrameAnimations().size(); i++){
if(sourceObject->GetFrameAnimations().at(i)->GetName() == _name){
animation = sourceObject->GetFrameAnimations().at(i);
break;
}
}
FrameAnimationInstance* animationInstance = nullptr;
if(animation){
if(animationMemberState->sprite){
animationInstance = new FrameAnimationInstance(animation, animationMemberState->sprite);
}else if(animationMemberState->sprites){
animationInstance = new FrameAnimationInstance(animation, *animationMemberState->sprites);
}
frameAnimationInstances->push_back(animationInstance);
}
return animationInstance;
}
void AnimationTrackState::_ClearLinkPointers(VectorShape *_shape)
{
if(path==_shape){
path = nullptr;
}
}
//============================================================================================================
AnimationMemberState::AnimationMemberState(AnimationMember *_animationMember)
{
animationMember = _animationMember;
for(AnimationTrack *ka : animationMember->GetAnimationTracks()){
if(ka->GetKind()==AnimationTrackKind::META) continue;
animationsTrackStates.push_back(new AnimationTrackState(ka, this));
}
disabled = _animationMember->IsDisabled();
}
AnimationMemberState::~AnimationMemberState()
{
for(AnimationTrackState* kas : animationsTrackStates){
delete kas;
}
animationsTrackStates.clear();
if(sprites){
delete sprites;
}
}
int AnimationMemberState::Update(int msTimePoint, int _flags)
{
int returnFLag = 0;
ap.Reset();
if(disabled){
return returnFLag;
}
for(AnimationTrackState *ats : animationsTrackStates){
returnFLag |= ats->Update(msTimePoint, _flags);
returnFLag |= UpdateAnimatedProperties(*ats);
}
return returnFLag;
}
void AnimationMemberState::ResetAnimatedProperties()
{
ap.Reset();
}
int AnimationMemberState::UpdateAnimatedProperties(AnimationTrackState & _ats)
{
if(_ats.IsDisabled()) return 0;
AnimationTrackKind kind = _ats.GetKind();
AnimationKey *stateKey = _ats.GetStateKey(); assert(stateKey);
AnimationTrackParameters &tp = _ats.GetTrackParameters();
if(kind==AnimationTrackKind::TRANSLATION){
ap.translation += static_cast<AKTranslation*>(stateKey)->position;
ap.changeFlags |= Sprite::Property::POSITION;
}else if (kind==AnimationTrackKind::SCALING){
ap.scale *= static_cast<AKScaling*>(stateKey)->scale;
ap.changeFlags |= Sprite::Property::SCALE;
}else if (kind==AnimationTrackKind::FLIP_HIDE){
ap.hidden = static_cast<AKFlipHide*>(stateKey)->hidden;
ap.flip = static_cast<AKFlipHide*>(stateKey)->flip;
ap.changeFlags |= Sprite::Property::FLIP;
}else if (kind==AnimationTrackKind::ROTATION){
ap.rotation += static_cast<AKRotation*>(stateKey)->rotation;
ap.changeFlags |= Sprite::Property::ROTATION;
}else if (kind==AnimationTrackKind::ALPHA_CHANGE){
ap.alpha *= static_cast<AKAlphaChange*>(stateKey)->alpha;
ap.changeFlags |= Sprite::Property::ALPHA;
}else if (kind==AnimationTrackKind::OVERLAY_COLOR_CHANGE){
/*
ap.shaderBasedProperties.SetKind(ap.shaderBasedProperties.GetKind() | TShaderBasedProperties::kindOVERLAY_COLOR);
ap.shaderBasedProperties.SetBlend(tp.colorBlend);
AKOverlayColorChange* k = static_cast<AKOverlayColorChange*>(stateKey);
ap.shaderBasedProperties.SetRGB(k->color.r * 255, k->color.g*255, k->color.b*255);
ap.shaderBasedProperties.SetAlpha(k->color.a);
*/
AKOverlayColorChange* k = static_cast<AKOverlayColorChange*>(stateKey);
ap.colorOverlayBlend = tp.colorBlend;
ap.colorOverlayRGBA.Set(k->color.r * 255, k->color.g*255, k->color.b*255, k->color.a*255);
ap.changeFlags |= Sprite::Property::OVERLAY_COLOR;
}else if (kind==AnimationTrackKind::PATH_MOVEMENT){
VectorShape* path = _ats.GetPath();
if(path){
AKPathMovement* k = static_cast<AKPathMovement*>(stateKey);
//----
float p = k->relDistance;
if(path->IsClosed() && tp.reverseDirectionOnClosedShape){
p = 1.0f - p;
}
p += tp.pathRelDistanceOffset;
if(p > 1.0f){
p = p - 1.0f;
}
//----
Vec2f pathPoint;
if(tp.pathDirectionOrientation){
float directionAngle = 0;
pathPoint = path->GetPathPoint(p, directionAngle);
ap.rotation -= directionAngle;
ap.changeFlags |= Sprite::Property::ROTATION;
}else{
pathPoint = path->GetPathPoint(p);
}
//---
//Vec2f pathStartPoint(path->Points[0].x, path->Points[0].y); //
Vec2f pathStartPoint = path->GetPath().front();
//Vec2f posPathAni(pathPoint.x - GetX(), pathPoint.y - GetY());
Vec2f posPathAni = pathPoint - pathStartPoint;
//if(path->GetName()=="pathSprity"){
// DbgOutput("p:"+std::to_string(p)+ " pathPoint x:" + std::to_string(pathPoint.x) + " y:" + std::to_string(pathPoint.y));
//}
ap.translation += posPathAni;
ap.changeFlags |= Sprite::Property::POSITION;
}
}else if (kind==AnimationTrackKind::FRAME_CHANGE){
SourceSprite *sourceObject = nullptr;
if(sprite){
sourceObject = sprite->GetSourceSprite();
}else if(sprites){
sourceObject = sprites->front()->GetSourceSprite();
}
AKFrameChange* k = static_cast<AKFrameChange*>(stateKey);
if(k->frameImageIndex>=0 && k->frameImageIndex< sourceObject->GetGraphicItems().size()){
k->animationFrame.texture = sourceObject->GetGraphicItems()[k->frameImageIndex];
ap.graphicItem = sourceObject->GetGraphicItems()[k->frameImageIndex];
ap.changeFlags |= Sprite::Property::TEXTURE;
}
}
if(ap.changeFlags!=0){
return AnimationPlayerFlags::ANIMATED_PROPERTIES_CHANGED;
}
return 0;
}
void AnimationMemberState::ResetSpritesAnimatedProperties()
{
if(sprite){
sprite->ResetAnimatedProperties();
}else if(sprites){
for(Sprite *o : *sprites){
o->ResetAnimatedProperties();
}
}
}
void AnimationMemberState::UpdateAnimatedSprites()
{
if(sprite){
sprite->AppendAnimatedProperties(ap);
}else if(sprites){
for(Sprite *o : *sprites){
o->AppendAnimatedProperties(ap);
}
}
//---
for(AnimationTrackState *ats : animationsTrackStates){
if(ats->GetFrameAnimationPlayer()){
if(ats->GetFrameAnimationPlayer()->GetAnimationInstance()){
ats->GetFrameAnimationPlayer()->GetAnimationInstance()->UpdateAnimatedSprites(false);
}
}else if(ats->GetTimelineAnimationQueuePlayer()){
if(ats->GetTimelineAnimationQueuePlayer()->GetAnimationInstance()){
ats->GetTimelineAnimationQueuePlayer()->GetAnimationInstance()->UpdateAnimatedSprites(false);
}
}
}
}
void AnimationMemberState::StopSubPlayers()
{
for(AnimationTrackState *ats : animationsTrackStates){
if(ats->GetFrameAnimationPlayer()){
ats->GetFrameAnimationPlayer()->Stop();
}else if(ats->GetTimelineAnimationQueuePlayer()){
ats->GetTimelineAnimationQueuePlayer()->Stop();
}
}
}
void AnimationMemberState::PauseSubPlayers()
{
for(AnimationTrackState *ats : animationsTrackStates){
if(ats->GetFrameAnimationPlayer()){
ats->GetFrameAnimationPlayer()->Pause();
}else if(ats->GetTimelineAnimationQueuePlayer()){
ats->GetTimelineAnimationQueuePlayer()->Pause();
}
}
}
void AnimationMemberState::ResumeSubPlayers()
{
for(AnimationTrackState *ats : animationsTrackStates){
if(ats->GetFrameAnimationPlayer()){
ats->GetFrameAnimationPlayer()->Resume();
}else if(ats->GetTimelineAnimationQueuePlayer()){
ats->GetTimelineAnimationQueuePlayer()->Resume();
}
}
}
//============================================================================================================
TimelineAnimationInstance::TimelineAnimationInstance(TimelineAnimation *_timelineAnimation, Sprite *_sprite)
{
assert(_timelineAnimation->GetSourceSprite()==_sprite->GetSourceSprite());
kind = AnimationKind::TIMELINE_ANIMATION;
animation = _timelineAnimation;
bp = animation->GetBaseParameters();
//--- create instances of member animations
for(AnimationMember *kas : _timelineAnimation->GetAnimationMembers()){
animationsMemberStates.push_back(new AnimationMemberState(kas));
animationsMemberStates.back()->animationInstance = this;
}
if(_timelineAnimation->GetMetaAnimationTrack()){
metaAnimationTrackState = new AnimationTrackState(_timelineAnimation->GetMetaAnimationTrack(), nullptr);
}
//--- set root member
if(animationsMemberStates.empty()==false){ // root sprite
animationsMemberStates.front()->sprite = _sprite;
_sprite->CreateAnimatedPropertiesIfNone();
}
//--- set child members
if(animationsMemberStates.size()>1){ // child sprites
//assert(_sprite->GetSourceSprite()->GetSourceComposedSprite());
assert(_sprite->GetKind()==SpriteKind::COMPOSED);
//----
std::vector<std::vector<Sprite*>>childrenPerNameID;
GatherSpritesWithSetNameID(static_cast<ComposedSprite*>(_sprite), childrenPerNameID);
//zbrani children so lahko isti objekti (blade) kar moram popraviti
for(int i=1; i<animationsMemberStates.size(); i++){
AnimationMemberState* ams = animationsMemberStates[i];
for(std::vector<Sprite*>& childSprites : childrenPerNameID){
assert(childSprites.empty()==false);
if(childSprites.front()->GetName() == ams->animationMember->GetNameID()){
if(childSprites.size()==1){
ams->sprite = childSprites.front();
ams->sprite->CreateAnimatedPropertiesIfNone();
}else if(childSprites.size()>1){
ams->sprites = new std::vector<Sprite*>();
*ams->sprites = childSprites;
for(Sprite*o : *ams->sprites){
o->CreateAnimatedPropertiesIfNone();
}
}
break;
}
}
}
}
}
TimelineAnimationInstance::TimelineAnimationInstance(TimelineAnimation *_timelineAnimation, std::vector<Sprite*>&_sprites)
{
assert(_sprites.empty()==false);
for(Sprite *o : _sprites){
assert(_timelineAnimation->GetSourceSprite()==o->GetSourceSprite());
}
kind = AnimationKind::TIMELINE_ANIMATION;
animation = _timelineAnimation;
bp = animation->GetBaseParameters();
//--- create instances of member animations
for(AnimationMember *kas : _timelineAnimation->GetAnimationMembers()){
animationsMemberStates.push_back(new AnimationMemberState(kas));
animationsMemberStates.back()->animationInstance = this;
}
if(_timelineAnimation->GetMetaAnimationTrack()){
metaAnimationTrackState = new AnimationTrackState(_timelineAnimation->GetMetaAnimationTrack(), nullptr);
}
//--- set root members
if(animationsMemberStates.empty()==false){
animationsMemberStates.front()->sprites = new std::vector<Sprite*>();
*animationsMemberStates.front()->sprites = _sprites;
for(Sprite*o : _sprites){
o->CreateAnimatedPropertiesIfNone();
}
}
//--- set child members
if(animationsMemberStates.size()>1){
//----
std::vector<std::vector<Sprite*>>childrenPerNameID;
for(Sprite* s : _sprites){
assert(s->GetKind()==SpriteKind::COMPOSED);
GatherSpritesWithSetNameID(static_cast<ComposedSprite*>(s), childrenPerNameID);
}
for(int i=1; i<animationsMemberStates.size(); i++){
AnimationMemberState* ams = animationsMemberStates[i];
for(std::vector<Sprite*>& childSprites : childrenPerNameID){
assert(childSprites.empty()==false);
if(childSprites.front()->GetName() == ams->animationMember->GetNameID()){
if(childSprites.size()==1){
ams->sprite = childSprites.front();
ams->sprite->CreateAnimatedPropertiesIfNone();
}else if(childSprites.size()>1){
ams->sprites = new std::vector<Sprite*>();
*ams->sprites = childSprites;
for(Sprite*o : *ams->sprites){
o->CreateAnimatedPropertiesIfNone();
}
}
break;
}
}
}
}
}
TimelineAnimationInstance::~TimelineAnimationInstance()
{
for(AnimationMemberState *kads : animationsMemberStates){
delete kads;
}
animationsMemberStates.clear();
if(metaAnimationTrackState){
delete metaAnimationTrackState;
}
}
void TimelineAnimationInstance::UpdateAnimatedSprites(bool _resetSpriteAnimatedProperties)
{
if(_resetSpriteAnimatedProperties){
// We reset only for root sprites as any child sprites are also affected in the proccess !!!
animationsMemberStates.front()->ResetSpritesAnimatedProperties();
}
for(AnimationMemberState* set : animationsMemberStates){
set->UpdateAnimatedSprites();
}
}
int TimelineAnimationInstance::Update(int msTimePoint, int _flags)
{
int returnFlag = 0;
for(AnimationMemberState* set : animationsMemberStates){
returnFlag |= set->Update(msTimePoint, _flags);
}
//----
if(metaAnimationTrackState){
metaAnimationTrackState->Update(msTimePoint, _flags);
}
return returnFlag;
}
void TimelineAnimationInstance::ResetAnimatedProperties()
{
for(AnimationMemberState* set : animationsMemberStates){
set->ResetAnimatedProperties();
}
}
void TimelineAnimationInstance::StopSubPlayers()
{
for(AnimationMemberState* kads : animationsMemberStates){
kads->StopSubPlayers();
}
}
void TimelineAnimationInstance::PauseSubPlayers()
{
for(AnimationMemberState* kads : animationsMemberStates){
kads->PauseSubPlayers();
}
}
void TimelineAnimationInstance::ResumeSubPlayers()
{
for(AnimationMemberState* kads : animationsMemberStates){
kads->ResumeSubPlayers();
}
}
void TimelineAnimationInstance::ClearLinkPointers(VectorShape* _shape)
{
for(AnimationMemberState* kads : animationsMemberStates){
for(AnimationTrackState *kad : kads->animationsTrackStates){
kad->_ClearLinkPointers(_shape);
}
}
}
AnimationMemberState* TimelineAnimationInstance::FindAnimationMemberState(AnimationMember* _animationMember)
{
for(AnimationMemberState* set : animationsMemberStates){
if(set->GetAnimationMember() ==_animationMember){
return set;
}
}
return nullptr;
}
AnimationTrackState* TimelineAnimationInstance::FindAnimationTrackState(AnimationTrackKind _animationTrackKind, const std::string &_memberName)
{
for(AnimationMemberState* set : animationsMemberStates){
if(set->GetAnimationMember()->GetNameID()==_memberName){
for(AnimationTrackState *tas : set->GetAnimationTrackStates()){
if(tas->GetKind()==_animationTrackKind){
return tas;
}
}
}
}
return nullptr;
}
AnimationTrackState* TimelineAnimationInstance::FindAnimationTrackState(AnimationTrack *_animationTrack)
{
for(AnimationMemberState* set : animationsMemberStates){
for(AnimationTrackState *tas : set->GetAnimationTrackStates()){
if(tas->GetAnimationTrack() == _animationTrack){
return tas;
}
}
}
return nullptr;
}
}
| 27.241905 | 143 | 0.633897 | [
"vector"
] |
fd07c1505e19665d752596909767fb3d9b73efe9 | 12,855 | cpp | C++ | SRC/system_of_eqn/linearSOE/sparseGEN/PFEMSolver_LumpM.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | 8 | 2019-03-05T16:25:10.000Z | 2020-04-17T14:12:03.000Z | SRC/system_of_eqn/linearSOE/sparseGEN/PFEMSolver_LumpM.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | null | null | null | SRC/system_of_eqn/linearSOE/sparseGEN/PFEMSolver_LumpM.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | 3 | 2019-09-21T03:11:11.000Z | 2020-01-19T07:29:37.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision$
// $Date$
// $URL$
// Written: Minjie
// Created: May 22 2018
#include "PFEMSolver_LumpM.h"
#include "PFEMLinSOE.h"
#include <iostream>
#include <cmath>
#include <Timer.h>
#include <elementAPI.h>
void* OPS_PFEMSolver_LumpM()
{
bool once = false;
if (OPS_GetNumRemainingInputArgs() > 0) {
const char* opt = OPS_GetString();
if (strcmp(opt, "-once") == 0) {
once = true;
}
}
PFEMSolver_LumpM* theSolver = new PFEMSolver_LumpM(once);
return new PFEMLinSOE(*theSolver);
}
PFEMSolver_LumpM::PFEMSolver_LumpM(bool once)
:PFEMSolver(), MSym(0), MNum(0), LSym(0), LNum(0), theSOE(0),
numonce(once), factored(false)
{
}
PFEMSolver_LumpM::~PFEMSolver_LumpM()
{
if (MSym != 0) {
umfpack_di_free_symbolic(&MSym);
}
if (LSym != 0) {
umfpack_di_free_symbolic(&LSym);
}
if (MNum != 0) {
umfpack_di_free_numeric(&MNum);
}
if (LNum != 0) {
umfpack_di_free_numeric(&LNum);
}
}
int PFEMSolver_LumpM::setSize()
{
// reorder rows
cs* M = theSOE->M;
cs* Gft = theSOE->Gft;
cs* Git = theSOE->Git;
cs* L = theSOE->L;
cs* mats[4] = {M,Gft,Git,L};
for (int i=0; i<4; i++) {
cs* mat = mats[i];
for (int j=0; j<mat->n; j++) {
ID col(0, mat->p[j+1]-mat->p[j]);
for (int k=mat->p[j]; k<mat->p[j+1]; k++) {
col.insert(mat->i[k]);
}
int index = 0;
for (int k=mat->p[j]; k<mat->p[j+1]; k++) {
mat->i[k] = col[index++];
}
}
}
// set default control parameters
umfpack_di_defaults(Control);
Control[UMFPACK_PIVOT_TOLERANCE] = 1.0;
// clear
if (MSym != 0) {
umfpack_di_free_symbolic(&MSym);
MSym = 0;
}
if (LSym != 0) {
umfpack_di_free_symbolic(&LSym);
LSym = 0;
}
return 0;
}
int
PFEMSolver_LumpM::solve()
{
Timer timer;
timer.start();
cs* M = theSOE->M;
cs* Gft = theSOE->Gft;
cs* Git = theSOE->Git;
cs* L = theSOE->L;
Vector& Mf = theSOE->Mf;
Vector& X = theSOE->X;
Vector& B = theSOE->B;
ID& dofType = theSOE->dofType;
ID& dofID = theSOE->dofID;
int Msize = M->n;
int Isize = Git->n;
int Ssize = Msize-Isize;
int Fsize = Mf.Size();
int Psize = L->n;
int size = X.Size();
// check MNum
if (LSym != 0) {
umfpack_di_free_symbolic(&LSym);
LSym = 0;
}
if (!numonce && MNum!=0) {
umfpack_di_free_numeric(&MNum);
MNum = 0;
}
// check LNum
if (!numonce && LNum!=0) {
umfpack_di_free_numeric(&LNum);
LNum = 0;
}
// symbolic analysis of M
if (MSym==0 && Msize>0) {
int* Mp = M->p;
int* Mi = M->i;
double* Mx = M->x;
int status = umfpack_di_symbolic(Msize,Msize,Mp,Mi,Mx,&MSym,Control,Info);
// check error
if (status!=UMFPACK_OK) {
opserr<<"WARNING: symbolic analysis of M returns ";
opserr<<status<<" -- PFEMSolver_LumpM::solve\n";
return -1;
}
}
// Numerical factorization of M
if (MNum==0 && Msize>0) {
// numerical analysis
int* Mp = M->p;
int* Mi = M->i;
double* Mx = M->x;
int status = umfpack_di_numeric(Mp,Mi,Mx,MSym,&MNum,Control,Info);
// check error
if (status!=UMFPACK_OK) {
opserr<<"WARNING: numeric analysis of M returns ";
opserr<<status<<" -- PFEMSolver_LumpM::solve\n";
return -1;
}
}
timer.pause();
opserr<<"factorization time of M = "<<timer.getReal()<<"\n";
timer.start();
// structure and interface velocity predictor : deltaV1 = M^{-1} * rsi
Vector deltaV1(Msize);
if(Msize > 0) {
// rsi
for(int i=0; i<size; i++) { // row
int rowtype = dofType(i); // row type
int rowid = dofID(i); // row id
if(rowtype == 2) {
deltaV1(rowid+Ssize) = B(i); // ri
} else if(rowtype == 0) {
deltaV1(rowid) = B(i); // rs
}
}
// opserr<<"ri = "<<ri.Norm()<<"\n";
// opserr<<"rs = "<<rs.Norm()<<"\n";
// M^{-1}*rsi
Vector x(Msize);
double* deltaV1_ptr = &deltaV1(0);
double* x_ptr = &x(0);
int* Ap = M->p;
int* Ai = M->i;
double* Ax = M->x;
int status = umfpack_di_solve(UMFPACK_A,Ap,Ai,Ax,x_ptr,deltaV1_ptr,MNum,Control,Info);
deltaV1 = x;
// check error
if (status!=UMFPACK_OK) {
opserr<<"WARNING: solving M returns "<<status<<" -- PFEMSolver_LumpM::solve\n";
return -1;
}
}
// fluid velocity predictor: deltaVf1 = Mf^{-1} * rf
Vector deltaVf1(Fsize);
if(Fsize > 0) {
// rf
for(int i=0; i<size; i++) { // row
int rowtype = dofType(i); // row type
int rowid = dofID(i); // row id
if(rowtype == 1) {
if(Mf(rowid) == 0) {
opserr<<"WANING: Zero Mf at location "<<rowid<<" ";
opserr<<" - PFEMLinSOE::solve()\n";
return -1;
}
deltaVf1(rowid) = B(i)/Mf(rowid); // rf
}
}
}
timer.pause();
// opserr<<"dV1 = "<<deltaV1.Norm()<<"\n";
// opserr<<"dVf1 = "<<deltaVf1.Norm()<<"\n";
opserr<<"predictor time = "<<timer.getReal()<<"\n";
timer.start();
// Mi
Vector Mi(Isize);
for(int j=Ssize; j<Msize; j++) {
for(int k=M->p[j]; k<M->p[j+1]; k++) {
Mi(j-Ssize) += M->x[k];
}
}
// Gi, Gf
cs* Gi = cs_transpose(Git, 1);
cs* Gf = cs_transpose(Gft, 1);
if(Fsize > 0) {
for(int j=0; j<Psize; j++) {
for(int k=Gf->p[j]; k<Gf->p[j+1]; k++) {
int i = Gf->i[k];
double& x = Gf->x[k];
x /= Mf(i);
}
}
}
if(Isize > 0) {
for(int j=0; j<Psize; j++) {
for(int k=Gi->p[j]; k<Gi->p[j+1]; k++) {
int i = Gi->i[k];
double& x = Gi->x[k];
x /= Mi(i);
}
}
}
timer.pause();
opserr<<"Mi,Gi,Gf time = "<<timer.getReal()<<"\n";
timer.start();
// fluid pressure
Vector deltaP(Psize);
if (Psize > 0) {
double* deltaP_ptr = &deltaP(0);
// GfT*Mf^{-1}*Gf+GiT*Mi^{-1}*Gi
cs* S = 0;
if (Fsize > 0) {
cs* Lf = cs_multiply(Gft,Gf);
S = cs_add(Lf,L,1.0,1.0);
cs_spfree(Lf);
}
if (Isize > 0) {
cs* Li = cs_multiply(Git,Gi);
if (S == 0) {
S = cs_add(Li,L,1.0,1.0);
} else {
cs* temp2 = cs_add(Li,S,1.0,1.0);
cs_spfree(S);
S = temp2;
}
cs_spfree(Li);
}
if (S == 0) {
opserr<<"WARNING: S=L -- PFEMSolver_LumpM::solve\n";
return -1;
}
int* Sp = S->p;
int* Si = S->i;
double* Sx = S->x;
for (int j=0; j<Psize; j++) {
ID col(0, Sp[j+1]-Sp[j]);
Vector colval(Sp[j+1]-Sp[j]);
ID col0(colval.Size());
int index = 0;
for (int k=Sp[j]; k<Sp[j+1]; k++) {
col.insert(Si[k]);
col0(index) = Si[k];
colval(index++) = Sx[k];
}
index = 0;
for (int k=Sp[j]; k<Sp[j+1]; k++) {
Si[k] = col[index++];
Sx[k] = colval(col0.getLocation(Si[k]));
}
}
// Gft*deltaVf1
if(Fsize > 0) {
double* deltaVf1_ptr = &deltaVf1(0);
cs_gaxpy(Gft, deltaVf1_ptr, deltaP_ptr);
}
// Git*deltaVi1
if(Isize > 0) {
double* deltaVi1_ptr = &deltaV1(0) + Ssize;
cs_gaxpy(Git, deltaVi1_ptr, deltaP_ptr);
}
// rp-Git*deltaVi1-Gft*deltaVf1
for(int i=0; i<size; i++) { // row
int rowtype = dofType(i); // row type
int rowid = dofID(i); // row id
if(rowtype == 3) { // pressure
deltaP(rowid) = B(i) - deltaP(rowid);
}
}
timer.pause();
opserr<<"matrix time for L = "<<timer.getReal()<<"\n";
timer.start();
// symbolic analysis of L
if (LSym == 0) {
int status = umfpack_di_symbolic(Psize,Psize,Sp,Si,Sx,&LSym,Control,Info);
// check error
if (status!=UMFPACK_OK) {
opserr<<"WARNING: symbolic analysis of L returns ";
opserr<<status<<" -- PFEMSolver_LumpM::solve\n";
opserr<<"UMFPACK_ERROR_n_nonpositive = "<<UMFPACK_ERROR_n_nonpositive<<"\n";
opserr<<"UMFPACK_ERROR_invalid_matrix = "<<UMFPACK_ERROR_invalid_matrix<<"\n";
opserr<<"UMFPACK_ERROR_out_of_memory = "<<UMFPACK_ERROR_out_of_memory<<"\n";
opserr<<"UMFPACK_ERROR_argument_missing = "<<UMFPACK_ERROR_argument_missing<<"\n";
opserr<<"UMFPACK_ERROR_internal_error = "<<UMFPACK_ERROR_internal_error<<"\n";
return -1;
}
}
timer.pause();
opserr<<"Symbolic time for L = "<<timer.getReal()<<"\n";
timer.start();
// numerical analysis of L
if (LNum == 0) {
int status = umfpack_di_numeric(Sp,Si,Sx,LSym,&LNum,Control,Info);
// check error
if (status!=UMFPACK_OK) {
opserr<<"WARNING: numeric analysis of L returns ";
opserr<<status<<" -- PFEMSolver_LumpM::solve\n";
return -1;
}
}
timer.pause();
opserr<<"Numerical time for L = "<<timer.getReal()<<"\n";
timer.start();
// L^{-1}*rp
Vector x(Psize);
double* x_ptr = &x(0);
int* Ap = S->p;
int* Ai = S->i;
double* Ax = S->x;
int status = umfpack_di_solve(UMFPACK_A,Ap,Ai,Ax,x_ptr,deltaP_ptr,LNum,Control,Info);
deltaP = x;
// check error
if (status!=UMFPACK_OK) {
opserr<<"WARNING: solving L returns "<<status<<" -- PFEMSolver_LumpM::solve\n";
return -1;
}
cs_spfree(S);
}
timer.pause();
// opserr<<"deltaP = "<<deltaP.Norm()<<"\n";
opserr<<"pressure time = "<<timer.getReal()<<"\n";
// structural and interface velocity corrector
cs_spfree(Gi);
Gi = cs_transpose(Git, 1);
Vector deltaV(Msize);
if (Isize > 0 && Psize > 0) {
double* deltaV_ptr = &deltaV(0);
double* deltaP_ptr = &deltaP(0);
// Gi*deltaP
cs_gaxpy(Gi, deltaP_ptr, deltaV_ptr+Ssize);
// solve
Vector x(Msize);
double* x_ptr = &x(0);
int* Ap = M->p;
int* Ai = M->i;
double* Ax = M->x;
int status = umfpack_di_solve(UMFPACK_A,Ap,Ai,Ax,x_ptr,deltaV_ptr,MNum,Control,Info);
deltaV = x;
// check error
if (status!=UMFPACK_OK) {
opserr<<"WARNING: solving M returns "<<status<<" -- PFEMSolver_LumpM::solve\n";
return -1;
}
}
deltaV += deltaV1;
// fluid velocity corrector
Vector deltaVf = deltaVf1;
if (Fsize > 0 && Psize > 0) {
double* deltaVf_ptr = &deltaVf(0);
double* deltaP_ptr = &deltaP(0);
// Vf1+Gf*deltaP
cs_gaxpy(Gf, deltaP_ptr, deltaVf_ptr);
}
timer.pause();
opserr<<"corrector time = "<<timer.getReal()<<"\n";
timer.start();
// copy to X
X.Zero();
for(int i=0; i<size; i++) { // row
int rowtype = dofType(i); // row type
int rowid = dofID(i);
if(rowtype == 0) {
X(i) = deltaV(rowid);
} else if(rowtype == 2) {
X(i) = deltaV(rowid+Ssize);
} else if(rowtype == 1) {
X(i) = deltaVf(rowid);
} else if(rowtype == 3) {
X(i) = deltaP(rowid);
}
}
// opserr<<"dvi = "<<dvi.Norm()<<"\n";
// timer.pause();
// opserr<<"solving time for PFEMSolver_LumpM = "<<timer.getReal()<<"\n";
cs_spfree(Gi);
cs_spfree(Gf);
return 0;
}
int
PFEMSolver_LumpM::sendSelf(int cTag, Channel &theChannel)
{
// nothing to do
return 0;
}
int
PFEMSolver_LumpM::recvSelf(int ctag,
Channel &theChannel,
FEM_ObjectBroker &theBroker)
{
// nothing to do
return 0;
}
int
PFEMSolver_LumpM::setLinearSOE(PFEMLinSOE& theSOE)
{
this->theSOE = &theSOE;
return 0;
}
| 25.205882 | 87 | 0.511319 | [
"vector"
] |
fd084bfcec3c8cba4fad35dc92bf8f202be86b68 | 9,158 | hpp | C++ | include/mbedTLScpp/TlsConfig.hpp | zhenghaven/mbedTLScpp | 9921ce81d5ee0102fc3f4a8ee3a6b7e80d0f1cd3 | [
"MIT"
] | null | null | null | include/mbedTLScpp/TlsConfig.hpp | zhenghaven/mbedTLScpp | 9921ce81d5ee0102fc3f4a8ee3a6b7e80d0f1cd3 | [
"MIT"
] | null | null | null | include/mbedTLScpp/TlsConfig.hpp | zhenghaven/mbedTLScpp | 9921ce81d5ee0102fc3f4a8ee3a6b7e80d0f1cd3 | [
"MIT"
] | null | null | null | #pragma once
#include "ObjectBase.hpp"
#include <mbedtls/ssl.h>
#include "Common.hpp"
#include "Exceptions.hpp"
#include "DefaultRbg.hpp"
#include "X509Cert.hpp"
#include "X509Crl.hpp"
#include "TlsSessTktMgrIntf.hpp"
#include "PKey.hpp"
#ifndef MBEDTLSCPP_CUSTOMIZED_NAMESPACE
namespace mbedTLScpp
#else
namespace MBEDTLSCPP_CUSTOMIZED_NAMESPACE
#endif
{
/**
* @brief TLS Config object allocator.
*
*/
struct TlsConfObjAllocator : DefaultAllocBase
{
typedef mbedtls_ssl_config CObjType;
using DefaultAllocBase::NewObject;
using DefaultAllocBase::DelObject;
static void Init(CObjType* ptr)
{
return mbedtls_ssl_config_init(ptr);
}
static void Free(CObjType* ptr) noexcept
{
return mbedtls_ssl_config_free(ptr);
}
};
/**
* @brief TLS Config object trait.
*
*/
using DefaultTlsConfObjTrait = ObjTraitBase<TlsConfObjAllocator,
false,
false>;
class TlsConfig : public ObjectBase<DefaultTlsConfObjTrait>
{
public: // Static members:
using TlsConfObjTrait = DefaultTlsConfObjTrait;
using _Base = ObjectBase<TlsConfObjTrait>;
/**
* @brief Certificate verify call back function that is given to the mbed TLS's certificate
* verification function call.
*
* @param [in,out] inst The pointer to 'this instance'. Must be not null.
* @param [in,out] cert The pointer to MbedTLS's certificate. Must be not null.
* @param depth The depth of current verification along the certificate chain.
* @param [in,out] flag The flag of verification result. Please refer to MbedTLS's API for details.
*
* @return The verification error code return.
*/
static int CertVerifyCallBack(void* inst, mbedtls_x509_crt* cert, int depth, uint32_t* flag) noexcept
{
if (inst == nullptr ||
cert == nullptr ||
flag == nullptr)
{
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
try
{
return static_cast<TlsConfig*>(inst)->CustomVerifyCert(*cert, depth, *flag);
}
catch (const mbedTLSRuntimeError& e)
{
return e.GetErrorCode();
}
catch (...)
{
return MBEDTLS_ERR_X509_FATAL_ERROR;
}
}
public:
/**
* \brief Default constructor that will create and initialize an TLS
* configuration.
*
* \param isStream True if transport layer is stream (TLS), false
* if not (DTLS).
* \param isServer Is this the server side?
* \param vrfyPeer Do we want to verify the peer?
* \param preset The preset. Please refer to mbedTLS
* mbedtls_ssl_config_defaults.
* \param ca The CA. Can be \c nullptr if we don't verify peer.
* \param crl Certificate Revocation List (Optional).
* \param cert The certificate of this side (Optional). If it's
* not nullptr, the private key will be required.
* \param prvKey The private key of this side. Required if cert is
* not \c nullptr .
* \param ticketMgr Manager for TLS ticket (Optional).
* \param rand The Random Bit Generator.
*/
TlsConfig(
bool isStream, bool isServer, bool vrfyPeer,
int preset,
std::shared_ptr<const X509Cert> ca,
std::shared_ptr<const X509Crl> crl,
std::shared_ptr<const X509Cert> cert,
std::shared_ptr<const PKeyBase<> > prvKey,
std::shared_ptr<TlsSessTktMgrIntf > ticketMgr,
std::unique_ptr<RbgInterface> rand = Internal::make_unique<DefaultRbg>()) :
_Base::ObjectBase(),
m_ca(ca),
m_crl(crl),
m_cert(cert),
m_prvKey(prvKey),
m_ticketMgr(ticketMgr),
m_rand(std::move(rand))
{
mbedtls_ssl_conf_rng(NonVirtualGet(), &RbgInterface::CallBack, m_rand.get());
mbedtls_ssl_conf_verify(NonVirtualGet(), &TlsConfig::CertVerifyCallBack, this);
mbedtls_ssl_conf_session_tickets(NonVirtualGet(), MBEDTLS_SSL_SESSION_TICKETS_ENABLED);
if (m_ticketMgr != nullptr)
{
mbedtls_ssl_conf_session_tickets_cb(NonVirtualGet(),
&TlsSessTktMgrIntf::Write,
&TlsSessTktMgrIntf::Parse,
m_ticketMgr.get());
}
int endpoint = isServer ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT;
MBEDTLSCPP_MAKE_C_FUNC_CALL(
TlsConfig::TlsConfig,
mbedtls_ssl_config_defaults,
NonVirtualGet(), endpoint,
isStream ? MBEDTLS_SSL_TRANSPORT_STREAM : MBEDTLS_SSL_TRANSPORT_DATAGRAM,
preset
);
if (m_cert != nullptr)
{
if (m_prvKey == nullptr)
{
throw InvalidArgumentException("TlsConfig::TlsConfig - Private key or is required for this TLS config.");
}
m_prvKey->NullCheck();
m_cert->NullCheck();
MBEDTLSCPP_MAKE_C_FUNC_CALL(
TlsConfig::TlsConfig,
mbedtls_ssl_conf_own_cert,
NonVirtualGet(),
m_cert->MutableGet(),
m_prvKey->MutableGet()
);
}
if (vrfyPeer)
{
if (m_ca == nullptr)
{
throw InvalidArgumentException("TlsConfig::TlsConfig - CA's certificate is required for this TLS config.");
}
m_ca->NullCheck();
mbedtls_x509_crl* crlPtr = nullptr;
if (m_crl != nullptr)
{
m_crl->NullCheck();
crlPtr = m_crl->MutableGet();
}
mbedtls_ssl_conf_ca_chain(NonVirtualGet(), m_ca->MutableGet(), crlPtr);
mbedtls_ssl_conf_authmode(NonVirtualGet(), MBEDTLS_SSL_VERIFY_REQUIRED);
}
else
{
mbedtls_ssl_conf_authmode(NonVirtualGet(), MBEDTLS_SSL_VERIFY_NONE);
}
}
/**
* @brief Move Constructor. The `rhs` will be empty/null afterwards.
*
* @exception None No exception thrown
* @param rhs The other TlsConfig instance.
*/
TlsConfig(TlsConfig&& rhs) noexcept :
_Base::ObjectBase(std::forward<_Base>(rhs)), //noexcept
m_rand(std::move(rhs.m_rand)), //noexcept
m_ca(std::move(rhs.m_ca)), //noexcept
m_crl(std::move(rhs.m_crl)), //noexcept
m_cert(std::move(rhs.m_cert)), //noexcept
m_prvKey(std::move(rhs.m_prvKey)), //noexcept
m_ticketMgr(std::move(rhs.m_ticketMgr)) //noexcept
{
if (NonVirtualGet() != nullptr)
{
mbedtls_ssl_conf_verify(NonVirtualGet(), &TlsConfig::CertVerifyCallBack, this);
}
}
TlsConfig(const TlsConfig& rhs) = delete;
virtual ~TlsConfig()
{}
/**
* @brief Move assignment. The `rhs` will be empty/null afterwards.
*
* @exception None No exception thrown
* @param rhs The other TlsConfig instance.
* @return TlsConfig& A reference to this instance.
*/
TlsConfig& operator=(TlsConfig&& rhs) noexcept
{
_Base::operator=(std::forward<_Base>(rhs)); //noexcept
if (this != &rhs)
{
m_rand = std::move(rhs.m_rand); //noexcept
m_ca = std::move(rhs.m_ca); //noexcept
m_crl = std::move(rhs.m_crl); //noexcept
m_cert = std::move(rhs.m_cert); //noexcept
m_prvKey = std::move(rhs.m_prvKey); //noexcept
m_ticketMgr = std::move(rhs.m_ticketMgr); //noexcept
if (Get() != nullptr)
{
mbedtls_ssl_conf_verify(Get(), &TlsConfig::CertVerifyCallBack, this);
}
}
return *this;
}
TlsConfig& operator=(const TlsConfig& other) = delete;
/**
* @brief Check if the current instance is holding a null pointer for
* the mbedTLS object. If so, exception will be thrown. Helper
* function to be called before accessing the mbedTLS object.
*
* @exception InvalidObjectException Thrown when the current instance is
* holding a null pointer for the C mbed TLS
* object.
*/
virtual void NullCheck() const
{
_Base::NullCheck(MBEDTLSCPP_CLASS_NAME_STR(TlsConfig));
}
virtual bool IsNull() const noexcept override
{
return _Base::IsNull() ||
(m_rand == nullptr) ||
(m_prvKey == nullptr);
}
using _Base::NullCheck;
using _Base::Get;
using _Base::NonVirtualGet;
using _Base::Swap;
/**
* \brief Verify the certificate with customized verification process.
* The certificate should already be verified by the standard process,
* and then call this function.
* Usually this is called by mbed TLS's callback.
* Note: this function and any underlying calls may throw
* exceptions, but, they will be caught by the static callback
* function (i.e. CertVerifyCallBack), and return an error code
* instead.
*
* \param [in,out] cert The certificate.
* \param depth The depth of current verification along the certificate chain.
* \param [in,out] flag The flag of verification result. Please refer to MbedTLS's API for
* details.
*
* \return The verification error code return.
*/
virtual int CustomVerifyCert(mbedtls_x509_crt& cert, int depth, uint32_t& flag) const
{
// The default behavior is to keep the flag untouched and directly return success.
return MBEDTLS_EXIT_SUCCESS;
}
private:
std::unique_ptr<RbgInterface> m_rand;
std::shared_ptr<const X509Cert> m_ca;
std::shared_ptr<const X509Crl> m_crl;
std::shared_ptr<const X509Cert> m_cert;
std::shared_ptr<const PKeyBase<> > m_prvKey;
std::shared_ptr<TlsSessTktMgrIntf > m_ticketMgr;
};
}
| 29.733766 | 112 | 0.661607 | [
"object"
] |
fd0a2a0fb3af415eec85154007e3e33f4018ba07 | 2,711 | cpp | C++ | Source/SystemQOR/MSWindows/WinQAPI/src/User32/WinQAuthorization.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/SystemQOR/MSWindows/WinQAPI/src/User32/WinQAuthorization.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/SystemQOR/MSWindows/WinQAPI/src/User32/WinQAuthorization.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //WinQAuthorization.cpp
// Copyright Querysoft Limited 2013
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//Authorization functions
#include "WinQAPI/User32.h"
#include "../Source/SystemQOR/MSWindows/WinQAPI/include/ReturnCheck.h"
//--------------------------------------------------------------------------------
namespace nsWinQAPI
{
//--------------------------------------------------------------------------------
BOOL CUser32::GetUserObjectSecurity( HANDLE hObj, PSECURITY_INFORMATION pSIRequested, PSECURITY_DESCRIPTOR pSD, DWORD nLength, LPDWORD lpnLengthNeeded )
{
_WINQ_FCONTEXT( "CUser32::GetUserObjectSecurity" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( GetUserObjectSecurity );
bResult = Call< BOOL, HANDLE, PSECURITY_INFORMATION, PSECURITY_DESCRIPTOR, DWORD, LPDWORD >( pFunc, hObj, pSIRequested, pSD, nLength, lpnLengthNeeded );
return bResult;
}
//--------------------------------------------------------------------------------
BOOL CUser32::SetUserObjectSecurity( HANDLE hObj, PSECURITY_INFORMATION pSIRequested, PSECURITY_DESCRIPTOR pSID )
{
_WINQ_FCONTEXT( "CUser32::SetUserObjectSecurity" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( SetUserObjectSecurity );
bResult = Call< BOOL, HANDLE, PSECURITY_INFORMATION, PSECURITY_DESCRIPTOR >( pFunc, hObj, pSIRequested, pSID );
return bResult;
}
}//nsWinQAPI
| 47.561404 | 154 | 0.703062 | [
"object"
] |
fd12770b8dfe59fcd124d55881e7d2be6c09090f | 166,821 | cpp | C++ | src/gap_util.cpp | fishlist/linear | e7a19ea372b70e40d636ddec8150ee482e297169 | [
"BSD-3-Clause"
] | null | null | null | src/gap_util.cpp | fishlist/linear | e7a19ea372b70e40d636ddec8150ee482e297169 | [
"BSD-3-Clause"
] | null | null | null | src/gap_util.cpp | fishlist/linear | e7a19ea372b70e40d636ddec8150ee482e297169 | [
"BSD-3-Clause"
] | null | null | null | #include <utility>
#include <seqan/align.h>
#include "base.h"
#include "shape_extend.h"
#include "cords.h"
#include "gap_util.h"
/*=============================================
= Global Variables =
=============================================*/
int editDist(String<Dna5> & seq1, String<Dna5> seq2, uint64_t str1, uint64_t str2)
{
//seqan::Score<int16_t, seqan::Simple> scoreAffine(2, -2, -1, -4);
//typedef Align<String<Dna5>, ArrayGaps> TAlign;
//TAlign align;
//resize(rows(align), 2);
//assignSource(row(align, 0), infix(seq1, str1, str1 + 96));
//assignSource(row(align, 1), infix(seq2, str2, str2 + 96));
String<Dna5> tmp1 = infix(seq1, str1, str1 + 96);
String<Dna5> tmp2 = infix(seq2, str2, str2 + 96);
// return globalAlignmentScore (tmp1, tmp2, MyersBitVector());
unsigned score = 0; //globalAlignmentScore (tmp1, tmp2, scoreAffine);
return score;
}
GapParms::GapParms(float err_rate) : //estimated err_rate
//global
thd_err(err_rate),
chn_score1(1, 50, &getGapAnchorsChainScore),
chn_score2(1, 0, &getGapBlocksChainScore2),
chn_ext_clip_metric1(1, 0, &getExtendClipScore),
direction(0),
int_precision(10000), //convert float to int to avoid float division, precision : 10^-4
thd_tile_size(96),
thd_ecr_shape_len(3),
thd_ecr_reject_da(20),
f_rfts_clip(1),
thd_accept_score(32),
f_me_map_extend(0),
thd_me_reject_gap(200), //~192 = 96 x 2
thd_ctfcs_accept_score(32),
thd_ctfcs_pattern_in_window(1),
f_gmsa_direction(0),
thd_gmsa_d_anchor_rate(0.1), //max(ins_rate, del_rate)
thd_cts_major_limit(1),
thd_ctfas2_connect_danchor(50),
thd_ctfas2_connect_dy_dx(150),
f_eis_raw_clip(1),
f_eis_raw_clip_ins(1),
thd_eis_shape_len(9),
thd_eis_step1(5),
thd_eis_step2(1),
thd_dcgx_window_size(5),
thd_dcgx_Xdrop_peak(125), //kmer size, step of kmer, err_rate related.
thd_dcgx_Xdrop_sum(60*thd_dcgx_window_size), //kmer size, step, err_rate related.
thd_tts_overlap_size (thd_tile_size * 0.85),
thd_tts_gap_size (100),
thd_smcn_danchor(12), //kmer size and step of kmer, err_rate related.
thd_dcomx_err_dx(25),
thd_dcomx_err_dy(25),
thd_eicos_clip_dxy(30), //given k=5,step1=3,step2=1, 99% distance < 30 (test dataset GIAB)
thd_eicos_window_size(8), //[weakly] @thd_etfas_shape_len, step1, step2 related.
thd_eicos_f_as_ins(true),
thd_etfas_shape_len(5),// gap_parms.thd_ecr_shape_len;
thd_etfas_step1(3),
thd_etfas_step2(1),
//mapGap_
thd_mg1_danc_indel(80),
thd_max_extend2(5000)
{
clipChainParms(5, 0.1);
}
//todo::fill in the parms
void GapParms::clipChainParms(int shape_len, float thd_err_rate)
{
unused(shape_len);
thd_ccps_window_size = 5;
//if (thd_err_rate > 0.20)
//{
//}
//else if (thd_err_rate >=0.15 && thd_err_rate < 0.17)
//{
//}
//else //regarded as err = 0.1
//{
thd_ccps_clip_min = std::min(thd_err_rate, float(0.1)) * int_precision;
thd_ccps_clip_init = thd_err_rate * int_precision;
thd_ccps_clip1_upper = 8 * int_precision;
thd_ccps_clip2_lower = 12 * int_precision;
//}
}
void GapParms::printParms(std::string header)
{
dout << header
<< thd_err
<< thd_gap_len_min
<< "\n";
}
/*
* NOTE! the following parameters are correlated.
* Change them carefully
*/
int const g_thd_anchor = 6;
float const g_thd_anchor_density = 0.03;
float const g_thd_error_percent = 0.2;
//----------------------------------------
///c_ functions to clip breakpoints by counting kmers
const unsigned c_shape_len = 8; //anchor shape
const unsigned c_shape_len2 = 4; //base-level clipping shape
const unsigned c_shape_len3 = 4; //base-level clipping gap shape
/**
* Operations of coordinates of ClipRecords
* Based on struct Tile
* end[1]|..cord: end = 0 none empty; else empty
*/
uint64_t EmptyClipConst = (~0) & ((1ULL << 50) - 1);
uint64_t getClipStr(String<uint64_t> & clips, int i)
{
if (i << 1 < (int)length(clips)){
return clips[i << 1];
}
else{
return 0;
}
}
uint64_t getClipEnd(String<uint64_t> & clips, int i)
{
return i << 1 < (int)length(clips) - 1 ? clips[(i << 1) + 1] : 0;
}
int getClipsLen(String<uint64_t> & clips)
{
return length(clips) >> 1;
}
void insertClipStr(String<uint64_t> & clips, uint64_t clip)
{
if (length(clips) >> 1 << 1 != length(clips))
{
appendValue (clips, EmptyClipConst);
back(clips) &= ~(1023ULL << 50);
}
appendValue(clips, clip);
}
void insertClipEnd(String<uint64_t> & clips, uint64_t clip)
{
if (length(clips) >> 1 << 1 == length(clips))
{
appendValue (clips, EmptyClipConst);
set_cord_id (back(clips), get_cord_id(clip));
}
appendValue (clips, clip);
}
bool isClipEmpty(uint64_t clip) //NOTE: clip is the tile structure.
{
return (clip & ((1ULL << 50) - 1)) == EmptyClipConst;
}
int isClipTowardsLeft (int clip_direction)
{
return clip_direction <= 0;
}
int isClipTowardsRight (int clip_direction)
{
return clip_direction >= 0;
}
/*
* String of SV types
*/
int insertSVType(String<int> & sv_types, int type)
{
appendValue (sv_types, type);
return 0;
}
int getSVType (String<int> & sv_types, int i)
{
return sv_types[i];
}
int print_clips_gvf_(StringSet<String<uint64_t> > & clips,
StringSet<CharString> & readsId,
StringSet<CharString> & genomesId,
std::ofstream & of)
//std::string outputPrefix)
{
//std::string file_path = outputPrefix + ".gvf";
//of.open(toCString(file_path));
of << "##gvf-version 1.10\n";
std::string source = ".";
std::string type = ".";
for (unsigned i = 0; i < length(clips); i++)
{
for (unsigned j = 0; j < (unsigned)getClipsLen(clips[i]); j++)
{
uint64_t clip_str = getClipStr(clips[i], j);
uint64_t clip_end = getClipEnd(clips[i], j);
uint64_t cord_str1 = get_cord_x(clip_str);
uint64_t cord_str2 = get_cord_y(clip_str);
uint64_t cord_end1 = get_cord_x(clip_end);
uint64_t cord_end2 = get_cord_y(clip_end);
char strand = !(get_cord_strand(clip_str))?'+':'-';
CharString genomeId = genomesId[get_cord_id(clips[i][j])];
of << genomeId << "\t"
<< source << "\t"
<< type << "\t";
if (!isClipEmpty(clip_str))
{
of << cord_str1 << "\t";
}
else
{
of << ".\t";
}
if (!isClipEmpty(clip_end))
{
of << cord_end1 << "\t";
}
else
{
of << ".\t";
}
of << "readStrand=" << strand << ";";
of << "readId=" << readsId[i] << ";";
if (isClipEmpty(clip_str))
{
of << "read_clip_str=.;";
}
else
{
of << "read_clip_str=" << cord_str2 <<";";
}
if (isClipEmpty(clip_end))
{
of << "read_clip_end=.;";
}
else
{
of << "read_clip_end=" << cord_end2 << ";";
}
of << "\n";
}
}
return 0;
}
//======= End of interface function =======*//
/**
* Struct Tile : Cord
* tile_sign[2]|strand[1]|tileEnd[1](cordEnd)|x[40]|y[20]
* tile_sign:=1 start, 2 end, 0 body;
* 0-61 bits same as the Format::Cord
*/
struct TileBase
{
uint64_t const xBitLen = 40;
uint64_t const yBitLen = 20;
uint64_t const strandBit = 61;
uint64_t const xmask = (1ULL << xBitLen) - 1;
uint64_t const ymask = (1ULL << yBitLen) - 1;
uint64_t const sgnBit_str = 1ULL << 62;
uint64_t const sgnBit_end = 2ULL << 62;
}_defaultTileBase;
struct Tile
{
uint64_t getX (uint64_t val,
uint64_t const & bit = _defaultTileBase.yBitLen,
uint64_t const & mask = _defaultTileBase.xmask)
{
return (val >> bit) & mask;
}
uint64_t getY (uint64_t val,
uint64_t const & mask = _defaultTileBase.ymask)
{
return val & mask;
}
uint64_t makeValue(uint64_t x, uint64_t y, uint64_t const & bit = _defaultTileBase.yBitLen)
{
return (x << bit) + y;
}
uint16_t getStrand (uint64_t val,
uint64_t bit = _defaultTileBase.strandBit)
{
return (val >> bit) & 1;
}
void setStrand(uint64_t &val, uint64_t bit = _defaultTileBase.strandBit)
{
val |= (1ULL << bit);
}
void setTileEnd(uint64_t & val,
uint64_t bit = _defaultTileBase.sgnBit_end)
{
val |= bit;
}
void setTileStart(uint64_t & val, uint64_t bit = _defaultTileBase.sgnBit_str)
{
val |= bit;
}
uint64_t isTileEnd(uint64_t & val, uint64_t bit = _defaultTileBase.sgnBit_end)
{
return val & bit;
}
bool isTileStart(uint64_t & val, uint64_t bit = _defaultTileBase.sgnBit_str)
{
return val & bit;
}
bool isTileBody (uint64_t & val)
{
return !isTileStart(val) && !isTileEnd(val);
}
void removeTileSgnStart(uint64_t & val, uint64_t bit = ~_defaultTileBase.sgnBit_str)
{
val &= bit;
}
void removeTileSgnEnd(uint64_t & val, uint64_t bit = ~_defaultTileBase.sgnBit_end)
{
val &= bit;
}
void removeTileSgn(uint64_t & val,
uint64_t bit = ~(_defaultTileBase.sgnBit_str | _defaultTileBase.sgnBit_end))
{
val &= bit;
}
void copyTileSgn(uint64_t tile1, uint64_t & tile2,
uint64_t bit = _defaultTileBase.sgnBit_str | _defaultTileBase.sgnBit_end)
{
tile2 = (tile1 & bit) | (tile2 & (~bit));
}
}_defaultTile;
/*
* shortcut to get max overlap(y cord) between the given gap and those in the gaps list
* @gapsy: list of gaps(y cord)
* @str_y, @end_y: start and end of the gap
*/
int64_t _getMaxGapsyOverlap(String<UPair> & gapsy, uint64_t gap_str, uint64_t gap_end)
{
int64_t overlap = 0;
int64_t gap_stry = get_cord_y(gap_str);
int64_t gap_endy = get_cord_y(gap_end);
for (unsigned i = 0 ; i < length(gapsy); i++)
{
int64_t ystr = gapsy[i].first;
int64_t yend = gapsy[i].second;
if (gap_stry >= ystr && gap_stry <= yend)
{
return std::min(gap_endy, yend) - gap_stry;
}
else if (gap_endy >= ystr && gap_endy <= yend)
{
return gap_endy - std::max(gap_stry, ystr);
}
overlap = 0;
}
return overlap;
}
/*
* Update value while keep the original sign bit
*/
void _updateCordsStrEndValue(String<uint64_t> & cords_str,
String<uint64_t> & cords_end,
unsigned i,
uint64_t cord1,
uint64_t cord2,
uint64_t thd_tile_size)
{
if (empty(cords_end))
{
resize (cords_end, length(cords_str));
for (unsigned i = 0; i < length(cords_str); i++)
{
cords_end[i] = shift_cord (cords_str[i], thd_tile_size, thd_tile_size);
}
}
set_cord_xy (cords_str[i], get_cord_x(cord1), get_cord_y(cord1));
set_cord_xy (cords_end[i], get_cord_x(cord2), get_cord_y(cord2));
}
inline uint64_t get_tile_strand (uint64_t val)
{
return _defaultTile.getStrand(val);
}
inline void set_tile_end (uint64_t & val)
{
_defaultTile.setTileEnd(val);
}
void set_tile_start (uint64_t & val)
{
_defaultTile.setTileStart(val);
}
void remove_tile_sgn (uint64_t & val)
{
_defaultTile.removeTileSgn(val);
}
void copy_tile_sgn (uint64_t tile1, uint64_t & tile2)
{
_defaultTile.copyTileSgn(tile1, tile2);
}
void remove_tile_sgn_start(uint64_t &val)
{
_defaultTile.removeTileSgnStart(val);
}
void remove_tile_sgn_end(uint64_t & val)
{
_defaultTile.removeTileSgnEnd(val);
}
bool is_tile_start(uint64_t val)
{
return _defaultTile.isTileStart(val);
}
uint64_t is_tile_end(uint64_t val)
{
return _defaultTile.isTileEnd(val);
}
bool is_tile_body(uint64_t val)
{
return _defaultTile.isTileBody(val);
}
uint64_t shift_tile(uint64_t const & val, int64_t x, int64_t y)
{
return shift_cord (val, x, y);
}
uint64_t get_tile_x (uint64_t val)
{
return get_cord_x(val);
}
uint64_t get_tile_y (uint64_t val)
{
return get_cord_y(val);
}
uint64_t get_tile_id(uint64_t val)
{
return get_cord_id(val);
}
uint64_t create_tile (uint64_t id, uint64_t cordx, uint64_t cordy, uint64_t strand)
{
return create_cord(id, cordx, cordy, strand);
}
void set_tile_strand(uint64_t & val)
{
_defaultTile.setStrand(val);
}
void g_print_tile (uint64_t tile, CharString str)
{
std::cout << str << " "
<< get_cord_id(tile) << " "
<< get_cord_strand(tile) << " "
<< get_cord_x(tile) << " "
<< get_cord_y(tile) << " "
<< get_cord_x(tile) - get_cord_y (tile) << "\n";
}
void g_print_tiles_(String<uint64_t> & tiles, CharString str)
{
for (unsigned i = 0; i < length(tiles); i++)
{
std::cout << i << " ";
g_print_tile (tiles[i], str);
if (is_tile_end(tiles[i]) || i == length(tiles) - 1)
{
std::cout << str << "end\n\n";
}
}
}
/*=============================================
= Index free Map and clip =
=============================================*/
/**
* Part 2
* NOTE: index free mapping for gaps
*/
/**
* g_hs_anchor: N/A[13]|strand[1]|anchorX[30]|cord_y[20]
* @strand := shape strand of kmer in genome ^ shape strand of kmer in read
* While the kmers are always picked up from the genome and read rather than
* the reverse complement of the read.
* This is different from anchors used in chainning.
* @anchor := n/a[..]|strand[1]|anchorX[30]
* @anchorX = x - y + g_hs_anchor_zero. g_hs_anchor_zero to restrict @anchorX > 0.
(bits overflow otherwise) such that -g_hs_anchor_zero <= x - y < g_hs_anchor_zero
*/
uint64_t const g_hs_anchor_mask1 = (1ULL << 20) - 1;
uint64_t const g_hs_anchor_mask1_ = ~ g_hs_anchor_mask1;
uint64_t const g_hs_anchor_mask3 = (1ULL << 30) - 1;
uint64_t const g_hs_anchor_mask5 = (1ULL << 31) - 1;
uint64_t const g_hs_anchor_bit1 = 20;
uint64_t const g_hs_anchor_bit2 = 50;
uint64_t const g_hs_anchor_mask2 = ~(1ULL << 50);
uint64_t const g_hs_anchor_zero = 1ULL << (20);
uint64_t g_hs_anchor_getAnchor (uint64_t anchor)
{
return (anchor >> g_hs_anchor_bit1) & g_hs_anchor_mask3;
}
uint64_t g_hs_anchor_getStrAnchor (uint64_t anchor) // return @anchor := strand + anchorx
{
return ((anchor >> g_hs_anchor_bit1) & g_hs_anchor_mask5) - g_hs_anchor_zero;
}
uint64_t g_hs_anchor_getX (uint64_t val)
{
return (((val >> g_hs_anchor_bit1)) & g_hs_anchor_mask3) - g_hs_anchor_zero +
(val & g_hs_anchor_mask1);
}
uint64_t g_hs_anchor_getY (uint64_t val)
{
return val & g_hs_anchor_mask1;
}
uint64_t g_hs_anchor_get_strand(uint64_t val)
{
return (val >> g_hs_anchor_bit2) & 1;
}
///g_hs: N/A[1]|xval[30]|type[2]|strand[1]|coordinate[30]
///type=0: from genome, type=1: from read
const uint64_t g_hs_bit1 = 30;
const uint64_t g_hs_bit2 = 31;
const uint64_t g_hs_bit3 = 33;
const uint64_t g_hs_mask2 = (1ULL << 30) - 1;
const uint64_t g_hs_mask3 = (1ULL << 32) - 1;
uint64_t g_hs_makeGhs_(uint64_t xval,
uint64_t type,
uint64_t strand,
uint64_t coord)
{
return (xval << 33) + (type<< 31) + (strand << 30) + coord;
}
int64_t g_hs_getCord(uint64_t & val)
{
return int64_t(val & g_hs_mask2);
}
//given cord1, return g_hs type anchor = strand + anchor:= strand[1]|anchor[30]
uint64_t g_hs_Cord2StrAnchor(uint64_t cord)
{
uint64_t strand = get_cord_strand(cord);
return get_cord_x(cord) - get_cord_y(cord) + (strand << (g_hs_anchor_bit2 - g_hs_anchor_bit1));
}
void g_hs_setAnchor_(uint64_t & val,
uint64_t const & hs1, /*genome*/
uint64_t const & hs2, /*read*/
uint64_t revscomp_const)
{
uint64_t strand = ((hs1 ^ hs2) >> 30 ) & 1;
uint64_t x = revscomp_const * strand - _nStrand(strand) * (hs2 & g_hs_mask2);
val = (((hs1 + g_hs_anchor_zero - x) & (g_hs_mask2))<< 20) + x + (strand << g_hs_anchor_bit2);
}
//create anchors in clip, where strand is ommited
uint64_t c_2Anchor_(uint64_t const & hs1, uint64_t const & hs2)
{
///hs1 genome, hs2 read
uint64_t x = hs2 & g_hs_mask2;
return (((hs1 - x + g_hs_anchor_zero) & (g_hs_mask2)) << g_hs_anchor_bit1) + x;
}
///get xvalue and type
uint64_t g_hs_getXT (uint64_t const & val)
{
return (val >> 31) & g_hs_mask3;
}
uint64_t g_hs_getX (uint64_t const & val)
{
uint64_t mask = ((1ULL << 30) - 1);
return ((val >> 33) & mask) ;
}
uint64_t g_hs_anchor2Tile (uint64_t anchor)
{
uint64_t strand = (anchor >> g_hs_anchor_bit2) & 1;
/**
* The cord of read read (y) is shown in its own direction.
*/
uint64_t y = g_hs_anchor_getY(anchor);
return (((anchor - (g_hs_anchor_zero << 20) +
((anchor & g_hs_anchor_mask1)<< 20)) &
g_hs_anchor_mask2) & g_hs_anchor_mask1_) + y + (strand << 61);
}
int64_t tile_distance_x (uint64_t tile1, uint64_t tile2, uint64_t readlen)
{
(void)readlen;
return (int64_t)(get_cord_x(tile2)) - (int64_t)(get_cord_x(tile1));
}
int64_t tile_distance_y (uint64_t tile1, uint64_t tile2, uint64_t readlen)
{
return get_tile_strand (tile1 ^ tile2) ? get_tile_y(tile2) - readlen + 1 + get_tile_y(tile1) :
(int64_t)(_defaultTile.getY(tile2)) - (int64_t)(_defaultTile.getY(tile1));
}
/*
* shortcut to return if 2 cords have different anchors
* @cord1 and @cord2 are required to have same strand
* @thd_dxy_min lower bound of dx dy
* @thd_da_zero < is treated as 0.
* @greater > 0 return true if anchor1 >> anchor2 (significantly larger)
* @greater < 0 ... anchor1 << anchor2
* @greater = 0 ... |anchor1 - anchor2| >> 0
*/
bool is_diff_anchor (uint64_t cord1, uint64_t cord2, int greater, int64_t thd_dxy_min, float thd_da_zero)
{
int64_t dy = get_cord_y(cord2) - get_cord_y(cord1);
int64_t dx = get_cord_x(cord2) - get_cord_x(cord1);
int64_t dmax = std::max(std::abs(dx), std::abs(dy));
return std::abs(dy - dx) > int64_t(std::max(thd_dxy_min, dmax) * thd_da_zero) &&
dy - dx * greater >= 0;
}
/**
* Shortcut to set main and recd flag for tiles
* main and recd are sign of Cords.
* tiles sgn will be cleared and replaced by cords sgn.
*/
void set_tiles_cords_sgns(String<uint64_t> & tiles, uint64_t sgn)
{
for (int i = 0; i < (int)length(tiles); i++)
{
remove_tile_sgn(tiles[i]);
set_cord_gap(tiles[i]);
set_cord_recd(tiles[i] , sgn);
}
}
/**
* collecting k-mers in 'seq' to 'g_hs'
*/
int g_mapHs_kmer_(String<Dna5> & seq,
String<uint64_t> & g_hs,
uint64_t str,
uint64_t end,
int shape_len,
int step,
uint64_t type)
{
if (length(seq) < (unsigned)shape_len)
{
return 0;
}
LShape shape(shape_len);
hashInit(shape, begin(seq) + str);
int count = 0;
uint64_t val = 0;
for (uint64_t k = str; k < std::min(end, length(seq) - shape_len); k++)
{
val = hashNextV(shape, begin(seq) + k);
if (++count == step) //collecting every step bases
{
//TODO: k - getT(shape)
appendValue(g_hs, g_hs_makeGhs_(val, type, shape.strand, k));
count = 0;
}
}
return length(g_hs);
}
/**
* Stream the block of @g_hs specified by @p1, @p2, @k and
keep anchors that with in [@acnhor_lower, anchor_upper).
* When @direction is towards left, the function only collect anchors that can extend
from @gap_end to @gap_str.
*/
int g_mapHs_setAnchors_ (String<uint64_t> & g_hs,
String<uint64_t> & g_anchor,
int p1, int p2, int k,
uint64_t revscomp_const, int64_t anchor_lower, int64_t anchor_upper,
uint64_t gap_str, uint64_t gap_end, int direction, GapParms & gap_parms)
{
if (direction == 0)
{
for (int i = p1; i < p2; i++)
{
for (int j = p2; j < k; j++)
{
uint64_t tmp_anchor;
g_hs_setAnchor_(tmp_anchor, g_hs[i], g_hs[j], revscomp_const);
int64_t tmp = g_hs_anchor_getStrAnchor(tmp_anchor);
if (tmp < anchor_upper && tmp >= anchor_lower){
appendValue(g_anchor, tmp_anchor);
}
}
}
}
else if (direction < 0) //towards left : for mapping extend collect anchor of same strand and close to gap_str or gap_end, NOTE<red> anchors of different strands with gap_str or gap_end are skipped
{
int64_t y_end = get_cord_y(gap_end);
int64_t anchor_base = g_hs_Cord2StrAnchor(gap_end);
int64_t d_anchor = (1LL << 7) * gap_parms.thd_gmsa_d_anchor_rate;
int64_t anchor_lower2, anchor_upper2;
for (int i = p1; i < p2; i++)
{
for (int j = p2; j < k; j++)
{
uint64_t tmp_anchor;
g_hs_setAnchor_(tmp_anchor, g_hs[i], g_hs[j], revscomp_const);
int64_t tmp = g_hs_anchor_getStrAnchor(tmp_anchor);
int64_t dy = y_end - g_hs_anchor_getY(tmp_anchor);
if (dy < 0 || (g_hs_anchor_get_strand(tmp_anchor) ^ get_cord_strand(gap_str))){
continue;
}
else{
int64_t d_anchor_acc = std::max((dy >> 7) * d_anchor, int64_t(50)); // d_anchor accumulated
anchor_lower2 = std::max(anchor_base - d_anchor_acc, int64_t(0)); // 1<<7 =128, every 128bp increase by d_anchor
anchor_upper2 = anchor_base + d_anchor_acc;
}
if (tmp < anchor_upper2 && tmp >= anchor_lower2){
appendValue(g_anchor, tmp_anchor);
}
}
}
}
else if (direction > 0)
{
int64_t y_str = get_cord_y(gap_str);
int64_t anchor_base = g_hs_Cord2StrAnchor(gap_str);
int64_t d_anchor = (1LL << 7) * gap_parms.thd_gmsa_d_anchor_rate;
int64_t anchor_lower2, anchor_upper2;
for (int i = p1; i < p2; i++)
{
for (int j = p2; j < k; j++)
{
uint64_t tmp_anchor;
g_hs_setAnchor_(tmp_anchor, g_hs[i], g_hs[j], revscomp_const);
int64_t tmp = g_hs_anchor_getStrAnchor(tmp_anchor);
int64_t dy = g_hs_anchor_getY(tmp_anchor) - y_str;
if (dy < 0 || (g_hs_anchor_get_strand(tmp_anchor) ^ get_cord_strand(gap_str))){
continue;
}
else{
int64_t d_anchor_acc = std::max((dy >> 7) * d_anchor, int64_t(50)); // d_anchor accumulated
anchor_lower2 = std::max(anchor_base - d_anchor_acc, int64_t(0)); // 1<<7 =128, every 128bp increase d_anchor
anchor_upper2 = anchor_base + d_anchor_acc;
}
if (tmp < anchor_upper2 && tmp >= anchor_lower2){
appendValue(g_anchor, tmp_anchor);
}
}
}
}
return 0;
}
/*---------- Section of MapAnchor2_: function, parm and wrapper ----------*/
/**
::dcgx::simple X-drop by counting gap lens
Chains in ascending order required : xi < xj && yi < yj provided i < j
*/
int dropChainGapX(String<uint64_t> & chains,
uint64_t (*getX)(uint64_t),
uint64_t (*getY)(uint64_t),
int direction, bool f_erase, GapParms & gap_parms)
{
if (direction == g_map_rght)
{
for (int i = 1; i < (int)length(chains); i++)
{
uint di = i + 1 >= gap_parms.thd_dcgx_window_size ? gap_parms.thd_dcgx_window_size : 1;
if (int64_t(getX(chains[i]) - getX(chains[i - 1])) > gap_parms.thd_dcgx_Xdrop_peak ||
int64_t(getX(chains[i]) - getX(chains[i + 1 - di])) > gap_parms.thd_dcgx_Xdrop_sum ||
int64_t(getY(chains[i]) - getY(chains[i - 1])) > gap_parms.thd_dcgx_Xdrop_peak ||
int64_t(getY(chains[i]) - getY(chains[i + 1 - di])) > gap_parms.thd_dcgx_Xdrop_sum)
{
if (f_erase)
{
resize (chains, i);
return length(chains);
}
return i;
}
}
return length(chains);
}
if (direction == g_map_left)
{
for (int i = length(chains) - 2; i > 0; i--)
{
uint di = (int)length(chains) - i >= gap_parms.thd_dcgx_window_size ? gap_parms.thd_dcgx_window_size : 1;
if (int64_t(getX(chains[i + 1]) - getX(chains[i])) > gap_parms.thd_dcgx_Xdrop_peak ||
int64_t(getX(chains[i + di - 1]) - getX(chains[i])) > gap_parms.thd_dcgx_Xdrop_sum ||
int64_t(getY(chains[i + 1]) - getY(chains[i])) > gap_parms.thd_dcgx_Xdrop_peak ||
int64_t(getY(chains[i + di - 1]) - getY(chains[i])) > gap_parms.thd_dcgx_Xdrop_sum)
{
if (f_erase)
{
erase(chains, 0, i + 1);
return 0;
}
return i;
}
}
return 0;
}
return 0;
}
unsigned _get_tile_f_ (uint64_t & tile,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2)
{
// uint64_t tile = shift_tile(k_tile, )
uint thd_abort_score = UMAX;
uint64_t tile_x = _defaultTile.getX(tile);
uint64_t tile_y = _defaultTile.getY(tile);
uint64_t n1 = get_tile_strand(tile);
uint64_t n2 = get_tile_id(tile);
unsigned fscore;
if (n1 < length(f1) && n2 < length(f2))
{
fscore = _windowDist(f1[n1], f2[n2],
_DefaultCord.cord2Cell(tile_y),
_DefaultCord.cord2Cell(get_tile_x(tile)));
}
else
{
fscore = thd_abort_score;
}
unused(tile_x);
return fscore;
}
/*
* only when score < @thd_accept_score, @new_tile is meaningful
*
unsigned _get_tile_f_tri_ (uint64_t & new_tile,
StringSet<FeaturesDynamic > & f1,
StringSet<FeaturesDynamic > & f2,
unsigned thd_accept_score,
int thd_tile_size)
{
int shift = thd_tile_size / 4;
unsigned thd_abort_score = UMAX; // make sure thd_abort_score > thd_accept_score
double t1 = sysTime();
unsigned fscore = _get_tile_f_ (new_tile, f1, f2) ;
if (fscore <= thd_accept_score)
{
return fscore;
}
else
{
uint64_t tile_l = shift_tile(new_tile, -shift, -shift);
fscore = std::min(_get_tile_f_(tile_l, f1, f2), fscore);
if (fscore <= thd_accept_score)
{
new_tile = tile_l;
return fscore;
}
else
{
uint64_t tile_r = shift_tile(new_tile, shift, shift);
new_tile = tile_r;
fscore = std::min(_get_tile_f_(tile_r, f1, f2), fscore);
return fscore;
}
}
return fscore;
}
*/
/*
* only when score < @thd_accept_score, @new_tile is meaningful
*/
unsigned _get_tile_f_tri_ (uint64_t & new_tile,
StringSet<FeaturesDynamic > & f1,
StringSet<FeaturesDynamic > & f2,
unsigned thd_accept_score,
int thd_tile_size)
{
int shift = thd_tile_size / 4;
unsigned thd_abort_score = UMAX; // make sure thd_abort_score > thd_accept_score
unsigned fscore1 = _get_tile_f_ (new_tile, f1, f2) ;
unsigned min_score = fscore1;
uint64_t tile_l = shift_tile(new_tile, -shift, -shift);
unsigned fscore2 = _get_tile_f_(tile_l, f1, f2);
if (fscore2 < fscore1)
{
new_tile = tile_l;
min_score = fscore2;
}
uint64_t tile_r = shift_tile(new_tile, shift, shift);
unsigned fscore3 = _get_tile_f_(tile_r, f1, f2);
if (fscore3 < min_score)
{
new_tile = tile_r;
min_score = fscore3;
}
unused(thd_abort_score);
unused(thd_accept_score);
return min_score;
}
int createTilesFromAnchors1_(String<uint64_t> & anchor,
String<uint64_t> & tiles,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2,
uint64_t gap_str,
uint64_t gap_end,
int anchor_end,
int const & thd_tile_size,
float const & thd_err_rate,
int const & thd_pattern_in_window,
float const & thd_anchor_density,
int64_t const & thd_min_segment,
GapParms & gap_parms)
{
int anchor_len = 0;
std::sort (begin(anchor), begin(anchor) + anchor_end);
anchor[anchor_end] = ~0;
int prek = 0;
for (int k = 0; k < anchor_end + 1; k++)
{
//TODO: handle thd_min_segment, anchor
int64_t d = std::abs((int64_t)g_hs_anchor_getY(anchor[k]) - (int64_t)g_hs_anchor_getY(anchor[prek]));
if (g_hs_anchor_getStrAnchor(anchor[k]) - g_hs_anchor_getStrAnchor(anchor[prek]) >
thd_err_rate * std::max(thd_min_segment, d))
{
int thd_anchor_accpet = thd_anchor_density *
std::abs(int64_t(g_hs_anchor_getY(anchor[k - 1]) -
g_hs_anchor_getY(anchor[prek])));
thd_anchor_accpet = std::max (thd_anchor_accpet, 2);
thd_anchor_accpet = std::min (g_thd_anchor, thd_anchor_accpet);
if (anchor_len > thd_anchor_accpet)
{
std::sort (begin(anchor) + prek, begin(anchor) + k,
[](uint64_t & s1, uint64_t & s2)
{return g_hs_anchor_getX(s2) > g_hs_anchor_getX(s1);
});
// g_CreateTilesFromChains_(anchor, tiles, f1, f2, gap_str, prek, k,
// &g_hs_anchor_getX, &g_hs_anchor_getY, &g_hs_anchor_get_strand, gap_parms);
}
prek = k;
anchor_len = 0;
}
else
{
anchor_len++;
}
}
unused(tiles);
unused(f1);
unused(f2);
unused(gap_str);
unused(gap_end);
unused(thd_tile_size);
unused(thd_pattern_in_window);
unused(gap_parms);
return 0;
}
//ATTENTION::the Adjust @thd_abort_score if the function is changed
int getGapAnchorsChainScore(uint64_t const & anchor1, uint64_t const & anchor2, ChainScoreParms & chn_score_parms)
{
int64_t dy = g_hs_anchor_getY(anchor1) - g_hs_anchor_getY(anchor2);
int64_t dx = g_hs_anchor_getX(anchor1) - g_hs_anchor_getX(anchor2);
if (dy < 0 || g_hs_anchor_get_strand(anchor1 ^ anchor2) || (std::abs(dx) < 8 && dx != dy)) //abort too close dx, such as dx == 0, dy == 100;
{
return -10000;
}
int64_t thd_min_dy = 50;
int64_t da = std::abs(int64_t(g_hs_anchor_getStrAnchor(anchor2) - g_hs_anchor_getStrAnchor(anchor1)));
int64_t derr = (100 * da) / std::max(dy, thd_min_dy); // 1/100 = 0.01
int score_derr;
int score_dy;
//d_err
if (derr < 10)
{
score_derr = 0;
}
else if (derr < 15)
{
score_derr = 10 + 2 * derr ;
}
else
{
score_derr = derr * derr / 10 + 40;
}
//d_y
if (dy < 100)
{
score_dy = dy / 4;
}
else if (dy < 200)
{
score_dy = dy / 3 - 9;
}
else
{
score_dy = dy - 145;
}
unused(chn_score_parms);
return 100 - score_dy - score_derr ;
}
//chain compact anchors whose anchor value are very close
//supposed to use in extend existing anchor that might be called when mapping ins
//For 9mer:step1 = 5:step2 = 1
int getGapAnchorsChainScore2(uint64_t const & anchor1, uint64_t const & anchor2, ChainScoreParms & chn_score_parms)
{
unused(chn_score_parms);
int64_t dy = g_hs_anchor_getY(anchor1) - g_hs_anchor_getY(anchor2);
int64_t dx = g_hs_anchor_getX(anchor1) - g_hs_anchor_getX(anchor2);
if (dy < 0 || g_hs_anchor_get_strand(anchor1 ^ anchor2)
|| ((std::abs(dx) < 8 || std::abs(dy) < 8)&& dx != dy)) //abort too close dx, such as dx == 0, dy == 100;
{
return -10000;
}
int64_t thd_min_dy = 50;
int64_t da = std::abs(int64_t(g_hs_anchor_getStrAnchor(anchor2) - g_hs_anchor_getStrAnchor(anchor1)));
int64_t derr = (100 * da) / std::max({dx, dy, thd_min_dy}); // 1/100 = 0.01
int score_derr;
int score_dy;
//d_err
if (derr < 5)
{
score_derr = 4 * derr;
}
else if (derr < 10)
{
score_derr = 6 * derr - 10;
}
else
{
score_derr = derr * derr - 5 * derr;
}
score_dy = dy * (dy + 300) / 300;
return 100 - score_dy - score_derr ;
}
//Warn::yellow > sychronize getApxChainScore3 of same logic if necessary when modifiy this function
//Warn::red dup(dx < thd_min_dx) is not allowed in this score function.
int getGapBlocksChainScore2(uint64_t const & cord11, uint64_t const & cord12, uint64_t const & cord21, uint64_t const & cord22, uint64_t const & read_len, ChainScoreParms & chn_score_parms)
{
int64_t thd_min_dy = -40;
int64_t thd_min_dx = -40;
int64_t dx, dy, da, d_err;
//int f_type = getForwardChainDxDy(cord11, cord12, cord21, cord22, read_len, dx, dy);
int f_type = getChainBlockDxDy(cord11, cord12, cord21, cord22, read_len, chn_score_parms.chn_block_strand, dx, dy);
int64_t thd_max_dy = 500;
int64_t thd_max_dx = 15000; //inv at end can be infinity
int64_t thd_dup_trigger = -50;
int64_t dx_ = std::abs(dx);
int64_t dy_ = std::abs(dy);
da = dx - dy;
int score = 0;
//if (dy < thd_min_dy || (f_type == 0 && dy > thd_max_dy) || dx_ > thd_max_dx)
if (dx < thd_min_dx || dy < thd_min_dy)
{
score = INT_MIN;
//score = INT_MIN;
}
else
{
int64_t score_dy = dy_ > 300 ? dy_ / 4 - 25 : dy_ / 6;
int64_t score_dx = dx_ > 300 ? dx_ / 4 - 25 : dx_ / 6;
if (f_type == 1) //inv
{
score = 80 - score_dy;
}
else if (da < -std::max(dx_ / 4, int64_t(50))) //1/4 = *0.25 , maximum sequence error_rate
{
if (dx > thd_dup_trigger) //ins
{
score = 80 - score_dx; // any large dy is theoretically allowed
}
else //dup
{
score = 40 - score_dy; // different from ins the dy of dup is suppoesd to be close enough
}
}
else if (da > std::max(dy / 4, int64_t(50))) //del
{
score = 80 - score_dy;
}
else //normal
{
score = 100 - score_dy;
}
}
unused(d_err);
unused(thd_max_dx);
unused(thd_max_dy);
return score;
}
//chain blocks that are very close comppatly
//supposed to be used in extending existing anchor for ins/del
int getGapBlocksChainScore3(uint64_t const & cord11, uint64_t const & cord12, uint64_t const & cord21, uint64_t const & cord22, uint64_t const & read_len, ChainScoreParms & chn_score_parms)
{
int64_t thd_min_dy = 0;
int64_t thd_min_dx = 0;
int64_t dx, dy, da, d_err;
//int f_type = getForwardChainDxDy(cord11, cord12, cord21, cord22, read_len, dx, dy);
int f_type = getChainBlockDxDy(cord11, cord12, cord21, cord22, read_len, chn_score_parms.chn_block_strand, dx, dy);
int64_t thd_max_dy = 500;
int64_t thd_max_dx = 15000; //inv at end can be infinity
int64_t thd_dup_trigger = -50;
int64_t dx_ = std::abs(dx);
int64_t dy_ = std::abs(dy);
da = dx - dy;
int score = 0;
if (dx < thd_min_dx || dy < thd_min_dy)
{
return INT_MIN;
//score = INT_MIN;
}
int64_t score_dy = dy_ > 300 ? dy_ / 4 - 25 : dy_ / 6;
int64_t score_dist;
int64_t score_da;
int64_t da_ratio;
if (f_type == 1) //inv
{
score = 20 - score_dy;
}
else
{
da_ratio = 100 * std::abs(da) / std::max({dx_, dy_, int64_t(100)});
if (da < 15)
{
score_da = da_ratio * (da_ratio + 20) / 40;
}
else if (da >= 15 && da < 30)
{
score_da = da_ratio * (da_ratio + 50) / 45;
}
else
{
score_da = da_ratio * (da_ratio + 100) / 45;
}
/*
if (da_ratio < 5)
{
score_da = 4 * da_ratio;
}
else if (da_ratio < 10)
{
score_da = 6 * da_ratio - 10;
}
else
{
score_da = 10 * da_ratio - 50;
}
*/
int64_t max_dx_dy_ = std::max(dx_, dy_);
score_dist = max_dx_dy_ * (max_dx_dy_ + 450)/2000;
score = 100 - score_da - score_dist;
}
unused(d_err);
unused(thd_max_dx);
unused(thd_max_dy);
unused(thd_dup_trigger);
return score;
}
int chainTiles(String<uint64_t> & tiles, uint64_t read_len, uint64_t thd_gather_block_gap_size, GapParms & gap_parms)
{
//insert(tiles, 0, 0);
String<UPair> str_ends;
String<UPair> str_ends_p;
String<int> str_ends_p_score;
gather_blocks_(tiles, str_ends, str_ends_p, 0, length(tiles), read_len, thd_gather_block_gap_size, 0, 0, &is_tile_end, &set_tile_end);
//preFilterChains2(tiles, str_ends_p, &set_tile_end);
//ChainScoreMetric chn_score(0, &getGapChainScore2);
chainBlocksCords(tiles, str_ends_p, gap_parms.chn_score2, read_len, 64, gap_parms.thd_cts_major_limit, &remove_tile_sgn_end, &set_tile_end, 0);
return 0;
}
int g_CreateChainsFromAnchors_(String<uint64_t> & anchors, String<uint64_t> & tiles,
uint64_t & gap_str, uint64_t & gap_end, uint64_t read_len,
GapParms & gap_parms)
{
uint64_t thd_anchor_gap_size = 100; //warn::not the thd_gap_size
StringSet<String<uint64_t> > anchors_chains;
String<int> anchors_chains_score;
uint block_str = 0;
uint thd_chain_depth = 20;
uint64_t thd_chain_dx_depth = 80;
std::sort(begin(anchors), end(anchors), [](uint64_t & a, uint64_t & b){return g_hs_anchor_getX(a) > g_hs_anchor_getX(b);});
int thd_best_n = 20;
chainAnchorsBase(anchors, anchors_chains, anchors_chains_score, 0, length(anchors),
thd_chain_depth, thd_chain_dx_depth, thd_best_n, gap_parms.chn_score1, &g_hs_anchor_getX);
resize (tiles, lengthSum(anchors_chains));
int it = 0;
for (int i = 0; i < (int)length(anchors_chains); i++)
{
for (int j = 0; j < (int)length(anchors_chains[i]); j++)
{
tiles[it++] = g_hs_anchor2Tile(anchors_chains[i][j]);
}
set_tile_end(tiles[it - 1]);
}
chainTiles(tiles, read_len, thd_anchor_gap_size, gap_parms);
unused(block_str);
unused(gap_str);
unused(gap_end);
return 0;
}
/**
*get the chain closed to gap_str (if direction = right) or gap_end (if ..left)
*@f_erase_tiles, if remove tile in tmp_tiles that have been filtered out.
*/
std::pair<int, int> getClosestExtensionChain_(String<uint64_t> & tmp_tiles, uint64_t gap_str, uint64_t gap_end, bool f_erase_tiles, GapParms & gap_parms)
{
int pre_i = 0;
for (int i = 0; i < (int)length(tmp_tiles); i++)
{
if (is_tile_end(tmp_tiles[i]))
{
int64_t danchor = 0, dx, dy;
if (gap_parms.direction < 0)
{
dy = get_tile_y(gap_end) - get_tile_y(tmp_tiles[i]);
dx = get_tile_x(gap_end) - get_tile_x(tmp_tiles[i]);
danchor = dx - dy;
}
else if (gap_parms.direction > 0)
{
dy = get_tile_y(tmp_tiles[pre_i]) - get_tile_y(gap_str);
dx = get_tile_x(tmp_tiles[pre_i]) - get_tile_x(gap_str);
danchor = dx - dy;
}
if (std::abs(danchor) < gap_parms.thd_ctfas2_connect_danchor &&
std::max(std::abs(dy), std::abs(dx)) < gap_parms.thd_ctfas2_connect_dy_dx)
{
if (f_erase_tiles == true)
{
erase (tmp_tiles, 0, pre_i);
resize(tmp_tiles, i + 1 - pre_i); //remove [i + 1, end)
return std::pair<int, int>(0, length(tmp_tiles));
}
else
{
return std::pair<int, int>(pre_i, i + 1);
}
break;
}
pre_i = i + 1;
}
}
//failed to find closest chain
if (f_erase_tiles)
{
clear(tmp_tiles);
}
return std::pair<int, int>(0, 0);
}
//Create tiles for the block of @chains within [@it_str, it_end).
//Note::chains are supposed to have one tile_end sign (one block) at most
//The new tiles created from [@chains[it_str], @chains[it_end]) are appended to the @tiles
int g_CreateTilesFromChains_ (String<uint64_t> & chains,
String<uint64_t> & tiles,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2,
uint64_t gap_str,
int it_str,
int it_end,
uint64_t(*get_x)(uint64_t), //get_x of chains rather than tile
uint64_t(*get_y)(uint64_t),
uint64_t(*get_strand)(uint64_t),
GapParms & gap_parms)
{
if (it_end - it_str == 0)
{
return 0;
}
uint thd_fscore = getWindowThreshold(f1); // todo seqeunce error related
uint64_t pre_chain = chains[it_str];
uint64_t pre_tile = 0;
int64_t tmp_shift = gap_parms.thd_tile_size / 2;
uint64_t step = gap_parms.thd_tile_size / 3;
int kcount = 0; //count of kmers in range of each step
int scan_str = it_str;
int scan_end = it_str;
for (int i = it_str; i <= it_end; i++) //i == it_end is out of anchor, this is suit the last one it_end - 1
{
if (i == it_end || get_strand(chains[i] ^ pre_chain) || get_x(chains[i]) > get_x(pre_chain) + step ||
get_y(chains[i]) > get_y(pre_chain) + step)
{
if (i == it_end)
{
scan_end = it_end;
}
for (int j = scan_end - 1; j >= scan_str; j--)
{
uint64_t new_tile = create_tile(get_cord_id(gap_str),
get_x(chains[j]) - tmp_shift,
get_y(chains[j]) - tmp_shift,
get_strand(chains[j]));
//unsigned score = _get_tile_f_(new_tile, f1, f2);
//g_print_tile(new_tile, "gs2");
unsigned score = _get_tile_f_tri_(new_tile, f1, f2,
gap_parms.thd_ctfcs_accept_score, gap_parms.thd_tile_size);
//g_print_tile(new_tile, "gs22");
if (kcount >= (int)gap_parms.thd_ctfcs_pattern_in_window && score <= 32 &&
get_tile_y(new_tile) > get_tile_y(pre_tile))
{
if (empty (tiles) || is_tile_end(back(tiles)))
{
set_tile_start(new_tile);
}
appendValue (tiles, new_tile);
pre_tile = new_tile;
kcount = i - j;
pre_chain = chains[j];
break;
}
}
scan_str = i;
scan_end = i + 1;
}
else
{
scan_end++;
kcount++;
}
}
if (!empty(tiles))
{
set_tile_end(back(tiles)) ;
}
unused(thd_fscore);
return 0;
}
/*
* Create tiles for the block of @chains within [@it_str, it_end).
* Note::chains are supposed to have one tile_end sign (one block) at most
* This funtion requires @chains already clipped at the start and end of the chain,
Thus the first elment of @tiles_str and last element of @tiles_end == @chains[0]
and back(@chains)
* The function generates the @tiles_end as well
* @chains are required to be within [@gap_str, @gap_end)
* @chains are required to be on one strand
*/
int g_CreateTilesFromChains_ (String<uint64_t> & chains,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2,
uint64_t gap_str,
uint64_t gap_end,
int it_str,
int it_end,
uint64_t(*get_x)(uint64_t), //get_x of chains rather than tile
uint64_t(*get_y)(uint64_t),
uint64_t(*get_strand)(uint64_t),
GapParms & gap_parms)
{
(void)gap_str;
(void)gap_end;
int tiles_str_i = length(tiles_str);
String<uint64_t> tiles_str_tmp;
String<uint64_t> tiles_end_tmp;
//g_print_tiles_(chains, "gctf1");
g_CreateTilesFromChains_(chains, tiles_str_tmp, f1, f2, gap_str, it_str, it_end,
get_x, get_y, get_strand, gap_parms);
//std::cout << "gctf2" << it_str << it_end << length(tiles_str_tmp)<< empty(tiles_str_tmp) << "\n";
if (empty (tiles_str_tmp))
{
return 0;
}
int64_t tile_size = gap_parms.thd_tile_size;
for (unsigned i = 0; i < length(tiles_str_tmp); i++)
{
int64_t dx1 = get_x(chains[it_str]) - get_tile_x(tiles_str_tmp[i]);
int64_t dy1 = get_y(chains[it_str]) - get_tile_y(tiles_str_tmp[i]);
//dout << "gctf61" << dx1 << dx2 << dy1 << dy2 << "\n";
if (dx1 <= 0 && dy1 <= 0)
{
if (dx1 == 0 && dy1 == 0)
{
break;
}
uint64_t new_head_str = create_tile(get_cord_id(gap_str),
get_x(chains[it_str]),
get_y(chains[it_str]),
get_strand(chains[it_str]));
remove_tile_sgn(new_head_str);
if (i == 0)
{
insertValue(tiles_str_tmp, 0, new_head_str);
}
else
{
tiles_str_tmp[i - 1] = new_head_str;
erase(tiles_str_tmp, 0, i - 1);
}
break;
}
if (i == length(tiles_str_tmp) - 1) //if not found such...
{
clear(tiles_str_tmp);
appendValue(tiles_str_tmp, create_tile(get_cord_id(gap_str),
get_x(chains[it_str]),
get_y(chains[it_str]),
get_strand(chains[it_str])));
}
}
resize(tiles_end_tmp, length(tiles_str_tmp));
for (unsigned i = 0; i < length(tiles_str_tmp); i++)
{
tiles_end_tmp[i] = shift_tile (tiles_str_tmp[i], tile_size, tile_size);
}
for (int i = int(length(tiles_end_tmp)) - 1; i >= 0; i--)
{
int64_t dx1 = get_x(chains[it_end - 1]) - get_tile_x(tiles_end_tmp[i]);
int64_t dy1 = get_y(chains[it_end - 1]) - get_tile_y(tiles_end_tmp[i]);
if (dx1 >= 0 && dy1 >= 0)
{
if (dx1 == 0 && dy1 == 0)
{
break;
}
erase (tiles_str_tmp, i + 1, length(tiles_str_tmp));
erase (tiles_end_tmp, i + 1, length(tiles_end_tmp));
uint64_t new_tail_end = create_tile(get_cord_id(gap_str),
get_x(chains[it_end - 1]),
get_y(chains[it_end - 1]),
get_strand(chains[it_end - 1]));
uint64_t new_tail_str = shift_tile(new_tail_end, -tile_size, -tile_size);
if (is_tile_end(tiles_str_tmp[i]))
{
remove_tile_sgn(tiles_str_tmp[i]);
remove_tile_sgn(tiles_end_tmp[i]);
set_tile_end(new_tail_str);
set_tile_end(new_tail_end);
}
appendValue(tiles_str_tmp, new_tail_str);
appendValue(tiles_end_tmp, new_tail_end);
break;
}
if (i == 0) //if not found such.., then erase all except the first one
{
erase(tiles_str_tmp, 1, length(tiles_str_tmp));
erase(tiles_end_tmp, 1, length(tiles_end_tmp));
tiles_end_tmp[0] = shift_tile(tiles_end_tmp[0], dx1, dy1);
//set_tile_end(tiles_str_tmp[0]);
//set_tile_end(tiles_end_tmp[0]);
}
}
append(tiles_str, tiles_str_tmp);
append(tiles_end, tiles_end_tmp);
unused(tiles_str_i);
return 0;
}
/*
int mapClipChains(String<uint64_t> & chain)
{
for (int i = 0; i < length(tmp_tiles); i++)
{
if (is_tile_end(tmp_tiles[i]))
{
g_CreateTilesFromChains_(tmp_tiles, tiles, f1, f2, gap_str, pre_i, i + 1, &get_tile_x, &get_tile_y, &get_tile_strand, gap_parms);
pre_i = i + 1;
}
else if (i < length(tmp_tiles) - 1 &&
get_tile_strand(tmp_tiles[i] ^ tmp_tiles[i + 1]))
{
int len = length(tiles);
///extendClipInterval(ref, read, comstr, tmp_tiles, direction, gap_parms);
g_CreateTilesFromChains_(tmp_tiles, tiles, f1, f2, gap_str, pre_i, i + 1, &get_tile_x, &get_tile_y, &get_tile_strand, gap_parms);
if (len != length(tiles))
{
remove_tile_sgn_end(back(tiles));
}
pre_i = i + 1;
}
}
}
*/
int trimTiles(String<uint64_t> & tiles,
StringSet<FeaturesDynamic> & f1, StringSet<FeaturesDynamic> & f2,
uint64_t gap_str, uint64_t gap_end, uint64_t revscomp_const, int direction,
GapParms & gap_parms)
{
/**
* step1.Extend patch
* extend window if there are gaps between tiles until the
coordinates x1 - x2 < window_size or the gap can't be extend any more
* ATTENTION: This methods takes no account of the relation between y1 and y2.
*/
int thd_gap_size = gap_parms.thd_tts_gap_size;
uint64_t thd_tile_size = gap_parms.thd_tile_size;
uint64_t thd_overlap_size = gap_parms.thd_tts_overlap_size;
uint64_t cord_str = gap_str;
int64_t shift_x = std::min(int64_t(get_cord_x(gap_end) - get_cord_x(gap_str)), int64_t(thd_tile_size));
int64_t shift_y = std::min(int64_t(get_cord_y(gap_end) - get_cord_y(gap_str)), int64_t(thd_tile_size));
uint64_t cord_end = shift_cord(gap_end, -shift_x, -shift_y);
for (int i = 0; i < (int)length(tiles); i++)
{
if (is_tile_start(tiles[i]) && direction >= 0)
{
int new_num = extendPatch(f1, f2, tiles, i, cord_str, tiles[i], revscomp_const, thd_overlap_size, thd_gap_size, gap_parms.thd_accept_score);
if (new_num)
{
set_tile_start(tiles[i]);
i += new_num;
remove_tile_sgn_start(tiles[i]);
}
}
if (is_tile_end(tiles[i]) && direction <= 0)
{
int new_num = extendPatch(f1, f2, tiles, i + 1, tiles[i], cord_end, revscomp_const, thd_overlap_size, thd_gap_size, gap_parms.thd_accept_score);
if (new_num)
{
remove_tile_sgn_end(tiles[i]);
i += new_num;
set_tile_end(tiles[i]);
}
}
if (i >= 1 && !is_tile_end (tiles[i - 1]) && !is_tile_start(tiles[i]))
{
i += extendPatch(f1, f2, tiles, i, tiles[i - 1], tiles[i], revscomp_const, thd_overlap_size, thd_gap_size, gap_parms.thd_accept_score);
}
}
//g_print_tiles_(tiles, "tms12");
//step2.Remove tiles out of bound.
int64_t x_str = get_tile_x(gap_str);
int64_t y_str = get_tile_y(gap_str);
int64_t x_end = get_cord_x(gap_end);
int64_t y_end = get_cord_y(gap_end);
int di = 0;
for (int i = 0; i < (int)length(tiles); i++)
{
int64_t x_t = get_tile_x(tiles[i]);
int64_t y_t = get_tile_strand(tiles[i] ^ gap_str) ?
revscomp_const - 1 - get_tile_y(tiles[i]) - thd_tile_size :
get_tile_y(tiles[i]);
if (x_t < x_str || x_t + (int64_t)thd_tile_size > x_end ||
y_t < y_str || y_t + (int64_t)thd_tile_size > y_end) //out of bound of [gap_str, gap_end)
{
if (is_tile_start (tiles[i]) && is_tile_end(tiles[i]))
{
//NONE
}
else if (is_tile_start(tiles[i]))
{
if (i + 1 < (int)length(tiles))
{
set_tile_start(tiles[i + 1]);
}
}
else if (is_tile_end(tiles[i]))
{
if (i - di - 1 > 0)
{
set_tile_end (tiles[i - di - 1]);
}
}
else{
//NONE
}
di++;
}
else
{
tiles[i - di] = tiles[i];
}
}
if (di)
{
resize (tiles, length(tiles) - di);
}
return 0;
}
int g_create_anchors_ (String<uint64_t> & g_hs,
String<uint64_t> & g_hs_anchor,
int shape_len,
int direction,
int64_t anchor_lower,
int64_t anchor_upper,
uint64_t rvcp_const,
uint64_t gap_str,
uint64_t gap_end,
GapParms & gap_parms)
{
uint64_t mask = (1ULL << (2 * shape_len + g_hs_bit3)) - 1;
std::sort (begin(g_hs), end(g_hs), [mask](uint64_t & a, uint64_t & b){return (a & mask) < (b & mask);});
int p1 = 0, p2 = 0;
for (int k = 1; k < (int)length(g_hs); k++)
{
switch (g_hs_getXT((g_hs[k] ^ g_hs[k - 1]) & mask))
{
case 0: //x1 = x2 both from genome or read
break;
case 1: //x1 = x2 one from genome the other from read
p2 = k;
break;
default: //anchor current block before process next block
g_mapHs_setAnchors_(g_hs, g_hs_anchor, p1, p2, k, rvcp_const, anchor_lower, anchor_upper, gap_str, gap_end, direction, gap_parms);
p1 = k;
p2 = k;
}
}
return 0;
}
int g_CreateExtendAnchorsPair_ (String<uint64_t> & g_hs,
String<uint64_t> & g_hs_anchor1,
String<uint64_t> & g_hs_anchor2,
int shape_len,
uint64_t rvcp_const,
uint64_t gap_str1,
uint64_t gap_end1,
uint64_t gap_str2,
uint64_t gap_end2,
GapParms & gap_parms)
{
uint64_t mask = (1ULL << (2 * shape_len + g_hs_bit3)) - 1;
std::sort (begin(g_hs), end(g_hs), [mask](uint64_t & a, uint64_t & b){return (a & mask) < (b & mask);});
int p1 = 0, p2 = 0;
int direction1 = 1;
int direction2 = -1;
for (int k = 1; k < (int)length(g_hs); k++)
{
switch (g_hs_getXT((g_hs[k] ^ g_hs[k - 1]) & mask))
{
case 0: //x1 = x2 both from genome or read
break;
case 1: //x1 = x2 one from genome the other from read
p2 = k;
break;
default: //anchor current block before process next block
g_mapHs_setAnchors_(g_hs, g_hs_anchor1, p1, p2, k, rvcp_const, 0, 0, gap_str1, gap_end1, direction1, gap_parms);
g_mapHs_setAnchors_(g_hs, g_hs_anchor2, p1, p2, k, rvcp_const, 0, 0, gap_str2, gap_end2, direction2, gap_parms);
p1 = k;
p2 = k;
}
}
return 0;
}
int g_stream_(String<Dna5> & seq1, //genome
String<Dna5> & seq2, //read
String<uint64_t> & g_hs,
uint64_t gap_str,
uint64_t gap_end,
unsigned shape_len,
int step1,
int step2,
GapParms & gap_parms)
{
unused(gap_parms);
//clear(g_hs);
//resize(g_hs, 1ULL << 20);
uint64_t gs_str = get_cord_x(gap_str);
uint64_t gs_end = get_cord_x(gap_end);
uint64_t gr_str = get_cord_y(gap_str);
uint64_t gr_end = get_cord_y(gap_end);
if (get_cord_strand(gap_str))
{
gr_str = length(seq2) - gr_str - 1;
gr_end = length(seq2) - gr_end - 1;
std::swap (gr_end, gr_str);
}
g_mapHs_kmer_(seq1, g_hs, gs_str, gs_end, shape_len, step1, 0);
g_mapHs_kmer_(seq2, g_hs, gr_str, gr_end, shape_len, step2, 1);
return 0;
}
/*---------- Clip function ----------*/
/**
* stream seq creating hs
*/
int c_stream_(String<Dna5> & seq,String<uint64_t> & g_hs,
uint64_t sq_str, uint64_t sq_end, int step, int shape_len, uint64_t type)
{
if (length(seq) < unsigned(shape_len))
{
return 0;
}
LShape shape(shape_len);
hashInit_hs(shape, begin(seq) + sq_str, 0);
int count = 0;
uint64_t val = 0;
for (uint64_t k = sq_str; k < std::min(sq_end, length(seq) - shape_len); k++)
{
val = hashNext_hs(shape, begin(seq) + k);
if (++count == step) //collecting every step bases
{
//TODO: k - getT(shape)
appendValue(g_hs, g_hs_makeGhs_(val, type, 0, k));
count = 0;
}
}
return length(g_hs);
}
//using de brujin sequence to calculate the clz and ctz of 4-mers
int const clzb_4_index_[8] = {0, 0, 3, 1, 3, 2, 2, 1}; // de brujin sequence table / 2
int clzb_4__ (uint64_t a)
{
uint64_t tmp = a & ((~a) + 1);
return clzb_4_index_[(tmp - (tmp >> 4) - (tmp >> 5)) & 255];
}
short clzb_4_(uint64_t a)
{
return (a)?__builtin_clz(unsigned (a)) / 2 - 12:4;
}
short ctzb_4_(uint64_t a)
{
return (a)?__builtin_ctz(unsigned(a)) / 2:4;
}
/**
* Stream the block of 'g_hs' within [p1,p2)x[p2,k), and convert the
production of cords to anchors with the restrictions of
|candidates_anchor - 'anchor' | < band
*/
int c_createAnchorsBlocks_ (String<uint64_t> & g_hs,
String<uint64_t> & g_anchor,
int p1,
int p2,
int k,
int thd_band_level, //dx >> band_level
int thd_band_lower, //band lower bound
int64_t anchor_x,
int64_t anchor_y,
int64_t x_lower = 0, //lower bound
int64_t x_upper = 0)
{
int64_t dx_lower, dx_upper;
if (x_lower == 0 && x_upper == 0)
{
dx_lower = ~0;
dx_upper = std::numeric_limits<int64_t>::max();
//dout << "dxm" << dx_upper << "\n";
}
else
{
dx_lower = x_lower - anchor_x;
dx_upper = x_upper - anchor_x;
}
for (int i = p1; i < p2; i++)
{
int dx = g_hs_getCord(g_hs[i]) - anchor_x;
for (int j = p2; j < k; j++)
{
int dy = g_hs_getCord(g_hs[j]) - anchor_y;
int d_anchor = std::abs(dx - dy);
if (d_anchor <= std::max(std::abs(dx) >> thd_band_level, thd_band_lower)
&& dx < dx_upper && dx > dx_lower)
{
appendValue(g_anchor, c_2Anchor_(g_hs[i], g_hs[j]));
}
}
}
return length(g_anchor);
}
int c_createAnchors (String<uint64_t> & g_hs,
String<uint64_t> & g_anchors,
int g_hs_end,
int band_level,
int band_lower,
int64_t anchor_x,
int64_t anchor_y,
int64_t x_lower = 0,
int64_t x_upper = 0)
{
int p1 = 0, p2 = 0;
std::sort (begin(g_hs), end(g_hs));
for (int k = 1; k < g_hs_end; k++)
{
switch (g_hs_getXT(g_hs[k] ^ g_hs[k - 1]))
{
case 0:
break;
case 1:
p2 = k;
break;
default:
c_createAnchorsBlocks_(
g_hs, g_anchors,
p1, p2, k,
band_level, band_lower,
anchor_x, anchor_y,
x_lower, x_upper);
p1 = k;
p2 = k;
}
}
return length(g_anchors);
}
//Create anchors within the given range
int c_createAnchors2 (String<uint64_t> & g_hs,
String<uint64_t> & g_anchors,
int g_hs_end,
int64_t anchor_lower,
int64_t anchor_upper)
{
int p1 = 0, p2 = 0;
std::sort (begin(g_hs), end(g_hs));
for (int k = 1; k < g_hs_end; k++)
{
switch (g_hs_getXT(g_hs[k] ^ g_hs[k - 1]))
{
case 0:
break;
case 1:
p2 = k;
break;
default:
for (int i = p1; i < p2; i++)
{
int64_t x = g_hs_getCord(g_hs[i]);
for (int j = p2; j < k; j++)
{
int64_t y = g_hs_getCord(g_hs[j]);
if (anchor_lower <= x - y && x - y < anchor_upper)
{
appendValue(g_anchors, c_2Anchor_(g_hs[i], g_hs[j]));
}
}
}
p1 = k;
p2 = k;
}
}
return length(g_anchors);
}
/**
* []::f9
* clip by anchors
* @val1 length of match
* @val2 length of cluster
* !!todo::tune thd_exp_err thd_min_len
* ---------mmmmmmmmmm
*/
inline int64_t c_sc_(int val1,
int val2,
float thd_exp_err = 0.85)
{
float rate = (float)val1 / val2;
float thd_err1 = thd_exp_err;
float thd_err2 = thd_exp_err;
int thd_min_len1 = 10; //20
int thd_min_len2 = 10;
if (val1 > 25)
{
thd_err1 -= 0.05;
thd_err2 -= 0.15;
}
else if (val1 > 15)
{
thd_err1 += 0.05;
thd_err2 -= 0.05;
}
else
{
thd_err1 += 0.1;
thd_err2 += 0.05;
}
if (rate > thd_err1 && val1 > thd_min_len1)
{
return val1 << 2;
}
else if (rate > thd_err2 && val1 > thd_min_len2)
{
return val1 << 1;
}
else
{
return val1;
}
}
//small anchors
/**
* Clip the anchors at the end of the leftmost (-1) or rightmost (1) anchor that is well extended.
* @clip_direction: -1 gap-match; 1 match-gap
*/
int64_t c_clip_anchors_ (String<uint64_t> & anchor,
uint64_t clip_str,
uint64_t clip_end,
int shape_len,
int thd_merge1, // thd of anchor
int thd_merge1_lower,
int thd_merge2, //thd of x
int clip_direction,
int thd_clip_sc = c_sc_(25, 30),
int thd_accept_score = c_sc_(c_shape_len + 3, (c_shape_len + 3) * 2)
)
{
uint64_t gs_str = get_tile_x(clip_str);
uint64_t gr_str = get_tile_y(clip_str);
uint64_t genomeId = get_tile_id (clip_str);
uint64_t gr_strand = get_tile_strand(clip_str);
int direction = (clip_direction < 0) ? -1 : 1;
int it = 0;
int bit1 = 20;
int bit2 = g_hs_anchor_bit1 + bit1;
uint64_t mask = (1LL << bit1) - 1;
uint64_t ct_conts = 0;
appendValue(anchor, ~0);
if (length(anchor) < 1)
{
return direction > 0 ? clip_str : clip_end;
}
std::sort (begin(anchor), end(anchor));
int i_str = 0;
for (int i = 0; i < (int)length(anchor) - 1; i++)
{
if (g_hs_anchor_getY(anchor[i + 1] - anchor[i]) == 1 &&
g_hs_anchor_getStrAnchor(anchor[i + 1]) - g_hs_anchor_getStrAnchor(anchor[i])== 0)
{
ct_conts++;
}
else
{
i_str = i - ct_conts ;
uint64_t x = g_hs_anchor_getX(anchor[i_str]) - gs_str;
uint64_t y = g_hs_anchor_getY(anchor[i_str]) - gr_str;
anchor[it++] = (x << bit2) + ((ct_conts + 1) << g_hs_anchor_bit1) + y;
ct_conts = 0;
//collect continuos patterns (no gaps)
}
}
i_str = length(anchor) - 1 - ct_conts;
uint64_t x = g_hs_anchor_getX(anchor[i_str]) - gs_str;
uint64_t y = g_hs_anchor_getY(anchor[i_str]) - gr_str;
anchor[it++] = (x << bit2) + ((ct_conts + 1) << g_hs_anchor_bit1) + y;
if (it < 1)
{
return direction > 0 ? clip_str : clip_end;
}
//!NOTE::Value of anchor has been changed to := x|ct_conts|y
int64_t y1 = 0, y2 = 0;
int64_t x1 = 0, x2 = 0;
int64_t x1_end = 0, x2_end = 0;
if (direction < 0)
{
int max_score = 0;
uint64_t max_anchor = 0;
std::sort(begin(anchor), begin(anchor) + it);
for (int i = 0; i < it; i++) //extend anchor[i]
{
y1 = g_hs_anchor_getY(anchor[i]);
x1 = (anchor[i] >> bit2) & mask;
x1_end = x1 + ((anchor[i] >> bit1) & mask) + shape_len - 1;
int score = c_sc_(x1_end - x1, x1_end - x1);
int dj = 0;
for (int j = i + 1; j < it; j++)
{
//#anchor will be shrinked(overwrite anchor[j])
//if anchor[j] can be merged to the
//the chain starting from the anchor[i].
y2 = g_hs_anchor_getY(anchor[j]);
x2 = (anchor[j] >> bit2) & mask;
x2_end = x2 + ((anchor[j] >> bit1) & mask) + shape_len - 1;
int64_t da = x2 - x1 - y2 + y1;
int thd_da_accept = std::max(int(x2 - x1) >> thd_merge1,
thd_merge1_lower);
if (std::abs(da) < thd_da_accept &&
x2 - x1 < thd_merge2 &&
x1 < x2)
{
score += c_sc_(x2_end - x2, x2_end - x1_end);
y1 = y2;
x1 = x2;
x1_end = x2_end;
++dj;
}
else
{
anchor[j - dj] = anchor[j];
}
}
if (score > thd_clip_sc)
{
int64_t rslt_x = (anchor[i] >> bit2) & mask;
int64_t rslt_y = (anchor[i] & mask);
uint64_t clip = create_cord(genomeId, gs_str + rslt_x, gr_str + rslt_y, gr_strand);
return clip;
}
else if (score > max_score && score > thd_accept_score)
{
max_score = score;
max_anchor = anchor[i];
}
it -= dj;
}
if (max_score > 0)
{
int64_t rslt_x = (max_anchor >> bit2) & mask;
int64_t rslt_y = (max_anchor & mask);
uint64_t clip = create_cord(genomeId, gs_str + rslt_x, gr_str + rslt_y, gr_strand);
return clip;
}
else
{
return clip_end;
}
}
else if (direction > 0)
{
int max_score = 0;
uint64_t max_anchor = 0;
std::sort(begin(anchor), begin(anchor) + it, std::greater<uint64_t>());
for (int i = 0; i < it; ++i)
{
y1 = g_hs_anchor_getY(anchor[i]);
x1 = (anchor[i] >> bit2) & mask;
x1_end = x1 + ((anchor[i] >> bit1) & mask) + shape_len - 1;
int score = c_sc_(x1_end - x1, x1_end - x1);
int dj = 0;
for (int j = i; j < it; ++j)
{
y2 = g_hs_anchor_getY(anchor[j]);
x2 = (anchor[j] >> bit2) & mask;
x2_end = x2 + ((anchor[j] >> bit1) & mask) + shape_len - 1;
int64_t da = x2 - x1 - y2 + y1;
int thd_da_accept = std::max(int(x1 - x2) >> thd_merge1,
thd_merge1_lower);
if (std::abs(da) < thd_da_accept &&
x1 - x2_end < thd_merge2 &&
x1 > x2)
{
score += c_sc_(x2_end - x2, x2_end - x1_end);
x1 = x2;
y1 = y2;
x1_end = x2_end;
++dj;
}
else
{
anchor[j - dj] = anchor[j];
}
}
if (score > thd_clip_sc)
{
int64_t rslt_x = (anchor[i] >> bit2) & mask;
int64_t rslt_y = (anchor[i] & mask);
uint64_t clip = create_cord(genomeId, gs_str + rslt_x, gr_str + rslt_y, gr_strand);
return clip;
}
else if (score > max_score && score > thd_accept_score)
{
max_score = score;
max_anchor = anchor[i];
}
it -= dj;
}
if (max_score > 0)
{
int64_t rslt_x = (max_anchor >> bit2) & mask;
int64_t rslt_y = (max_anchor & mask);
uint64_t clip = create_cord(genomeId, gs_str + rslt_x, gr_str + rslt_y, gr_strand);
return clip;
}
else
{
return clip_str;
}
}
else
{
return clip_str;
}
}
/**
* kmer of t1 is left to t2
*/
int c_isGapMatch_(uint64_t & dv, short& t1, short & t2, short & l1, short & l2, short k)
{
/*
if (dv == 0) {
return 1; // match
}
if (t1 + l1 - k + 1 == 0){
return 2; // mismatch
}
if (t2 + l1 - k == 0 && t2 != k && l1 != k){
return 3; //del
}
if (t1 + l2 - k + 1 == 0){
return 4; //ins
}
return 0;
*/
return ((dv == 0) || (t1 + l1 - k + 1 == 0) ||
(t2 + l1 - k == 0 && t2 != k && l1 != k) || (t1 + l2 - k + 1 == 0)) ? 1 : 0;
}
/***********************<Section: extend clip*************************/
//chain compact and small anchors
//supposed to use in extendClip 5mer:step1 = 5:step2=1
int getExtendClipScore(uint64_t const & anchor1, uint64_t const & anchor2, ChainScoreParms & chn_score_parms)
{
unused(chn_score_parms);
int64_t dy = g_hs_anchor_getY(anchor1) - g_hs_anchor_getY(anchor2);
int64_t dx = g_hs_anchor_getX(anchor1) - g_hs_anchor_getX(anchor2);
if (dy <= 0 || g_hs_anchor_get_strand(anchor1 ^ anchor2)
|| ((std::abs(dx) < 3 || std::abs(dy) < 3) && dx != dy)) //abort too close dx, such as dx == 0, dy == 100;
{
return -10000;
}
int64_t thd_min_dy = 10;
int64_t da = std::abs(int64_t(g_hs_anchor_getStrAnchor(anchor2) - g_hs_anchor_getStrAnchor(anchor1)));
int64_t derr = (100 * da) / std::max({dx, dy, thd_min_dy}); // 1/100 = 0.01
int score_da;
int score_dy;
//d_err
if (da == 0)
{
score_dy = 0;
}
if (da < 2)
{
score_da = 30 + 5 * da;
}
else if (da < 5)
{
score_da = 36 + 2 * da;
}
else
{
score_da = 41 + da;
}
score_dy = dy * (12 * dy + 650) / 450;
(void)derr;
return 100 - score_dy - score_da ;
}
/*
* Simple accumlated score of counting matches, taking less computational complexity
* @shape_len : length of shape to create the @chain
* @_getX : pass getY if accumulate y
* Always accumulate from left to right, clip direction is not considerd in the function(so do not use too large kmers to avoid introduced by length of kmers).
*/
int accumulateSimpleGapScore1(String<uint64_t> & chain, String<int> & gaps_score, int shape_len, uint64_t(*_getX)(uint64_t), GapParms & gap_parms)
{
if (empty(chain))
{
return -1;
}
resize(gaps_score, length(chain), 0);
uint64_t pre_x = _getX(chain[0]);
for (int i = 1; i < (int)length(chain); i++)
{
uint64_t x_i = _getX(chain[i]);
int new_gap = int(x_i - pre_x) > shape_len ? x_i - pre_x - shape_len : 0;
gaps_score[i] += gaps_score[i - 1] + new_gap * gap_parms.int_precision;
pre_x = x_i;
}
return 0;
}
/*
* Find and Clip the chain at the breakpoint;
* Method: ds(b) = max{s(b - dx) - s(b + dx)}
* Namely clip at the point where the difference of score of two windows at the two sides of the point reaches the maximum.
*/
int clipChain_(String<uint64_t> & chain,
String<int> & gaps_score_x,
String<int> & gaps_score_y,
int direction,
bool f_clip,
uint64_t (*_get_x)(uint64_t),
uint64_t (*_get_y)(uint64_t),
GapParms & gap_parms)
{
unused(_get_x);
unused(_get_y);
if (empty(chain))
{
return -1;
}
int clip_i = isClipTowardsLeft(direction) ? - 1 : length(chain) - 1;
int clip_x1, clip_x2, clip_y1, clip_y2;
int thd_window_i_size = gap_parms.thd_ccps_window_size; //window_bps >=
//step1 * (thd_window_i_size - 1) + shape_len (when no gaps, equal)
int max_d_clip = INT_MIN;
int f_found_clip = 0;
for (int i = 1; i < (int)length(chain) - 1; i++)
{
int i_str = std::max(i - thd_window_i_size, 0);
int i_end = std::min(i + thd_window_i_size, int(length(chain) - 1));
int d1 = i - i_str;
int d2 = i_end - i;
clip_x1 = (gaps_score_x[i] - gaps_score_x[i_str]) / d1;
clip_x2 = (gaps_score_x[i_end] - gaps_score_x[i]) / d2;
clip_y1 = (gaps_score_y[i] - gaps_score_y[i_str]) / d1;
clip_y2 = (gaps_score_y[i_end] - gaps_score_y[i]) / d2;
if (isClipTowardsLeft(direction))
{
std::swap (clip_x1, clip_x2);
std::swap (clip_y1, clip_y2);
}
int d_clip = clip_x2 - clip_x1 + clip_y2 - clip_y1;
if (d_clip > max_d_clip &&
clip_x1 < gap_parms.thd_ccps_clip1_upper && clip_y1 < gap_parms.thd_ccps_clip1_upper &&
(clip_x2 > gap_parms.thd_ccps_clip2_lower || clip_y2 > gap_parms.thd_ccps_clip2_lower))
{
max_d_clip = d_clip;
clip_i = i;
f_found_clip = 1;
}
}
if (f_clip && f_found_clip)
{
if (isClipTowardsLeft(direction))
{
erase(chain, 0, clip_i + 1);
}
else
{
resize(chain, clip_i + 1);
}
}
return clip_i + 1;
}
int clipChain(String<uint64_t> & chain, int shape_len, int direction, bool f_clip, uint64_t (*_get_x)(uint64_t), uint64_t (*_get_y)(uint64_t), GapParms & gap_parms)
{
gap_parms.clipChainParms(shape_len, gap_parms.thd_err); //init clip parms
String <int> gaps_score_x;
String <int> gaps_score_y;
accumulateSimpleGapScore1(chain, gaps_score_x, shape_len, _get_x, gap_parms);
accumulateSimpleGapScore1(chain, gaps_score_y, shape_len, _get_y, gap_parms);
return clipChain_(chain, gaps_score_x, gaps_score_y, direction, f_clip, _get_x, _get_y,
gap_parms);
}
/*
* Generic function
to filter records in @chain1 that located around the records of @chain2.
* chain1 are required to be sorted by x in DESCENDING order already,
It's supposed to be the reversely sorted anchors before chaning
* chain2 are required to be sorted by x in AESCENDING order already,
It's supposed to be the sorted chain after chaining.
* @chain1 is the chain to be filtered, @chain2 is the main chain
* Record in @chain1 r1 is sticked to the largest record in @chain2 r2 and r1 > r2,
namely r1_x > r2_x;
*/
int stickMainChain(String<uint64_t> & chain1,
String<uint64_t> & chain2,
uint64_t(*getX1)(uint64_t),
uint64_t(*getY1)(uint64_t),
uint64_t(*getX2)(uint64_t),
uint64_t(*getY2)(uint64_t),
GapParms & gap_parms)
{
if (empty(chain1) || empty(chain2))
{
return 0;
}
int di = 0, jj = length(chain2) - 1;
uint64_t x1, x2 = getX2(chain2[jj]);
for (int i = 0; i < (int)length(chain1); i++)
{
x1 = getX1(chain1[i]);
if (x1 < x2)
{
for (int j = jj - 1; j >= 0; j--)
{
x2 = getX2(chain2[j]);
if (x1 >= x2)
{
jj = j;
break;
}
}
}
if (x1 < x2)//none such x2 exists in chain2 : x1 <= all in chains1
{
jj = 0; //replaced with the first element of chain2 that is the closet to x1.
}
int64_t anchor1 = x1 - getY1(chain1[i]);
int64_t anchor2 = getX2(chain2[jj]) - getY2(chain2[jj]);
if (anchor1 >= anchor2 + gap_parms.thd_smcn_danchor ||
anchor1 < anchor2 - gap_parms.thd_smcn_danchor)
{
di++;
}
else
{
chain1[i - di] = chain1[i];
}
}
resize (chain1, length(chain1) - di);
return 0;
}
/*
* Extend and clip within the range specified by @ext_str and @ext_end;
* The @tiles_str and @tiles_end are empty string to store the result
which is within ext_str<= .. <ext_end.
* Note<red>::The function uses single strand hash, thus seq2 is required to
be on the same strand of the @ext_str.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ERROR::Don't use this function cause the c_stream doesn't contain strand.
The newly inserted chain thus doesn't have strand.
*/
uint64_t extendClipRange(String<Dna5> & seq1,
String<Dna5> & seq2,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
uint64_t ext_str,
uint64_t ext_end,
int direction,
GapParms & gap_parms)
{
//ext_str = shift_tile(ext_str, -50, -50);
if (get_cord_strand(ext_str ^ ext_end))
{
return 1;
}
int thd_best_n = 2;
int shape_len = 5;// gap_parms.thd_ecr_shape_len;
int step1 = 3;
int step2 = 1;
String<uint64_t> g_hs;
String<uint64_t> g_hs_anchors;
reserve(g_hs, 1024);
reserve(g_hs_anchors, 1024);
//int64_t anchor_lower = isClipTowardsLeft(direction) ? g_hs_Cord2StrAnchor(ext_end) - 50 : g_hs_Cord2StrAnchor(ext_str) - 50;
//int64_t anchor_upper = isClipTowardsLeft(direction) ? g_hs_Cord2StrAnchor(ext_end) + 50 : g_hs_Cord2StrAnchor(ext_str) + 50;
//create_g_anchors(seq1, seq2, g_hs, g_hs_anchors, ext_str, ext_end, anchor_lower, anchor_upper, shape_len, step1, step2);
c_stream_(seq1, g_hs, get_tile_x(ext_str), get_tile_x(ext_end), step1, shape_len, 0);
c_stream_(seq2, g_hs, get_tile_y(ext_str), get_tile_y(ext_end), step2, shape_len, 1);
c_createAnchors(g_hs, g_hs_anchors, length(g_hs), 3, 50, get_tile_x(ext_str), get_tile_y(ext_str));
//g_create_anchors_(g_hs, g_hs_anchors, shape_len, anchor_lower, anchor_upper, length(seq2) - 1);
StringSet<String<uint64_t> > anchors_chains;
String<int> anchors_chains_score;
uint thd_chain_depth = 15;
uint64_t thd_chain_dx_depth = 30;
std::sort(begin(g_hs_anchors), end(g_hs_anchors), [](uint64_t & a, uint64_t & b){return g_hs_anchor_getX(a) > g_hs_anchor_getX(b);});
chainAnchorsBase(g_hs_anchors, anchors_chains, anchors_chains_score, 0, length(g_hs_anchors),
thd_chain_depth, thd_chain_dx_depth, thd_best_n, gap_parms.chn_ext_clip_metric1, &g_hs_anchor_getX);
if (empty(anchors_chains))
{
return 1;
}
//select the chain whose anchor of first (clip2right) or last tile(clip2left) is cloest to the init ext_str or ext_end as the final chain.
int closest_i = 0;
int score_i_str = 0;
int len_sum = 0;
int64_t min_da = LLMAX;
for (int i = 0; i < (int)length(anchors_chains) && !empty(anchors_chains[i]); i++)
{
uint64_t new_tile = isClipTowardsRight(direction) ? g_hs_anchor2Tile(anchors_chains[i][0]) :
g_hs_anchor2Tile(back(anchors_chains[i]));
uint64_t connect_tile = isClipTowardsRight(direction) ? ext_str : ext_end;
int64_t da = std::abs(int64_t(get_tile_x(new_tile) - get_tile_x(connect_tile) - get_tile_y(new_tile) + get_tile_y(connect_tile)));
if (da < min_da)
{
min_da = da;
closest_i = i;
score_i_str = len_sum;
}
len_sum += length(anchors_chains[i]);
}
if (min_da > gap_parms.thd_ecr_reject_da || length(anchors_chains[closest_i]) < 1)
{
return 2;
}
String<int> chain_score;
resize(chain_score, length(anchors_chains[closest_i]));
for (int i = 0; i < (int)length(anchors_chains[closest_i]); i++)
{
chain_score[i] = anchors_chains_score[score_i_str + i];
}
//insert new tiles:
//start to create new tile from the breakpoint(anchor) towards the ext_str(when clip towards right)
//or ext_end (when clip towards left);
int64_t thd_new_tile_step = gap_parms.thd_tile_size / 2;
if (isClipTowardsLeft(direction))
{
uint64_t pre_str_tile = 0;
uint64_t ext_end_y = get_tile_y(ext_end);
//int clip_i = clipChain (anchors_chains[closest_i], shape_len, direction, false, &g_hs_anchor_getX, &g_hs_anchor_getY, gap_parms);
for (int i = 0; i < (int)length(anchors_chains[closest_i]); i++)
{
uint64_t new_str_tile = g_hs_anchor2Tile(anchors_chains[closest_i][i]);
if (i == 0 || get_tile_y(new_str_tile) > get_tile_y(pre_str_tile) + thd_new_tile_step)
{
appendValue(tiles_str, new_str_tile);
if (get_tile_y(new_str_tile) + gap_parms.thd_tile_size < ext_end_y) // assure tiles_end_y < ext_end_y
{
appendValue(tiles_end, shift_tile(new_str_tile, gap_parms.thd_tile_size, gap_parms.thd_tile_size));
}
else //otherwise use the end of last anchor as the end of the tile
{
uint64_t last_end_tile = shift_tile(g_hs_anchor2Tile(back(anchors_chains[closest_i])), shape_len, shape_len);
appendValue(tiles_end, last_end_tile);
break;
}
pre_str_tile = new_str_tile;
}
}
}
else if (isClipTowardsRight(direction))
{
uint64_t pre_end_tile = 0;
uint64_t ext_str_y = get_tile_y(ext_str);
//int clip_i = clipChain (anchors_chains[closest_i], shape_len, direction, false, &g_hs_anchor_getX, &g_hs_anchor_getY, gap_parms);
for (int i = length(anchors_chains[closest_i]) - 1; i >= 0; i--)
{
uint64_t new_end_tile = shift_tile(g_hs_anchor2Tile(anchors_chains[closest_i][i]), shape_len, shape_len);
if (i == (int)length(anchors_chains[closest_i]) - 1 ||
get_tile_y(pre_end_tile) > get_tile_y(new_end_tile) + thd_new_tile_step)
{
insertValue(tiles_end, 0, new_end_tile);
if (get_tile_y(new_end_tile) >= ext_str_y + gap_parms.thd_tile_size)
{
insertValue(tiles_str, 0, shift_tile(new_end_tile, -gap_parms.thd_tile_size, -gap_parms.thd_tile_size));
}
else
{
uint64_t first_str_tile = g_hs_anchor2Tile(anchors_chains[closest_i][0]);
insertValue(tiles_str, 0, first_str_tile);
break;
}
pre_end_tile = new_end_tile;
}
}
}
//Note::red, reomve this when using create_g_anchors; c_stream negelect strand, so add strand here.
if (get_tile_strand(ext_str))
{
for (int i = 0; i < (int)length(tiles_str); i++)
{
set_tile_strand (tiles_str[i]);
set_tile_strand (tiles_end[i]);
}
}
return 0;
}
/********************************************************************/
/**
* Extend the region around the breakpoint and clip it by gapped pattern.
* The clip function is splitted into two independent functoins for
* two @clip_direction value {-1,1} to reduce branches of if and else.
*/
uint64_t c_clip_extend_( uint64_t & ex_d, // results
String<uint64_t> & hashs,
String<Dna5> & seq1,
String<Dna5> & seq2,
uint64_t extend_str,
uint64_t extend_end,
int thd_scan_radius,
int thd_error_level,
int thd_merge_anchor,
int thd_drop,
int clip_direction)
{
unused(thd_merge_anchor);
CmpInt64 g_cmpll;
int thd_init_chain_da = 10;
int thd_init_chain_num = 6;
//int thd_init_scan_radius = 20;
int thd_da_upper = 3;
int thd_da_lower = -3;
uint64_t hs_len1 = get_cord_x(extend_end) - get_cord_x(extend_str);
uint64_t hs_len2 = get_cord_y(extend_end) - get_cord_y(extend_str);
unsigned shape_len = c_shape_len3;
if (length(hashs) < hs_len1 ||
hs_len1 < shape_len ||
hs_len2 < shape_len)
{
return 1;
}
int k_str = 0;
int64_t j_str = 0;
int64_t j_end = 0;
int chain_init_len;
float drop_count = 0;
String<short> tzs; //trailing zero of each pattern
String<short> lzs; //leading zero of each pattern
String<short> chain_x;
String<short> chain_y;
Iterator<String<Dna5> >::Type it_str1 = begin(seq1) + get_cord_x(extend_str);
Iterator<String<Dna5> >::Type it_str2 = begin(seq2) + get_cord_y(extend_str);
LShape shape(shape_len);
hashInit_hs(shape, it_str1, 0);
for (int i = 0; i < (int64_t) hs_len1; i++)
{
hashs[i] = hashNext_hs(shape, it_str1 + i);
}
if (isClipTowardsLeft(clip_direction)) //-Gap-Match-
{
appendValue(chain_x, hs_len1 - 1);
appendValue(chain_y, hs_len2 - 1);
chain_init_len = length(chain_y);
hashInit_hs(shape, it_str2 + hs_len2 - shape.span, 1);
for (int64_t i = hs_len2 - shape.span; i > 0; --i) //scan the read
{
clear(tzs);
clear(lzs);
bool f_extend = false;
uint64_t hash_read = hashPre_hs(shape, it_str2 + i);
int64_t di = (hs_len2 - i) >> thd_error_level;
di = std::max((int64_t)thd_scan_radius, di);
int64_t dj = thd_scan_radius << 1;
//TODO::check boundary of j_str and j_end
g_cmpll.min(j_end, i + di) << int64_t(chain_x[k_str])
<< int64_t(hs_len2 - 1)
<< int64_t(length(hashs));
g_cmpll.max(j_str, i - di) >> int64_t(j_end - dj) >> 0 ;
if (j_str > (int)length(hashs) || j_end > (int)length(hashs))
{
return 0;
}
//TODO::check boundary of j_str and j_end
for (int64_t j = j_end; j > j_str; j--) //scan the genome
{
uint64_t dhash = hash_read ^ hashs[j];
appendValue(tzs, ctzb_4_(dhash));
appendValue(lzs, clzb_4_(dhash));
short x = j;
short y = i;
int m = j_end - j - 1;
if (m >= 0 && c_isGapMatch_(dhash, tzs[m], tzs[m + 1], lzs[m], lzs[m + 1], c_shape_len3))
{
bool f_first = true;
if (int64_t(hs_len2 - 1 - i) < (int64_t)thd_init_chain_num)
{
if (std::abs(y - x) < thd_init_chain_da)
{
appendValue(chain_x, x);
appendValue(chain_y, y);
f_extend = true;
chain_init_len = length(chain_y);
}
}
else
{
for (int k = k_str; k < (int)length(chain_y); k++)
{
short dx = chain_x[k] - x;
short dy = chain_y[k] - y;
short da = dx - dy;
if (std::abs(dy) <= (int)shape_len && f_first)
{
k_str = k;
f_first = false;
}
if (da < thd_da_upper && da > thd_da_lower)
{
appendValue(chain_x, x);
appendValue(chain_y, y);
f_extend = true;
break;
}
}
}
}
}
if (!f_extend)
{
if (++drop_count > thd_drop)
{
if ((int)length(chain_x) > chain_init_len) //!empty
{
ex_d = shift_cord(extend_str, back(chain_x), back(chain_y));
}
else
{
ex_d = extend_end;
}
return ex_d;
}
}
else
{
drop_count = std::max (drop_count - 0.5, 0.0);
}
}
}
else if (isClipTowardsRight(clip_direction)) //-Match-Gap
{
appendValue(chain_x, 0);
appendValue(chain_y, 0);
chain_init_len = length(chain_y);
hashInit_hs(shape, it_str2, 0);
for (int64_t i = 0; i < int(hs_len2 - shape.span + 1); i++) //scan the read
{
clear(tzs);
clear(lzs);
bool f_extend = false;
uint64_t hash_read = hashNext_hs(shape, it_str2 + i);
int64_t di = std::max (i >> thd_error_level, int64_t(thd_scan_radius));
int64_t dj = thd_scan_radius << 1;
g_cmpll.max(j_str, i - di) >> int64_t(chain_x[k_str]) >> 0 ;
g_cmpll.min(j_end, i + di) << int64_t(j_str + dj)
<< int64_t(hs_len2)
<< length(hashs);
if (j_str > (int64_t)length(hashs) || j_end > (int64_t)length(hashs))
{
return 0;
}
for (int64_t j = j_str; j < j_end; j++) //scan the genome
{
uint64_t dhash = hash_read ^ hashs[j];
appendValue(tzs, ctzb_4_(dhash));
appendValue(lzs, clzb_4_(dhash));
short x = j;
short y = i;
int m = j - j_str - 1;
if (m >= 0 && c_isGapMatch_(dhash, tzs[m], tzs[m + 1], lzs[m], lzs[m + 1], c_shape_len3))
{
bool f_first = true;
if (i < thd_init_chain_num)
{
if (std::abs(y - x) < thd_init_chain_da)
{
appendValue(chain_x, x);
appendValue(chain_y, y);
chain_init_len = length(chain_y);
f_extend = true;
}
}
else
{
for (int k = k_str; k < (int)length(chain_y); k++)
{
short dx = x - chain_x[k];
short dy = y - chain_y[k];
short da = dx - dy;
if (std::abs(dy) <= (int)shape_len && f_first)
{
k_str = k;
f_first = false;
}
if (da < thd_da_upper && da > thd_da_lower)
{
appendValue(chain_x, x);
appendValue(chain_y, y);
f_extend = true;
break;
}
}
}
}
}
if (!f_extend)
{
if (++drop_count > thd_drop)
{
if ((int)length(chain_x) > chain_init_len)
{
ex_d = shift_cord (extend_str, back(chain_x), back(chain_y));
return ex_d;
}
else
{
ex_d = extend_str;
return ex_d;
}
}
}
else
{
drop_count = std::max (drop_count - 0.5, 0.0);
}
}
}
return 0;
}
struct ParmClipExtend
{
int thd_min_scan_delta;
int thd_error_level;
int thd_gap_shape;
int thd_merge_anchor;
int thd_merge_drop;
};
/*
*@clip_str, @clip_end required to have the equivalent strand
*/
uint64_t c_clip_(String<Dna5> & genome,
String<Dna5> & read,
String<Dna5> & comstr, //complement revers of read
uint64_t clip_str,
uint64_t clip_end,
float thd_band_ratio,
int clip_direction = 1)
{
CmpInt64 g_cmpll;
uint64_t gs_str = get_tile_x(clip_str);
uint64_t gr_str = get_tile_y(clip_str);
uint64_t gs_end = get_tile_x(clip_end);
uint64_t gr_end = get_tile_y(clip_end);
uint64_t gr_strand = get_tile_strand(clip_str);
String<uint64_t> g_hs;
String<uint64_t> g_anchor;
reserve(g_hs, 1024);
reserve(g_anchor, 1024);
String<Dna5> & seq1 = genome;
String<Dna5> & seq2 = (gr_strand) ? comstr : read;
int band = (gs_end - gs_str) * thd_band_ratio;
///clip scaffold
//step1. extend anchor : currently aborted since the gap map is precies enough
c_stream_(seq1, g_hs, gs_str, gs_end, 1, c_shape_len, 0);
c_stream_(seq2, g_hs, gr_str, gr_end, 1, c_shape_len, 1);
//std::sort (begin(g_hs), end(g_hs));
int band_level = 3; //>>3 = /8 = * 12.5% error rate
c_createAnchors(g_hs, g_anchor, length(g_hs), band_level, band, gs_str, gr_str);
int thd_merge1 = 3;
int thd_merge1_lower = 10;
int thd_merge2 = 20;
uint64_t clip = c_clip_anchors_(g_anchor, clip_str, clip_end, c_shape_len,
thd_merge1, thd_merge1_lower, thd_merge2, clip_direction);
//uint64_t clip = (clip_direction < 0 )? clip_end : clip_str;
//step2. clip_extend gap pattern further.
int64_t extend_window = 100;
int64_t thd_ovlp_shift = 10;
int64_t thd_merge_anchor = 5;
int64_t thd_merge_drop = 6;
int64_t thd_error_level = 3; // >>3 == * 0.125
int64_t thd_scan_radius = 3; //at least scan 5 elements in the genome for each kmer in the read
int64_t dx = 0;
int64_t dy = 0;
uint64_t extend_str;
uint64_t extend_end;
int64_t shift;
if (isClipTowardsLeft (clip_direction))
{
g_cmpll.min(dx, thd_ovlp_shift) << int64_t(get_cord_x(clip_end - clip) - 1);
g_cmpll.min(dy, thd_ovlp_shift) << int64_t(get_cord_y(clip_end - clip) - 1);
extend_end = shift_cord (clip, dx, dy);
g_cmpll.min(shift, extend_window)
<< get_tile_x(extend_end - clip_str)
<< get_tile_y(extend_end - clip_str);
extend_str = shift_cord (extend_end, -shift, -shift);
}
else if (isClipTowardsRight (clip_direction))
{
g_cmpll.min(dx, thd_ovlp_shift) << int64_t(get_cord_y(clip - clip_str));
g_cmpll.min(dy, thd_ovlp_shift) << int64_t(get_cord_y(clip - clip_str));
extend_str = shift_cord(clip, -dx, -dy);
g_cmpll.min(shift, extend_window)
<< get_tile_x(clip_end - extend_str)
<< get_tile_y(clip_end - extend_str);
extend_end = shift_cord(extend_str, shift, shift);
}
else
{
extend_str = 0;
extend_end = 0;
}
c_clip_extend_(clip, g_hs, seq1, seq2, extend_str, extend_end,
thd_scan_radius, thd_error_level, thd_merge_anchor, thd_merge_drop,clip_direction);
return clip;
}
/*
* Clip exact breakpoints of the given tile at the front or end according to the clip direction.
*/
uint64_t clip_tile (String<Dna5> & seq1,
String<Dna5> & seq2,
String<Dna5> & comstr,
uint64_t tile,
int sv_flag,
int tile_size)
{
int64_t thd_max_gap_size = tile_size;
float thd_band_ratio = 0.5;
CmpInt64 g_cmpll;
uint64_t clip = EmptyClipConst;
int64_t shift;
int clip_direction;
if (sv_flag & g_sv_r)
{
g_cmpll.min(shift) << int64_t(tile_size / 2)
<< length(seq1) - 1 - get_tile_x(tile)
<< length(seq2) - 1 - get_tile_y(tile);
uint64_t clip_str = shift_tile(tile, shift, shift);
g_cmpll.min(shift, shift + thd_max_gap_size)
<< length(seq1) - 1 - get_tile_x(tile)
<< length(seq2) - 1 - get_tile_y(tile);
uint64_t clip_end = shift_tile(tile, shift, shift);
int clip_direction = 1;
clip = c_clip_ (seq1, seq2, comstr, clip_str, clip_end, thd_band_ratio, clip_direction);
//clip = clip_str;
}
else if (sv_flag & g_sv_l)
{
g_cmpll.min(shift) << tile_size / 2
<< length(seq1) - 1 - get_tile_x(tile)
<< length(seq2) - 1 - get_tile_y(tile);
uint64_t clip_end = shift_tile(tile, shift, shift);
g_cmpll.min(shift) << tile_size / 2
<< get_tile_x(tile)
<< get_tile_y(tile);
uint64_t clip_str = shift_tile(tile, -shift, -shift);
clip_direction = -1;
clip = c_clip_ (seq1, seq2, comstr, clip_str, clip_end, thd_band_ratio, clip_direction);
//clip = clip_end;
//remove_tile_sgn(clip2);
}
remove_tile_sgn(clip);
return clip;
}
/*---------- Reform tiles of gaps ----------*/
int isTilesConsecutive(uint64_t & tile1, uint64_t tile2, uint64_t thd_cord_gap)
{
return isCordsConsecutive_(tile1, tile2, thd_cord_gap);
}
/*
* @tile_str and tile_end refer to the start and end of the same tile rather than two different cords
* @thd_tile_size is the regular size of tile, 96x96 by default;
However the size of the tile specified by the @tile_str and @tile_end is allowed to be smaller than that.
*/
uint64_t reform_tile_ (String<Dna5> & seq1,
String<Dna5> & seq2,
String<Dna5> & comstr,
uint64_t & tile_str,
uint64_t & tile_end,
int sv_flag,
int thd_tile_size)
{
int f_e = is_tile_end(tile_str);
uint64_t clip = clip_tile (seq1, seq2, comstr, tile_str, sv_flag, thd_tile_size);
if (sv_flag & g_sv_r)
{
tile_end = clip;
}
else if (sv_flag & g_sv_l)
{
tile_str = clip;
}
if (f_e)
{
set_tile_end(tile_str);
set_tile_end(tile_end);
}
return clip;
}
/*
* reform, extend and clip tlies of @tiles_str[it] @tiles_end[it]
* For simplicity, only one tile is allowed to be reform: @tiles_it[it];
Hence in case of towards right, ext_str should >= @tiles_str[it] to make sure the newly reformed tile can be connectted to its predecessors
* to do:: to reform a series of tiles, add for loop to compare the newly reformed tiles with the predecessors.
*/
int reformExtendClipTile (String<Dna5> & seq1, String<Dna5> & seq2, String<Dna5> & comstr,
String<uint64_t> & tiles_str, String<uint64_t> & tiles_end,
int it, int sv_flag, GapParms gap_parms)
{
int d_it = 0;
String<uint64_t> tmp_tiles_str;
String<uint64_t> tmp_tiles_end;
String<Dna5> & read = get_tile_strand(tiles_str[it]) ? comstr : seq2;
if (sv_flag & g_sv_r)
{
uint64_t ext_str = tiles_str[it];
uint64_t ext_end = shift_tile(tiles_end[it], gap_parms.thd_tile_size, gap_parms.thd_tile_size);
extendClipRange(seq1, read, tmp_tiles_str, tmp_tiles_end, ext_str, ext_end, g_clip_rght, gap_parms);
if (!empty(tmp_tiles_str))
{
int ii = it;
while (ii>= 0 && !(ii < it && is_tile_end(tiles_str[ii]))
&& (get_tile_y(tiles_end[ii]) > get_tile_y(tmp_tiles_end[0]) ||
get_tile_x(tiles_end[ii]) > get_tile_x(tmp_tiles_end[0])))
{ii--;}
if (ii < it) //erase at least one
{
tmp_tiles_str[0] = tiles_str[ii + 1];
if (is_tile_end(tiles_str[it]))
{
set_tile_end(back(tmp_tiles_str));
set_tile_end(back(tmp_tiles_end));
}
}
//predecessor tiles_end out bound of newly clipped tiles_end.
erase(tiles_str, ii + 1, it + 1);
erase(tiles_end, ii + 1, it + 1);
insert(tiles_str, ii + 1, tmp_tiles_str);
insert(tiles_end, ii + 1, tmp_tiles_end);
d_it = length(tmp_tiles_str) - it + ii;
}
}
else if (sv_flag & g_sv_l)
{
uint64_t ext_str = shift_tile(tiles_str[it], -gap_parms.thd_tile_size, -gap_parms.thd_tile_size);
uint64_t ext_end = tiles_end[it];
extendClipRange(seq1, read, tmp_tiles_str, tmp_tiles_end, ext_str, ext_end, g_clip_left, gap_parms);
if (!empty(tmp_tiles_str))
{
int ii = it;
while (ii < (int)length(tiles_str) && !(ii > 0 && is_tile_end(tiles_str[ii - 1])) &&
(get_tile_y(tiles_str[ii]) < get_tile_y(back(tmp_tiles_str)) ||
get_tile_x(tiles_str[ii]) < get_tile_x(back(tmp_tiles_str))))
{ii++;}
if (it < ii)
{
back(tmp_tiles_end) = tiles_end[ii - 1]; //keep the tiles_end[ii]
if (is_tile_end(tiles_str[ii - 1]))
{
set_tile_end(back(tmp_tiles_str));
set_tile_end(back(tmp_tiles_end));
}
}
erase(tiles_str, it, ii);
erase(tiles_end, it, ii);
insert(tiles_str, it, tmp_tiles_str);
insert(tiles_end, it, tmp_tiles_end);
d_it = length(tmp_tiles_str) - std::min(ii - it, 1); //always points the original it, if the original it is erased then point to the last of tmp_tiles_str since the last_tmp_tiles_end is set as the original;
}
}
return d_it;
}
/**
* Scan @tiles_str[x] @tiles_end[x] of within x:[@pos_str, @pos_end) and reform if 1. head or taile, 2. gaps exists;
* When (length(tiles_str) == 1), g_map_closed is not allowed
* else the fist tile of each tile block in @tiles_str is clipped towards left only if @direction == g_map_left;
The last tile ...towards right... only if == g_map_rght;
* Others clipped towards both direction if gap exists.
* @tiles_end required to be initied with same length of @tiles_str before call the functoin
*/
int reform_tiles_(String<Dna5> & seq1,
String<Dna5> & seq2/*read*/,
String<Dna5> & comstr, //complement reverse of seq2
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
String<uint64_t> & sp_tiles, //record tiles id that needs additional process(dups).
int direction,
GapParms & gap_parms)
{
float thd_da_zero = gap_parms.thd_err;
int64_t thd_dxy_min = 80; //skip ins del < this value todo tune later
unused(thd_dxy_min);
unused(thd_da_zero);
unused(sp_tiles);
if (empty (tiles_str))
{
return 0;
}
if (length(tiles_str) == 1 && direction == g_map_closed)
{
return 1;
}
//for (int i = pos_str; i < pos_end; i++)
return 0;
for (int it = 0; it < (int)length(tiles_str); it++)
{
uint64_t thd_gap_size = gap_parms.thd_gap_len_min;
unused(thd_gap_size);
if ((it == 0 || (it > 0 && is_tile_end (tiles_str[it - 1]))) && direction == g_map_left)
{
it += reformExtendClipTile (seq1, seq2, comstr, tiles_str, tiles_end, it, g_sv_l, gap_parms);
}
/*
else if (it > 0)
{
uint64_t x11 = get_tile_x(tiles_str[it - 1]);
uint64_t y11 = get_tile_y(tiles_str[it - 1]);
uint64_t x12 = get_tile_x(tiles_end[it - 1]);
uint64_t y12 = get_tile_y(tiles_end[it - 1]);
uint64_t x21 = get_tile_x(tiles_str[it]);
uint64_t y21 = get_tile_y(tiles_str[it]);
if (!(x11 <= x21 && y11 <= y21 && x12 + thd_gap_size >= x21 && y12 + thd_gap_size >= y21 &&
!get_tile_strand(tiles_str[it - 1] ^ tiles_str[it])))
{
it += reformExtendClipTile (seq1, seq2, comstr, tiles_str, tiles_end, it - 1, g_sv_r, gap_parms);
if (is_diff_anchor (tiles_str[it - 1], tiles_str[it], 1, thd_dxy_min, thd_da_zero))
{
insertClipStr(sp_tiles, it - 1); //tiles[i - 1] and tiles[i] might be dups
insertClipEnd(sp_tiles, it);
}
it += reformExtendClipTile (seq1, seq2, comstr, tiles_str, tiles_end, it, g_sv_l, gap_parms);
//return 0;
}
}
*/
if (direction == g_map_rght && (is_tile_end(tiles_str[it]) || it == (int)length(tiles_str) - 1))
{
it += reformExtendClipTile (seq1, seq2, comstr, tiles_str, tiles_end, it, g_sv_r, gap_parms);
}
}
return 0;
}
/*
@direction == g_map_left @gap_str is ommited::will not append to tiles to be clipped
@direction == g_map_rght @gap_end is ommited::will not append to tiles to be clipped
*/
int reform_tiles(String<Dna5> & seq1,
String<Dna5> & seq2,
String<Dna5> & comstr,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
String<uint64_t> & sp_tiles,
uint64_t gap_str,
uint64_t gap_end,
int direction,
GapParms & gap_parms)
{
unused(seq1);
unused(seq2);
unused(comstr);
unused(sp_tiles);
//step.1 init tiles_str, tiles_end;
//Insert head_tile and tail tile at the front and end for each block of tiles
uint64_t head_tile = gap_str;
uint64_t tail_tile = shift_tile(gap_end, -gap_parms.thd_tile_size, -gap_parms.thd_tile_size);
if ((int64_t)get_tile_x(gap_end) > gap_parms.thd_tile_size && (int64_t)get_tile_y (gap_end) > gap_parms.thd_tile_size)
{
tail_tile = shift_tile(gap_end, -gap_parms.thd_tile_size, -gap_parms.thd_tile_size);
}
else
{
tail_tile = head_tile;
}
remove_tile_sgn(head_tile);
//remove_tile_sgn(tail_tile);
set_tile_end(tail_tile);
if (!empty(tiles_str))
{
copy_tile_sgn(back(tiles_str), tail_tile);
copy_tile_sgn(tiles_str[0], head_tile);
remove_tile_sgn(back(tiles_str));
remove_tile_sgn(tiles_str[0]);
}
if (direction != g_map_left)
{
insertValue(tiles_str, 0, head_tile);
}
if (direction != g_map_rght)
{
appendValue(tiles_str, tail_tile);
}
int64_t d = shift_tile (0ULL, gap_parms.thd_tile_size, gap_parms.thd_tile_size);
if (empty(tiles_end))
{
resize(tiles_end, length(tiles_str));
for (int i = 0; i < (int)length(tiles_str); i++)
{
tiles_end[i] = tiles_str[i] + d;
}
}
else
{
if (direction != g_map_left)
{
insertValue(tiles_end, 0, shift_tile(head_tile, gap_parms.thd_tile_size,
gap_parms.thd_tile_size));
}
if (direction != g_map_rght)
{
appendValue(tiles_end, shift_tile(tail_tile, gap_parms.thd_tile_size,
gap_parms.thd_tile_size));
}
}
//step.2 reform tiles:clip and break block if necessary
if (gap_parms.f_rfts_clip)
{
//reform_tiles_(seq1, seq2, comstr, tiles_str, tiles_end, sp_tiles, direction,
// gap_parms);
}
return 0;
}
/**
* shortcut to insert @tiles at @cords[@pos] or @cords[@pos + 1] according to the @direction
* if direction = g_map_left: erase back(@tiles) and insert(cords, @pos),
* if direction = g_map_closed erase first and last tiles then insert(cords, @pos)
* if direction = g_map_rght: erase @tiles[0] and insert(cords, @pos + 1);
* @tiles is required to have at least 2 tiles;
* @tile[0] and back(@tiles) are the clipped cords of gap_str, gap_end
* They will replace the two joint cords between which @tiles are inserted
*/
int insert_tiles2Cords_(String<uint64_t> & cords, unsigned & pos, String<uint64_t> & tiles,
int direction, int thd_max_segs_num)
{
if ((length(tiles) < 2 && direction == g_map_closed) || empty(tiles))
{
return 1;
}
int segs_num = 0;
int return_type1 = 1 << 30;
for (auto & tile : tiles)
{
if (is_tile_end(tile))
{
set_cord_end (tile);
++segs_num;
}
}
if (segs_num > thd_max_segs_num)
{
return segs_num | return_type1;
}
String<uint64_t> tmp_tiles;
if (direction == g_map_left) //insert at front of cords
{
uint64_t recd = get_cord_recd(cords[pos]);//set cord flag
set_tiles_cords_sgns (tiles, recd);
if (is_cord_block_end (cords[pos]))
{
set_cord_end (back(tiles));
}
else
{
_DefaultHit.unsetBlockEnd(back(tiles));
}
cords[pos] = back(tiles);
resize (tiles, length(tiles) - 1);
insert(cords, pos, tiles);
pos += length(tiles);
clear(tiles);
}
else if (direction == g_map_rght) //insert at end
{
uint64_t recd = get_cord_recd(cords[pos]);
set_tiles_cords_sgns (tiles, recd);
uint64_t cordtmp = cords[pos];
cords[pos] = tiles[0];
for (int i = 0; i < (int)length(tiles) - 1; i++)
{
tiles[i] = tiles[i + 1];
}
resize(tiles, length(tiles) - 1);
insert(cords, pos + 1, tiles);
pos += length(tiles);
if (is_cord_block_end(cordtmp))
{
_DefaultHit.setBlockEnd(cords[pos]);
}
else
{
_DefaultHit.unsetBlockEnd(cords[pos]);
}
clear(tiles);
}
else if (direction == g_map_closed)
{
uint64_t recd = get_cord_recd(cords[pos]);//set cord flag
set_tiles_cords_sgns (tiles, recd);
uint64_t cordtmp = cords[pos];
cords[pos - 1] = tiles[0];
cords[pos] = back(tiles);
if (is_cord_block_end(cordtmp))
{
_DefaultHit.setBlockEnd(cords[pos]);
}
else
{
_DefaultHit.unsetBlockEnd(cords[pos]);
}
for (int i = 0; i < (int)length(tiles) - 2; i++)
{
tiles[i] = tiles[i + 1];
}
resize (tiles, length(tiles) - 2);
insert(cords, pos, tiles);
pos += length(tiles);
clear(tiles);
}
return 0;
}
int insert_tiles2Cords_(String<uint64_t> & cords_str,
String<uint64_t> & cords_end,
unsigned & pos,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
int direction,
int thd_cord_size,
int thd_max_segs_num)
{
if (empty(cords_end))
{
resize (cords_end, length(cords_str));
int64_t d = shift_cord (0ULL, int64_t(thd_cord_size), int64_t(thd_cord_size));
for (int i = 0; i < (int)length(cords_str); i++)
{
cords_end[i] = cords_str[i] + d;
}
}
unsigned postmp = pos;
insert_tiles2Cords_(cords_str, pos, tiles_str, direction, thd_max_segs_num);
insert_tiles2Cords_(cords_end, postmp, tiles_end, direction, thd_max_segs_num);
return 0;
}
/********************* START: Extend mapping for INS/DEL **********************/
/* The section is the extendsion for the ins/del.
Since many ins are repeats.
This part is to customize indels.
*/
/*
* Get the overalpped regions of @chain1 and @chain2
* NOTE:Resut [pair.first, len1) of chain1, [0, pair.second) of chain2 having overlaps within the region
*/
std::pair<int, int> getExtendsIntervalChainsOverlaps(String<uint64_t> & chain1,
String<uint64_t> & chain2,
uint64_t(*getX)(uint64_t),
uint64_t(*getY)(uint64_t),
GapParms & gap_parms)
{
if (empty(chain1) || empty(chain2))
{
return std::pair<int, int>(length(chain1), 0);
}
uint64_t x2 = getX(chain2[0]);
uint64_t y2 = getY(chain2[0]);
x2 = (x2 > gap_parms.thd_dcomx_err_dx) ? x2 - gap_parms.thd_dcomx_err_dx : 0;
y2 = (y2 > gap_parms.thd_dcomx_err_dy) ? y2 - gap_parms.thd_dcomx_err_dy : 0;
int i1 = 0;
for (int i = length(chain1) - 1; i >= 0; i--)
{
if (getX(chain1[i]) < x2 && getY(chain1[i]) < y2)
{
i1 = i + 1;
break;
}
}
uint64_t x1 = getX(back(chain1)) + gap_parms.thd_dcomx_err_dx;
uint64_t y1 = getY(back(chain1)) + gap_parms.thd_dcomx_err_dy;
x1 = (gap_parms.ref_len - x1 > gap_parms.thd_dcomx_err_dx) ? x1 + gap_parms.thd_dcomx_err_dx
: gap_parms.ref_len;
y1 = (gap_parms.read_len - y1 > gap_parms.thd_dcomx_err_dy) ? y1 + gap_parms.thd_dcomx_err_dy
: gap_parms.read_len;
int i2 = length(chain2);
for (int i = 0; i < (int)length(chain2); i++)
{
if (getX(chain2[i]) > x1 && getY(chain2[i]) > y1)
{
i2 = i;
break;
}
}
return std::pair<int, int> (i1, i2);
}
/*
* Generic function
* Given @chains, map continously with smaller patterns along @chains
* @map_str, @map_end are required to be on the same strand
* @chains is on the single strand,(values of different strand of @chain aren't allowed)
* Map along @chains[i], where i within [@i_str, @i_end)
the result is written to the @tiles
*/
int mapAlongChain(String<Dna5> & seq1,
String<Dna5> & seq2,
String<uint64_t> & chains,
String<uint64_t> & tiles,
int i_str, int i_end,
int shape_len,
int step1,
int step2,
uint64_t(*getX)(uint64_t),
uint64_t(*getY)(uint64_t),
uint64_t(*getStrand)(uint64_t),
void (*setStrand) (uint64_t &),
uint64_t(*mac_chain2Tile)(uint64_t),
GapParms & gap_parms)
{
if (empty(chains) || i_str < 0 || i_end > (int)length(chains) || i_end <= i_str)
{
return -1;
}
int thd_best_n = 1;
String<uint64_t> hs;
String<uint64_t> hs_anchors;
reserve(hs, 1024);
reserve(hs_anchors, 1024);
int64_t anchor_str = getX(chains[i_str]) - getY(chains[i_str]);
int64_t anchor_end = getX(chains[i_end - 1]) - getY(chains[i_end - 1]);
c_stream_(seq1, hs, getX(chains[i_str]), getX(chains[i_end - 1]), step1, shape_len, 0);
c_stream_(seq2, hs, getY(chains[i_str]), getY(chains[i_end - 1]), step2, shape_len, 1);
c_createAnchors2(hs, hs_anchors, length(hs), std::min(anchor_str, anchor_end) - 30, std::max(anchor_str, anchor_end) + 30);
std::sort(begin(hs_anchors), end(hs_anchors), [](uint64_t & a, uint64_t & b){return g_hs_anchor_getX(a) > g_hs_anchor_getX(b);});
stickMainChain(hs_anchors, chains, &g_hs_anchor_getX, &g_hs_anchor_getY, getX, getY, gap_parms);
StringSet<String<uint64_t> > anchors_chains;
String<int> anchors_chains_score;
uint thd_chain_depth = 15;
uint64_t thd_chain_dx_depth = 30;
chainAnchorsBase(hs_anchors, anchors_chains, anchors_chains_score, 0, length(hs_anchors),
thd_chain_depth, thd_chain_dx_depth, thd_best_n, gap_parms.chn_ext_clip_metric1, &g_hs_anchor_getX);
if (!empty (anchors_chains))
{//choose the first chain
int f_strand = getStrand(chains[0]);
for (int i = 0; i < (int)length(anchors_chains[0]); i++)
{
uint64_t new_tile = mac_chain2Tile(anchors_chains[0][i]);
if (f_strand)
{
setStrand(new_tile);
}
appendValue (tiles, new_tile);
}
}
return 0;
}
/*
* Find and clip the breakpoint of two chains as ins/del.
The function keeps x of the breakpoint two chains in case of ins and y of breakpoint two chains
in case of dels closed to each other and finding the breakpoint such that the score is
maxmized.
* NOTE: getX and getY are abstract operations. Swap getX and getY to clip by y, namely call
extendsIn..laps(chain1, chain2, getY, getX): choose y as the main coordinate in case of del
*/
int __extendsIntervalClipOverlapsInsDel_(String<uint64_t> & chain1,
String<uint64_t> & chain2,
int shape_len,
int step1,
int step2,
bool f_clip,
uint64_t(*getX)(uint64_t),
uint64_t(*getY)(uint64_t),
GapParms & gap_parms)
{
unused(step1);
unused(step2);
if (empty(chain1) || empty(chain2))
{
return 0;
//return std::pair<int, int>(length(chain1), 0);
}
String<int> gaps_score11;
String<int> gaps_score12;
String<int> gaps_score21;
String<int> gaps_score22;
gap_parms.clipChainParms(shape_len, gap_parms.thd_err); //init clip parms
accumulateSimpleGapScore1(chain1, gaps_score11, shape_len, getX, gap_parms);
accumulateSimpleGapScore1(chain1, gaps_score12, shape_len, getY, gap_parms);
accumulateSimpleGapScore1(chain2, gaps_score21, shape_len, getX, gap_parms);
accumulateSimpleGapScore1(chain2, gaps_score22, shape_len, getY, gap_parms);
clipChain_(chain1, gaps_score11, gaps_score12, g_map_rght, true, getX, getY, gap_parms);
clipChain_(chain2, gaps_score21, gaps_score22, g_map_left, true, getX, getY, gap_parms);
int j1 = 0, j2 = 0, i_clip = 0, j_clip = -1;
int j1_pre = 0, j2_pre = 0;
int score11, score12, score21, score22;
int min_score = INT_MAX;
uint64_t x21 = getX(chain2[0]), x22 = getX(chain2[0]); //[x21, x22)
for (int i = 0; i < (int)length(chain1); i++)
{
uint64_t x1 = getX(chain1[i]);
uint64_t x2_lower = x1;
uint64_t x2_upper = x1 + gap_parms.thd_eicos_clip_dxy;
for (int j = j1_pre; j < (int)length(chain2) && x21 < x2_lower; j++)
{
x21 = getX(chain2[j]);
j1 = j;
}
if (x21 > x2_upper)
{
continue;
}
if (x21 < x2_lower)
{
break;
}
for (int j = j2_pre; j < (int)length(chain2) && x22 <= x2_upper; j++)
{
x22 = getX(chain2[j]);
j2 = j;
}
if (x22 < x2_lower)
{
break;
}
//x22 < x2_upper occur only when j2 == length(chain2) - 1, while this is allowed;
//x2_lower<= x21 < x2_upper, x22 >= x2_upper && != pre(newly updated)
//then search max score within [x21, x22), namely [j1, j2)
if (j1 > j_clip || j2_pre != j2)
{
//int ii1 = std::max(i - gap_parms.thd_eicos_window_size, int(0));
//int ii2 = std::min(i + gap_parms.thd_eicos_window_size, int(length(chain1) - 1));
//score11 = gaps_score11[i] - gaps_score11[ii1];
score11 = gaps_score11[i];
score12 = gaps_score12[i];
for (int j = std::max(j1, j2_pre); j < j2; j++)
{
//int jj1 = std::max(j - gap_parms.thd_eicos_window_size + 1, int(0));
//int jj2 = std::min(j + gap_parms.thd_eicos_window_size, int(length(chain2) - 1));
//score21 = gaps_score21[jj2] - gaps_score21[j];
score21 = back(gaps_score21) - gaps_score21[j];
score22 = back(gaps_score22) - gaps_score22[j];
int score_connect = int64_t(getX(chain2[j]) - getX(chain1[i])) > shape_len ? (getX(chain2[j]) - getX(chain1[i]) - shape_len) * gap_parms.int_precision : 0;
int score = score11 + score12 + score21 + score22 + score_connect;
if (score < min_score)
{
min_score = score;
i_clip = i;
j_clip = j;
}
}
}
j1_pre = j1;
j2_pre = j2;
}
if (f_clip)
{
resize(chain1, i_clip);
j_clip = j_clip < 0 ? 0 : j_clip;
erase(chain2, 0, j_clip);
//return std::pair<int, int>(i_clip, 0);
return 0;
}
else
{
//return std::pair<int, int> (i_clip, j_clip);
return 0;
}
return 0;
}
/*
* Wrapper to clip the overlaps of @chain1 and @chain2.
The method is specifically for ins and dels.
*/
int extendsIntervalClipOverlapsInsDel_(String<uint64_t> & chain1, String<uint64_t> & chain2,
int shape_len, int step1, int step2, uint64_t(*getX)(uint64_t), uint64_t(*getY)(uint64_t),
GapParms & gap_parms)
{
if (empty(chain1) && empty(chain2))
{
return 0;
}
else if (empty(chain1))
{
clipChain (chain2, shape_len, g_map_left, true, getX, getY, gap_parms);
}
else if (empty(chain2))
{
clipChain (chain1, shape_len, g_map_rght, true, getX, getY, gap_parms);
}
else
{
if (!gap_parms.thd_eicos_f_as_ins)
{
clipChain (chain1, shape_len, g_map_rght, true, getX, getY, gap_parms);
clipChain (chain2, shape_len, g_map_left, true, getX, getY, gap_parms);
}
else //clip as indel rather than dups
{
__extendsIntervalClipOverlapsInsDel_(chain1, chain2, shape_len, step1, step2, true, getX, getY, gap_parms);
}
}
return 0;
}
/*
* @direction < 0, find the record chain[i] in chain that x-x0 > dx andd y-y0> dy
Then rechain the records from chain[0] to chain[i] and clip the new chain.
*
int extendClipChainGaps(String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & chain,
int i_str,
uint64_t dx,
uint64_t dy,
int direction,
GapParms & gap_parms)
{
if (empty(chain))
{
return 0;
}
if (direction < 0) //left
{
uint64_t x0 = get_cord_x(chain[0]);
uint64_t y0 = get_cord_y(chain[0]);
for (int i = 0; i < length(chain); i++)
{
if (get_cord_x(chain[i]) - x0 >= dx &&
get_cord_y(chain[i]) - y0 >= dy)
{
extendClipChain_(ref, read, comstr, chain, 0, i, direction, gap_parms);
break;
}
}
}
else if (direction > 0)
{
uint64_t x1 = get_cord_x(back(chain));
uint64_t y1 = get_cord_y(back(chain));
for (int i = length(chain) - 1; i >= 0; i--)
{
if (get_cord_x(chain[i]) - x1 >= dx &&
get_cord_y(chain[i]) - y1 >= dy)
{
extendClipChain_(ref, read, comstr, chain, i, length(chain),
direction, gap_parms);
break;
}
}
}
return 0;
}
*/
/*
*Drop at the breakpoints of two overlapped chains as ins or dels such that the score is maximized
*@chains1 direction = right, @chains direction = left
*/
int extendsIntervalMapOverlaps_(String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & tiles1,
String<uint64_t> & tiles2,
uint64_t gap_str1,
uint64_t gap_end1,
uint64_t gap_str2,
uint64_t gap_end2,
int shape_len,
int step1,
int step2,
GapParms & gap_parms)
{
unused(gap_end1);
unused(gap_str2);
dropChainGapX(tiles1, &get_tile_x, &get_tile_y, g_map_rght, true, gap_parms);
dropChainGapX(tiles2, &get_tile_x, &get_tile_y, g_map_left, true, gap_parms);
String<uint64_t> overlap_tiles1;
String<uint64_t> overlap_tiles2;
std::pair<int, int> overlaps = getExtendsIntervalChainsOverlaps(tiles1, tiles2, &get_tile_x,
& get_tile_y, gap_parms);
if (!empty(tiles1))
{
String<Dna5> & seq2 = get_tile_strand(tiles1[0]) ? comstr : read;
mapAlongChain(ref, seq2, tiles1, overlap_tiles1, overlaps.first, length(tiles1), shape_len,
step1, step2, &get_tile_x, &get_tile_y, &get_tile_strand, &set_tile_strand,
&g_hs_anchor2Tile, gap_parms);
}
if (!empty(tiles2))
{
String<Dna5> & seq2 = get_tile_strand(tiles2[0]) ? comstr : read;
mapAlongChain(ref, seq2, tiles2, overlap_tiles2, 0, overlaps.second, shape_len, step1, step2,
&get_tile_x, &get_tile_y, &get_tile_strand, &set_tile_strand,
&g_hs_anchor2Tile, gap_parms);
}
if (get_tile_x(gap_str1) - get_tile_y(gap_str1) > get_tile_x(gap_end2) - get_tile_y(gap_end2))
{
extendsIntervalClipOverlapsInsDel_(overlap_tiles1, overlap_tiles2, shape_len, step1, step2, &get_tile_x, &get_tile_y, gap_parms); //ins, don't wrapper the shape_len here into gap_parms
}
else
{
extendsIntervalClipOverlapsInsDel_(overlap_tiles1, overlap_tiles2, shape_len, step1, step2, &get_tile_y, &get_tile_x, gap_parms); //del
}
resize(tiles1, overlaps.first);
if (!empty(overlap_tiles1))
{
append(tiles1, overlap_tiles1);
}
erase(tiles2, 0, overlaps.second);
if (!empty(overlap_tiles2))
{
insert(tiles2, 0, overlap_tiles2);
}
return 0;
}
/*
* Supposed to call in @extendsInterval()
* step1 map(create chain) for each end of the interval direction sperately
* step2 remap of the overlap of the 2 chains of different direction : extendsIntervalMapOverlaps_
* step3 clip the overlaps
* step4 create tiles along the chains
* NOTE:If clip is ins or del is according to @gap_str1, @gap_end1, @gap_str2, @gap_end2.
Hence make sure @gap_str[1/2] and @gap_end[1/2] can correctly indicate ins/del.
*/
int extendsTilesFromAnchors (String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & anchors1,
String<uint64_t> & anchors2,
String<uint64_t> & tiles_str1,
String<uint64_t> & tiles_end1,
String<uint64_t> & tiles_str2,
String<uint64_t> & tiles_end2,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2,
uint64_t gap_str1,
uint64_t gap_end1,
uint64_t gap_str2,
uint64_t gap_end2,
uint64_t read_len,
GapParms & gap_parms)
{
int original_direction = gap_parms.direction;
int direction1 = g_map_rght;
int direction2 = g_map_left;
String<uint64_t> tmp_tiles1;
String<uint64_t> tmp_tiles2;
//!map right part
gap_parms.direction = direction1;
g_CreateChainsFromAnchors_(anchors1, tmp_tiles1, gap_str1, gap_end1, read_len, gap_parms);
getClosestExtensionChain_(tmp_tiles1, gap_str1, gap_end1, true, gap_parms);
//!map left part
gap_parms.direction = direction2;
g_CreateChainsFromAnchors_(anchors2, tmp_tiles2, gap_str2, gap_end2, read_len, gap_parms);
getClosestExtensionChain_(tmp_tiles2, gap_str2, gap_end2, true, gap_parms);
//!find and clip at the common breakpoint of the left and right chains
int shape_len = gap_parms.thd_etfas_shape_len;
int step1 = gap_parms.thd_etfas_step1;
int step2 = gap_parms.thd_etfas_step2;
extendsIntervalMapOverlaps_(ref, read, comstr, tmp_tiles1, tmp_tiles2, gap_str1, gap_end1, gap_str2, gap_end2, shape_len, step1, step2, gap_parms);
g_CreateTilesFromChains_(tmp_tiles1, tiles_str1, tiles_end1, f1, f2, gap_str1, gap_end1,
0, length(tmp_tiles1), &get_tile_x, &get_tile_y, &get_tile_strand, gap_parms);
//trimTiles(tiles_str1, tiles_end1, f1, f2, gap_str1, gap_end2, read_len - 1,
// direction1, gap_parms);
g_CreateTilesFromChains_(tmp_tiles2, tiles_str2, tiles_end2, f1, f2, gap_str2, gap_end2,
0, length(tmp_tiles2), &get_tile_x, &get_tile_y, &get_tile_strand, gap_parms);
//trimTiles(tiles_str2, tiles_end2, f1, f2, gap_str1, gap_end2, read_len - 1,
// direction2, gap_parms);
gap_parms.direction = original_direction;
return 0;
}
/**
* [@gap_str, @gap_end) to create a chain of tiles to extend the
mapping area as long as possible.
* @gap_str and @gap_end should have the same strand
*/
int extendsInterval(String<Dna5> & ref, //genome
String<Dna5> & read, //read
String<Dna5> & comstr,
String<uint64_t> & tiles_str1, //results
String<uint64_t> & tiles_end1, //results
String<uint64_t> & tiles_str2, //results
String<uint64_t> & tiles_end2, //results
StringSet<FeaturesDynamic > & fts_ref,
StringSet<FeaturesDynamic > & fts_read,
uint64_t gap_str1,
uint64_t gap_end1,
uint64_t gap_str2,
uint64_t gap_end2,
GapParms & gap_parms) // extern parm
{
if (get_cord_strand (gap_str1 ^ gap_end1) || get_cord_strand (gap_str2 ^ gap_end2) || get_cord_strand (gap_str1 ^ gap_str2))
{
return 1;
}
int original_direction = gap_parms.direction;
int shape_len = gap_parms.thd_eis_shape_len;
int step1 = gap_parms.thd_eis_step1; //shape_lenseq1 pattern step
int step2 = gap_parms.thd_eis_step2; //seq2...
String<uint64_t> g_hs;
String<uint64_t> g_hs_anchors1;
String<uint64_t> g_hs_anchors2;
reserve(g_hs, 2048);
reserve(g_hs_anchors1, 2048);
reserve(g_hs_anchors2, 2048);
uint64_t id = get_cord_id(gap_str1);
uint64_t strand = get_cord_strand(gap_str1);
uint64_t x1 = std::min(get_cord_x(gap_str1), get_cord_x(gap_str2));
uint64_t y1 = std::min(get_cord_y(gap_str1), get_cord_y(gap_str2));
uint64_t x2 = std::max(get_cord_x(gap_end1), get_cord_x(gap_end1));
uint64_t y2 = std::max(get_cord_y(gap_end1), get_cord_y(gap_end2));
uint64_t stream_str = create_cord(id, x1, y1, strand);
uint64_t stream_end = create_cord(id, x2, y2, strand);
double t1 = sysTime();
g_stream_(ref, read, g_hs, stream_str, stream_end, shape_len, step1, step2, gap_parms);
t1 = sysTime() - t1;
double t2 = sysTime();
g_CreateExtendAnchorsPair_(g_hs, g_hs_anchors1, g_hs_anchors2, shape_len, length(read) - 1, gap_str1, gap_end1, gap_str2, gap_end2, gap_parms);
t2 = sysTime() - t2;
double t3 = sysTime();
extendsTilesFromAnchors(ref, read, comstr, g_hs_anchors1, g_hs_anchors2, tiles_str1,
tiles_end1, tiles_str2, tiles_end2, fts_ref, fts_read, gap_str1, gap_end1,
gap_str2, gap_end2, length(read), gap_parms);
t3 = sysTime() - t3;
//--direction = 1 part;
/*
gap_parms.direction = direction1;
mapTilesFromAnchors (g_hs_anchors1, tiles1, fts_ref, fts_read, gap_str1, gap_end1, length(read) - 1, direction1, gap_parms);
//--diection = -1 part;
gap_parms.direction = direction2;
mapTilesFromAnchors (g_hs_anchors2, tiles2, fts_ref, fts_read, gap_str2, gap_end2, length(read) - 1, direction2, gap_parms);
*/
gap_parms.direction = original_direction;
return 0;
}
/*
* Remap the chain towards one direction with shorter patterns and clip the well mapped part
@direction < 0: remap region [@chain[0], @chain[i_end]);
@direction > 0: remap region [@chain[i_str], back(@chian));
*/
int remapChainOneEnd(String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & chain,
int shape_len,
int step1,
int step2,
int remap_num,
int direction,
uint64_t (*getChainX) (uint64_t),
uint64_t (*getChainY) (uint64_t),
uint64_t (*getChainStrand) (uint64_t),
void (*setChainStrand) (uint64_t &),
uint64_t (*anchor2Chain) (uint64_t),
GapParms & gap_parms)
{
if (!direction || empty(chain))
{
return 0;
}
//dropChainGapX(chain, getChainX, getChainY, direction, true, gap_parms);
String<Dna5> & seq2 = getChainStrand(chain[0]) ? comstr : read;
String<uint64_t> remap_chain;
int i_str, i_end;
if (isClipTowardsLeft(direction))
{
i_str = std::max(0, int(length(chain) - remap_num));
i_end = length(chain);
}
else if (isClipTowardsRight(direction))
{
i_str = 0;
i_end = std::min(int(length(chain)), remap_num);
}
else
{
return 0;
}
mapAlongChain(ref, seq2, chain, remap_chain, i_str, i_end, shape_len, step1,
step2, getChainX, getChainY, getChainStrand, setChainStrand, anchor2Chain, gap_parms);
clipChain(remap_chain, shape_len, direction, true, getChainX, getChainY, gap_parms);
if (isClipTowardsLeft(direction))
{
erase(chain, 0, i_end);
if (!empty(remap_chain))
{
insert(chain, 0, remap_chain);
}
}
else if (isClipTowardsRight(direction))
{
if (!empty(remap_chain))
{
resize(chain, i_str);
append(chain, remap_chain);
}
}
return 0;
}
/*
* Wrapper to call function remapChainOneEnd at @chain[i_ptr_str] or @chain[i_ptr_end]
if direction < 0
The region [@chain[@i_ptr_str]-lower, @chain[@i_ptr_str] + upper] will be remapped.
if direction > 0
The region [@chain[@i_ptr_end]-lower, @chain[@i_ptr_end] + upper] will be remapped.
And the new chain will replace the original ones which is in the region.
* The function returns the increased length of chain after re-extending.
The return value >= -length(chain), when the chain is all erased, return value == -length(chain)
Hence i_ptr_end + reExtendChainOneSide >= -1,
Take care of out of bound of i_ptr_end == -1 when iterating
*/
int reExtendChainOneSide(String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & chain,
int i_ptr_str,
int i_ptr_end,
int lower,
int upper,
int shape_len,
int step1,
int step2,
int direction,
uint64_t (*getChainX) (uint64_t),
uint64_t (*getChainY) (uint64_t),
uint64_t (*getChainStrand) (uint64_t),
void (*setChainStrand) (uint64_t &),
uint64_t (*shiftChain)(uint64_t const &, int64_t, int64_t),
uint64_t (*anchor2Chain) (uint64_t),
GapParms & gap_parms)
{
if (empty(chain) || i_ptr_str < 0 || i_ptr_end < 0)
{
return 0;
}
int ii, i_str, i_end;
int len = length(chain);
String <uint64_t> reextend_chain;
if (isClipTowardsLeft(direction))
{
int64_t d = -std::min({int64_t(get_cord_x(chain[i_ptr_str])),
int64_t(get_tile_y(chain[i_ptr_str])),
int64_t(lower)});
for (ii = i_ptr_str; ii < i_ptr_end; ii++)
{
if (int64_t(get_tile_x(chain[ii]) - get_cord_x(chain[i_ptr_str])) >= upper)
{
break;
}
}
//ii = std::min(int(i_ptr_end - 1), ii);
resize (reextend_chain, ii - i_ptr_str + 2);
reextend_chain[0] = shiftChain(chain[i_ptr_str], d, d); //insert the lower bound to extend to
for (int i = 0; i < ii - i_ptr_str + 1; i++)
{
reextend_chain[i + 1] = chain[i_ptr_str + i];
}
i_str = i_ptr_str;
i_end = ii + 1;
}
else if (isClipTowardsRight(direction))
{
int d = std::min({int64_t(length(ref) - get_cord_x(chain[i_ptr_end]) - 1),
int64_t(length(read) - get_cord_y(chain[i_ptr_end]) - 1),
int64_t(upper)});
for (ii = i_ptr_end; ii > i_ptr_str; ii--)
{
if (int64_t(get_tile_x(chain[i_ptr_end]) - get_tile_x(chain[ii])) >= lower)
{
break;
}
}
//ii = std::min(int(length(chain)) - 1, ii);
resize (reextend_chain, i_ptr_end - ii + 2);
for (int i = 0; i < i_ptr_end - ii + 1; i++)
{
reextend_chain[i] = chain[ii + i];
}
back(reextend_chain) = shiftChain(chain[i_ptr_end], d, d);
i_str = ii;
i_end = i_ptr_end + 1;
}
else
{
(void)i_str;
(void)i_end;
return 0;
}
remapChainOneEnd(ref, read, comstr, reextend_chain, shape_len, step1, step2,
length(reextend_chain), direction,
getChainX, getChainY, getChainStrand, setChainStrand, anchor2Chain, gap_parms);
erase(chain, i_str, i_end);
insert(chain, i_str, reextend_chain);
return length(chain) - len;
}
/*
* extends tiles towards one direction
*/
int extendTilesOneSide(String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & anchors,
String<uint64_t> & tiles1,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2,
uint64_t gap_str,
uint64_t gap_end,
uint64_t read_len,
int direction,
GapParms & gap_parms)
{
int original_direction = gap_parms.direction;
String<uint64_t> chain;
gap_parms.direction = direction;
g_CreateChainsFromAnchors_(anchors, chain, gap_str, gap_end, read_len, gap_parms);
getClosestExtensionChain_(chain, gap_str, gap_end, true, gap_parms);
//!find and clip at the common breakpoint of the left and right chains
int shape_len = gap_parms.thd_etfas_shape_len;
int step1 = gap_parms.thd_etfas_step1;
int step2 = gap_parms.thd_etfas_step2;
int remap_num = 50;
remapChainOneEnd(ref, read, comstr, chain, shape_len, step1, step2, remap_num,
direction, &get_tile_x, &get_tile_y, &get_tile_strand, &set_tile_strand,
&g_hs_anchor2Tile, gap_parms);
g_CreateTilesFromChains_(chain, tiles1, f1, f2, gap_str, 0, length(chain), &get_tile_x, &
get_tile_y, &get_tile_strand, gap_parms);
trimTiles(tiles1, f1, f2, gap_str, gap_end, read_len - 1, direction, gap_parms);
gap_parms.direction = original_direction;
return 0;
}
int extendIntervalOneSide(String<Dna5> & ref, //genome
String<Dna5> & read, //read
String<Dna5> & comstr,
String<uint64_t> & tiles, //results
StringSet<FeaturesDynamic > & fts_ref,
StringSet<FeaturesDynamic > & fts_read,
uint64_t gap_str,
uint64_t gap_end,
int direction,
GapParms & gap_parms) // extern parm
{
if (get_cord_strand (gap_str ^ gap_end))
{
return 1;
}
int original_direction = gap_parms.direction;
int shape_len = gap_parms.thd_eis_shape_len;
int step1 = gap_parms.thd_eis_step1; //seq1 pattern step
int step2 = gap_parms.thd_eis_step2; //seq2...
gap_parms.direction = direction;
String<uint64_t> g_hs;
String<uint64_t> g_hs_anchors;
reserve(g_hs, 2048);
reserve(g_hs_anchors, 2048);
g_stream_(ref, read, g_hs, gap_str, gap_end, shape_len, step1, step2, gap_parms);
g_create_anchors_(g_hs, g_hs_anchors, shape_len, direction, 0, 0, length(read) - 1, gap_str, gap_end, gap_parms);
extendTilesOneSide(ref, read, comstr, g_hs_anchors, tiles, fts_ref, fts_read,
gap_str, gap_end, length(read), direction, gap_parms);
gap_parms.direction = original_direction;
return 0;
}
int mapExtendResultFilter_(String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
uint64_t gap_str, uint64_t gap_end, int direction, GapParms & gap_parms)
{
if (isClipTowardsRight(direction))
{
uint64_t pre_tile = gap_str;
for (int i = 0; i < (int)length(tiles_str); i++)
{
int64_t dy = get_cord_y(tiles_str[i]) - get_tile_y(pre_tile);
int64_t dx = get_cord_y(tiles_str[i]) - get_tile_x(pre_tile);
if (dy > gap_parms.thd_me_reject_gap || dx > gap_parms.thd_me_reject_gap)
{
erase(tiles_str, i, length(tiles_str));
if (!empty(tiles_end))
{
erase(tiles_end, i, length(tiles_end));
}
break;
}
pre_tile = tiles_str[i];
}
}
if (isClipTowardsLeft(direction))
{
uint64_t pre_tile = gap_end;
for (int i = length(tiles_str) - 1; i >= 0; i--)
{
int64_t dy = get_cord_y(pre_tile) - get_tile_y(tiles_str[i]);
int64_t dx = get_cord_y(pre_tile) - get_tile_x(tiles_str[i]);
if (dy > gap_parms.thd_me_reject_gap || dx > gap_parms.thd_me_reject_gap)
{
erase(tiles_str, 0, i + 1);
if (!empty(tiles_end))
{
erase(tiles_end, 0, i + 1);
}
break;
}
pre_tile = tiles_str[i];
}
}
return 0;
}
/*
* map from @gap_str to @gap_end if direction > 0
or from @gap_end to @gap_str if direction < 0
*/
int mapExtend(StringSet<String<Dna5> > & seqs,
String<Dna5> & read, String<Dna5> & comstr,
StringSet<FeaturesDynamic > & f1,
StringSet<FeaturesDynamic > & f2,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
uint64_t gap_str,
uint64_t gap_end,
int direction,
GapParms & gap_parms)
{
/*--Specify gap parms map extending--*/
float d_anchor_rate_origin = gap_parms.thd_gmsa_d_anchor_rate;
gap_parms.direction = direction;
gap_parms.thd_ctfas2_connect_danchor = 50;
gap_parms.thd_ctfas2_connect_dy_dx = 150;
gap_parms.f_gmsa_direction = direction;
gap_parms.thd_cts_major_limit = 3;
gap_parms.f_me_map_extend = 1;
gap_parms.thd_gmsa_d_anchor_rate = 0.25;
String <Dna5> & ref = seqs[get_cord_id(gap_str)];
String<uint64_t> sp_tiles;
//mapInterval(ref, read, comstr, tiles_str, f1, f2, gap_str, gap_end, 0, 0, direction, gap_parms);
extendIntervalOneSide(ref, read, comstr, tiles_str, f1, f2, gap_str, gap_end,
direction, gap_parms);
//filter out tiles of large gaps
mapExtendResultFilter_(tiles_str, tiles_end, gap_str, gap_end, direction, gap_parms);
if (!empty(tiles_str) && isClipTowardsRight(direction))
{
remove_tile_sgn_end(back(tiles_str));
}
reform_tiles(ref, read, comstr, tiles_str, tiles_end, sp_tiles,
gap_str, gap_end, direction, gap_parms);
gap_parms.f_me_map_extend = 0;
gap_parms.thd_gmsa_d_anchor_rate = d_anchor_rate_origin;
return 0;
}
int mapExtends(StringSet<String<Dna5> > & seqs,
String<Dna5> & read,
String<Dna5> & comstr,
StringSet<FeaturesDynamic > & f1,
StringSet<FeaturesDynamic > & f2,
String<uint64_t> & tiles_str1,
String<uint64_t> & tiles_end1,
String<uint64_t> & tiles_str2,
String<uint64_t> & tiles_end2,
uint64_t gap_str1, uint64_t gap_end1,
uint64_t gap_str2, uint64_t gap_end2,
int64_t thd_dxy_min,
GapParms & gap_parms)
{
unused(thd_dxy_min);
/*--Specify gap parms map extending--*/
gap_parms.thd_ctfas2_connect_danchor = 50;
gap_parms.thd_ctfas2_connect_dy_dx = 150;
gap_parms.thd_cts_major_limit = 3;
gap_parms.f_me_map_extend = 1;
int original_direction = gap_parms.direction;
int original_f_rfts_clip = gap_parms.f_rfts_clip;
int direction1 = g_map_rght, direction2 = g_map_left;
gap_parms.f_rfts_clip = 0; //disable clip in when reform tiles.
String<Dna5> & ref = seqs[get_cord_id(gap_str1)];
String<uint64_t> sp_tiles1;
String<uint64_t> sp_tiles2;
extendsInterval(ref, read, comstr, tiles_str1, tiles_end1, tiles_str2, tiles_end2,
f1, f2, gap_str1, gap_end1, gap_str2, gap_end2, gap_parms);
//direction = 1 part
gap_parms.direction = direction1;
mapExtendResultFilter_(tiles_str1, tiles_end1, gap_str1, gap_end1, direction1, gap_parms);
if (!empty(tiles_str1))
{
remove_tile_sgn_end(back(tiles_str1));
}
reform_tiles(ref, read, comstr, tiles_str1, tiles_end1, sp_tiles1,
gap_str1, gap_end1, direction1, gap_parms);
//<<debug
if (!empty(tiles_end1))
{
// back(tiles_end1) = shift_tile(back(tiles_end1), -95, -95);
}
//>>debug
//direction = -1 part
gap_parms.direction = direction2;
mapExtendResultFilter_(tiles_str2, tiles_end2, gap_str2, gap_end2, direction2, gap_parms);
reform_tiles(ref, read, comstr, tiles_str2, tiles_end2, sp_tiles2,
gap_str2, gap_end2, direction2, gap_parms);
//restore gap_parms
gap_parms.direction = original_direction;
gap_parms.f_rfts_clip = original_f_rfts_clip;
gap_parms.f_me_map_extend = 0;
return 0;
}
/*--------------- Map of generic type ---------------*/
/*
* Wrapper of calling reExtendChainOneSide to clip
* @extend_lower_cord, @extend_upper_cord is the bound where the chain extended to,
usually gap_str or gap_end
* In [i_ptr_str, i_ptr_end], the function is called in the closed domain
*/
int reExtendClipOneSide(String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & chain,
uint64_t extend_lower_cord,
uint64_t extend_upper_cord,
int i_ptr_str,
int i_ptr_end,
int direction,
GapParms & gap_parms)
{
if (empty(chain) || i_ptr_str < 0 || i_ptr_end < 0)
{
return 0;
}
int lower = 60, upper = 60;
int shape_len = gap_parms.thd_etfas_shape_len;
int step1 = gap_parms.thd_etfas_step1;
int step2 = gap_parms.thd_etfas_step2;
if (isClipTowardsLeft(direction))
{
int dx = get_tile_x(chain[i_ptr_str]) - get_tile_x(extend_lower_cord);
int dy = get_tile_strand(chain[i_ptr_str]) ^ get_tile_strand(extend_lower_cord) ?
get_tile_y(extend_upper_cord) - length(read) + get_tile_y(chain[i_ptr_str]) :
get_tile_y(chain[i_ptr_str]) - get_tile_y(extend_lower_cord);
lower = std::min({dx, dy, lower});
}
else if (isClipTowardsRight(direction))
{
int dx = get_tile_x(extend_upper_cord) - 1 - get_tile_x(chain[i_ptr_end]);
int dy = get_tile_strand(chain[i_ptr_end]) ^ get_tile_strand(extend_upper_cord) ?
length(read) - 1 - get_tile_y(chain[i_ptr_end]) - get_tile_y(extend_lower_cord) :
get_tile_y(extend_upper_cord) - get_tile_y(chain[i_ptr_end]);
upper = std::min({dx, dy, upper});
//dout << "luex" << lower << upper << direction << dx << dy << "\n";
}
return reExtendChainOneSide(ref, read, comstr, chain, i_ptr_str, i_ptr_end, lower, upper,
shape_len, step1, step2, direction,
&get_tile_x, &get_tile_y, &get_tile_strand, &set_tile_strand, &shift_tile,
&g_hs_anchor2Tile,
gap_parms);
}
int createTilesFromAnchors2_(String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & anchors,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2,
uint64_t gap_str,
uint64_t gap_end,
uint64_t read_len,
int direction,
GapParms & gap_parms)
{
unused(direction);
String<uint64_t> tmp_tiles;
double t1=sysTime();
g_CreateChainsFromAnchors_(anchors, tmp_tiles, gap_str, gap_end, read_len, gap_parms);
t1=sysTime() - t1;
double t2=sysTime();
int pre_i = 0;
for (int i = 0; i < (int)length(tmp_tiles); i++)
{
if (is_tile_end(tmp_tiles[i]))
{
uint64_t head_tile = tmp_tiles[pre_i];
uint64_t tail_tile = tmp_tiles[i];
i += reExtendClipOneSide(ref, read, comstr, tmp_tiles, gap_str, gap_end,
pre_i, i, -1, gap_parms);
i += reExtendClipOneSide(ref, read, comstr, tmp_tiles, gap_str, gap_end,
pre_i, i, 1, gap_parms);
if (!(empty(tmp_tiles) || pre_i < 0 || i < 0))
{
copy_tile_sgn(head_tile, tmp_tiles[pre_i]);
copy_tile_sgn(tail_tile, tmp_tiles[i]);
g_CreateTilesFromChains_(tmp_tiles, tiles_str, tiles_end, f1, f2,
gap_str, gap_end, pre_i, i + 1, &get_tile_x, &get_tile_y,
&get_tile_strand, gap_parms);
}
pre_i = i + 1;
}
else if (i < int(length(tmp_tiles) - 1) &&
get_tile_strand(tmp_tiles[i] ^ tmp_tiles[i + 1]))
{
unsigned len = length(tiles_str);
uint64_t head_tile = tmp_tiles[pre_i];
uint64_t tail_tile = tmp_tiles[i];
//<<debug
//if (!get_tile_strand(tmp_tiles[pre_i]))
//{
//>>debug
i += reExtendClipOneSide(ref, read, comstr, tmp_tiles, gap_str, gap_end,
pre_i, i, -1, gap_parms);
i += reExtendClipOneSide(ref, read, comstr, tmp_tiles, gap_str, gap_end,
pre_i, i, 1, gap_parms);
//}
if (!(empty(tmp_tiles) || pre_i < 0 || i <0))
{
copy_tile_sgn(head_tile, tmp_tiles[pre_i]);
copy_tile_sgn(tail_tile, tmp_tiles[i]);
g_CreateTilesFromChains_(tmp_tiles, tiles_str, tiles_end, f1, f2,
gap_str, gap_end, pre_i, i + 1, &get_tile_x, &get_tile_y,
&get_tile_strand, gap_parms);
if (len != length(tiles_str))
{
remove_tile_sgn_end(back(tiles_str));
remove_tile_sgn_end(back(tiles_end));
}
}
//}
pre_i = i + 1;
//<<debug
//return 0;
//>>debug
}
}
t2=sysTime() - t2;
//dout << "mp1s1" << t2 << t1 << length(anchors) << "\n";
//set_tile_end(back(tiles_str));
//set_tile_end(back(tiles_end));
return 0;
}
/**
* ~Methods function of mapGAnchor2_
* Map gaps of [gap_str, gap_end)
* Cluster anchors and trim tiles for sv
* Change thd_tile_size for differe size of window in the apx mapping
*/
int mapTilesFromAnchors (String<Dna5> & ref,
String<Dna5> & read,
String<Dna5> & comstr,
String<uint64_t> & anchors,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
StringSet<FeaturesDynamic> & f1,
StringSet<FeaturesDynamic> & f2,
uint64_t gap_str,
uint64_t gap_end,
uint64_t revscomp_const,
int direction,
GapParms & gap_parms)
{
//method 1: sort to chain anchors o(nlg(n))
//createTilesFromAnchors1_(anchor, tiles, f1, f2, gap_str, gap_end, anchor_end, thd_tile_size, thd_err_rate, thd_pattern_in_window, thd_anchor_density, thd_min_segment, gap_parms);
//method 2: dp to chain anchors o(mn) ~ o(n)
createTilesFromAnchors2_(ref, read, comstr, anchors, tiles_str, tiles_end, f1, f2, gap_str,
gap_end, revscomp_const, direction, gap_parms);
//trimTiles(tiles_str, f1, f2, gap_str, gap_end, revscomp_const, direction, gap_parms);
return 0;
}
int _createGapAnchorsList(String<uint64_t> & anchors,
String<std::pair<unsigned, unsigned> > & anchors_list,
uint64_t shape_len, uint64_t thd_anchor_accept_density, uint64_t thd_anchor_accept_min, unsigned thd_anchor_err_bit)
{
(void)shape_len;
if (length(anchors) <= 1)
{
return 0;
}
anchors[0] = 0;
uint64_t thd_1k_bit = 10;
std::sort(begin(anchors), end(anchors),
[](uint64_t & a, uint64_t & b){return g_hs_anchor_getStrAnchor(a) <
g_hs_anchor_getStrAnchor(b);});
uint64_t ak2 = anchors[1]; //2/4, 3/4
uint64_t block_str = 1, count_anchors = 0;
uint64_t min_y = ULLMAX, max_y = 0;
for (unsigned i = 1; i < length(anchors); i++)
{
uint64_t anc_y =g_hs_anchor_getY(anchors[i]);
uint64_t dy2 = std::abs(int64_t(anc_y - g_hs_anchor_getY(ak2)));
int f_continuous = (g_hs_anchor_getStrAnchor(anchors[i]) - g_hs_anchor_getStrAnchor(ak2) <
(dy2 >> thd_anchor_err_bit));
if (f_continuous)
{
//dout << "fts2" << g_hs_anchor_getStrAnchor(anchors[i]) - g_hs_anchor_getStrAnchor(ak2)
// << (dy2 >> thd_anchor_err_bit) << "\n";
if (min_y > anc_y) {
min_y = anc_y;
}
if (max_y < anc_y){
max_y = anc_y;
}
ak2 = anchors[(block_str + i) >> 1]; //update the ak to the median
++count_anchors;
}
if (!f_continuous || i == length(anchors) - 1)
{
uint64_t thd_accpet_num = std::max(((max_y - min_y) * thd_anchor_accept_density >> thd_1k_bit), thd_anchor_accept_min);
if (count_anchors > thd_accpet_num)
{ //anchors[0] is remove
appendValue(anchors_list, std::pair<unsigned, unsigned>(block_str, i));
}
block_str = i;
ak2 = anchors[i];
min_y = anc_y;
max_y = anc_y;
count_anchors = 1;
}
}
return 0;
}
/*
* The function is to filter out a part of anchors that's not likely to be chained.
The problem is the to the false negative anchors that has not been accurately
anchored in the last stage.
The simple strategy applied here is to just filter according to the size of each anchored group.
* TODO::try to apply more accurate functions of creating an filtering gap anchors.
*/
int _filterGapAnchorsList(String<uint64_t> & anchors,
String<std::pair<unsigned, unsigned> > & anchors_list,
uint64_t gap_str,
uint64_t gap_end,
int direction,
GapParms & gap_parms)
{
unused(gap_str);
unused(gap_end);
unused(direction);
unused(gap_parms);
if (empty(anchors_list))
{
return 0;
}
float thd_fgal_median = 1.5;
float thd_fgal_significant_median1 = 1.5;
unsigned thd_fgal_significant_median2 = 20;
unsigned thd_fgal_min_len1 = 1000;
unsigned thd_fgal_min_len2 = 10;
unsigned thd_fgal_max_len1 = 5;
//unsigned thd_fgal_max_rate = 0.8;
unsigned thd_fgal_max_len2 = 2000;
typedef std::pair<unsigned, unsigned> ListElemType;
std::sort (begin(anchors_list), end(anchors_list),
[](ListElemType & a, ListElemType & b){
return a.second - a.first > b.second - b.first;
});
//dout << "fgal3" << length(anchors) << length(anchors_list) << "\n";
if (length(anchors) > thd_fgal_min_len1 &&
length(anchors_list) > thd_fgal_min_len2)
{
unsigned i_median = length(anchors_list) / 2;
unsigned l_median = anchors_list[i_median].second
- anchors_list[i_median].first;
unsigned l_max = anchors_list[0].second - anchors_list[0].first;
//dout << "fgal2" << length(anchors_list) << "\n";
if (l_max > l_median * thd_fgal_significant_median1 &&
l_max > l_median + thd_fgal_significant_median2)
{
// dout << "fgal1" << length(anchors_list) << "\n";
unsigned it = 0;
uint64_t break_value = (anchors_list[i_median].second -
anchors_list[i_median].first) * thd_fgal_median;
unsigned l_s = 0;
unsigned l_i = 0;
for (unsigned i = 0;
i < std::min(thd_fgal_max_len1, unsigned(length(anchors_list))); i++)
{
it++;
l_i = anchors_list[i].second - anchors_list[i].first;
l_s += l_i;
if (l_i < break_value || l_s > thd_fgal_max_len2)
{
break;
}
}
resize(anchors_list, it);
// dout << "fgal4" << length(anchors) << length(anchors_list) << l_max << l_median << l_s << tmp << "\n";
}
else //in such case, only anchors within the bounds are stored
{
//!anchors is supossed to be already sorted by anchor in ascending order
clear(anchors_list);
/*
unsigned it = 0;
for (unsigned i = 0; i < length(anchors_list); i++)
{
unsigned i1 = anchors_list[i].first;
unsigned i2 = anchors_list[i].second;
if (g_hs_anchor_getStrAnchor(anchors[i1]) > filter_anchor_upper)
{
break;
}
if (std::max(anchor[i1], filter_anchor_lower) <
std::min(anchor[i2], filter_anchor_upper))
{
anchor_list[it] = anchor_list[i];
it++;
}
}
resize (anchor_list, it);
*/
}
}
return 0;
}
int filterGapAnchors(String<uint64_t> & anchors,
uint64_t gap_str,
uint64_t gap_end,
int direction,
GapParms & gap_parms)
{
String<std::pair<unsigned, unsigned> > anchors_list;
_createGapAnchorsList(anchors, anchors_list, uint64_t(0), uint64_t(20), uint64_t(20), unsigned(0));
//<<debug
//for (unsigned i = 0; i < length(anchors_list); i++)
//{
//dout << "cts2" << length(anchors) << anchors_list[i].first << anchors_list[i].second << gap_parms.read_id << "\n";
//}
//>>debug
_filterGapAnchorsList(anchors, anchors_list, gap_str, gap_end,
direction, gap_parms);
//>>debug
//for (unsigned i = 0; i < length(anchors_list); i++)
//{
// dout << "cts3" << length(anchors) << anchors_list[i].first << anchors_list[i].second << gap_parms.read_id << "\n";
//}
//>>debug
unsigned it = 0;
for (unsigned i = 0; i < length(anchors_list); i++)
{
for(unsigned j = anchors_list[i].first; j < anchors_list[i].second; j++)
{
anchors[it] = anchors[j];
it++;
}
}
resize (anchors, it);
return 0;
}
/**
* Map interval [@gap_str, @gap_end) to extend the
mapped region as long as possible.
* @gap_str and @gap_end should have the same strand
*/
int mapInterval(String<Dna5> & seq1, //genome
String<Dna5> & seq2, //read
String<Dna5> & comstr,
String<uint64_t> & tiles_str, //results
String<uint64_t> & tiles_end, //results
StringSet<FeaturesDynamic > & f1,
StringSet<FeaturesDynamic > & f2,
uint64_t gap_str,
uint64_t gap_end,
int64_t anchor_lower,
int64_t anchor_upper,
int direction,
GapParms & gap_parms, // extern parm
int f_filter = 0)
{
unsigned thd_mi_filter = 1000;
if (get_cord_strand (gap_str ^ gap_end))
{
return 1;
}
int shape_len = 9;
int step1 = 5; //seq1 pattern step
int step2 = 1; //seq2...
String<uint64_t> g_hs;
String<uint64_t> g_hs_anchors;
reserve(g_hs, 2048);
reserve(g_hs_anchors, 2048);
double t1 = sysTime();
g_stream_(seq1, seq2, g_hs, gap_str, gap_end, shape_len, step1, step2, gap_parms);
g_create_anchors_(g_hs, g_hs_anchors, shape_len, direction, anchor_lower, anchor_upper, length(seq2) - 1, gap_str, gap_end, gap_parms);
t1 = sysTime() - t1;
//filterGapAnchors()
//<<debug
//float anchor_density = length(anchors) / std::min(get_cord_x(gap_end) - get_cord_x(gap_str),
// get_cord_y(gap_end) - get_cord_y(gap_str));
if (length(g_hs_anchors) > thd_mi_filter && f_filter)
{
filterGapAnchors(g_hs_anchors, gap_str, gap_end, direction, gap_parms);
}
//>>debug
mapTilesFromAnchors (seq1, seq2, comstr, g_hs_anchors, tiles_str, tiles_end, f1, f2, gap_str, gap_end, length(seq2) - 1, direction, gap_parms);
//dout << "mp1" << (sysTime() - t2) << t1 << (sysTime() - t2) / t1<< "\n";
return 0;
}
/*
* Map generic gap of [@gap_str, gap_end)
* Output one best @tiles_str1 and @tiles_end1
* Map direction = 0 (closed)
*/
int mapGeneric(StringSet<String<Dna5> > & seqs,
String<Dna5> & read,
String<Dna5> & comstr,
StringSet<FeaturesDynamic > & f1,
StringSet<FeaturesDynamic > & f2,
String<uint64_t> & tiles_str,
String<uint64_t> & tiles_end,
uint64_t gap_str,
uint64_t gap_end,
GapParms & gap_parms)
{
int t_direction = 0;
uint64_t thd_gather_block_gap_size = 100; //warn::not the thd_gap_size
String<uint64_t> sp_tiles_inv;
int f_rfts_clip = gap_parms.f_rfts_clip;
gap_parms.f_rfts_clip = 0; // createTileFromaAnchors2_ in mapInterval alredy clipped chain.
mapInterval(seqs[get_tile_id(gap_str)], read, comstr, tiles_str, tiles_end, f1, f2,
gap_str, gap_end, LLMIN, LLMAX, t_direction, gap_parms, 1);
//chainTiles(tiles_str1, length(read), thd_gather_block_gap_size, gap_parms);
reform_tiles(seqs[get_tile_id(gap_str)], read, comstr, tiles_str, tiles_end,
sp_tiles_inv, gap_str, gap_end, t_direction, gap_parms);
gap_parms.f_rfts_clip = f_rfts_clip;
(void)thd_gather_block_gap_size;
return 0;
}
void unusedGlobals()
{
unused(g_thd_anchor_density);
unused((g_thd_error_percent));
unused(c_shape_len2);
unused(g_hs_bit1);
unused(g_hs_bit2);
}
| 36.736622 | 219 | 0.550998 | [
"shape"
] |
fd1b636c1a817e19f50b4ab4ebea1c2a54b30225 | 3,185 | cc | C++ | src/simplesat/cnf/cnf_or_op_test.cc | evmaus/ClusterSAT | d26ff539fe9789611e9ecd8ef5c14a19e150105b | [
"Apache-2.0"
] | null | null | null | src/simplesat/cnf/cnf_or_op_test.cc | evmaus/ClusterSAT | d26ff539fe9789611e9ecd8ef5c14a19e150105b | [
"Apache-2.0"
] | null | null | null | src/simplesat/cnf/cnf_or_op_test.cc | evmaus/ClusterSAT | d26ff539fe9789611e9ecd8ef5c14a19e150105b | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC
//
// 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 "src/simplesat/cnf/cnf_or_op.h"
#include <vector>
#include "src/simplesat/variable_environment/vector_environment.h"
#include "src/simplesat/variable_environment/linear_variable_selector.h"
#include "googletest/include/gtest/gtest.h"
namespace simplesat {
namespace cnf {
namespace {
TEST(CnfOrOp, GetTermState_TermIsSat) {
Variable v0(0);
Variable v1(1);
VectorVariableEnvironment env(2, LinearVariableSelector(2));
env.assign(0, VariableState::STRUE);
env.assign(1, VariableState::SUNBOUND);
std::vector<Variable> vars;
vars.push_back(v0);
vars.push_back(v1);
Or or_term(vars);
EXPECT_EQ(or_term.term_state(env), TermState::SAT);
}
TEST(CnfOrOp, GetTermState_TermIsUnsat) {
Variable v0(0);
Variable v1(1);
VectorVariableEnvironment env(2, LinearVariableSelector(2));
env.assign(0, VariableState::SFALSE);
env.assign(1, VariableState::SFALSE);
std::vector<Variable> vars;
vars.push_back(v0);
vars.push_back(v1);
Or or_term(vars);
EXPECT_EQ(or_term.term_state(env), TermState::UNSAT);
}
TEST(CnfOrOp, GetTermState_TermIsUnit) {
Variable v0(0);
Variable v1(1);
VectorVariableEnvironment env(2, LinearVariableSelector(2));
env.assign(0, VariableState::SFALSE);
env.assign(1, VariableState::SUNBOUND);
std::vector<Variable> vars;
vars.push_back(v0);
vars.push_back(v1);
Or or_term(vars);
EXPECT_EQ(or_term.term_state(env), TermState::UNIT);
}
TEST(CnfOrOp, GetTermState_TermIsUnresolved) {
Variable v0(0);
Variable v1(1);
VectorVariableEnvironment env(2, LinearVariableSelector(2));
env.assign(0, VariableState::SUNBOUND);
env.assign(1, VariableState::SUNBOUND);
std::vector<Variable> vars;
vars.push_back(v0);
vars.push_back(v1);
Or or_term(vars);
EXPECT_EQ(or_term.term_state(env), TermState::UNRESOLVED);
}
TEST(CnfOrOp, FirstUnassigned_AllAssigned){
Variable v0(0);
Variable v1(1);
VectorVariableEnvironment env(2, LinearVariableSelector(2));
env.assign(0, VariableState::STRUE);
env.assign(1, VariableState::SFALSE);
std::vector<Variable> vars;
vars.push_back(v0);
vars.push_back(v1);
Or or_term(vars);
EXPECT_EQ(or_term.first_unassigned(env).id(), 0);
}
TEST(CnfOrOp, FirstUnassigned){
Variable v0(0);
Variable v1(5);
VectorVariableEnvironment env(5, LinearVariableSelector(2));
env.assign(0, VariableState::STRUE);
env.assign(5, VariableState::SUNBOUND);
std::vector<Variable> vars;
vars.push_back(v0);
vars.push_back(v1);
Or or_term(vars);
EXPECT_EQ(or_term.first_unassigned(env).id(), 5);
}
} // namespace
} // namespace test
} // namespace simplesat | 29.490741 | 75 | 0.740345 | [
"vector"
] |
fd1d76c6f47a166a566f3a9b00e2f8901785394f | 945 | cpp | C++ | problemsets/UVA/UVA256.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/UVA/UVA256.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/UVA/UVA256.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int K;
while (scanf("%d", &K) != EOF) {
vector<int> ret;
int p = 1;
for (p = 0; p*p < (int)(pow(10.,K)+1E-10); p++) {
for (int i = 0; i <= p; i++) {
if ((int)(i*pow(10.,K/2)+1E-9+p-i) == p*p)
ret.push_back(p*p);
}
}
sort(ret.begin(), ret.end());
if (K == 2) for (int i = 0; i < ret.size(); i++) printf("%02d\n", ret[i]);
if (K == 4) for (int i = 0; i < ret.size(); i++) printf("%04d\n", ret[i]);
if (K == 6) for (int i = 0; i < ret.size(); i++) printf("%06d\n", ret[i]);
if (K == 8) for (int i = 0; i < ret.size(); i++) printf("%08d\n", ret[i]);
}
return 0;
}
| 26.25 | 82 | 0.45291 | [
"vector"
] |
fd29eb5d3f72293420eda3b2f99c7a1e6dd79a9a | 4,324 | cpp | C++ | ExploringScaleSymmetry/Chapter7/ch7_figure4.cpp | TGlad/ExploringScaleSymmetry | 25b2dae0279a0ac26f6bae2277d3b76a1cda8b04 | [
"MIT"
] | null | null | null | ExploringScaleSymmetry/Chapter7/ch7_figure4.cpp | TGlad/ExploringScaleSymmetry | 25b2dae0279a0ac26f6bae2277d3b76a1cda8b04 | [
"MIT"
] | null | null | null | ExploringScaleSymmetry/Chapter7/ch7_figure4.cpp | TGlad/ExploringScaleSymmetry | 25b2dae0279a0ac26f6bae2277d3b76a1cda8b04 | [
"MIT"
] | null | null | null | // Thomas Lowe, 2020.
// Generates image of scale-symmetric ocean water. It is a first order approximation of water with low amplitude and depth.
#include "stdafx.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "imagewrite.h"
#include <set>
static double seaHeight = -0.1;
static Vector3d seaBase = Vector3d(0.1, 0.25, 0.35);
static Vector3d seaWaterColour = Vector3d(0.8, 0.9, 0.6);
static const int width = 1024;
static const int height = 512;
static void putpixel(vector<BYTE> &out, const Vector2i &pos, const Vector3d &colour)
{
if (pos[0] < 0 || pos[0] >= width || pos[1] < 0 || pos[1] >= height)
return;
int ind = 3 * (pos[0] + width*(height - 1 - pos[1]));
out[ind + 0] = max(0, min((int)(255.0*colour[0]), 255));
out[ind + 1] = max(0, min((int)(255.0*colour[1]), 255));
out[ind + 2] = max(0, min((int)(255.0*colour[2]), 255));
}
static const double PI = 3.14159;
static Vector3d mix(const Vector3d &a, const Vector3d &b, double t)
{
return a + (b - a)*t;
}
static Vector3d reflect(const Vector3d &ray, const Vector3d &normal)
{
return ray - normal * 2.0*ray.dot(normal);
}
// lighting
static double diffuse(const Vector3d &n, const Vector3d &l, double p)
{
return pow(n.dot(l) * 0.4 + 0.6, p);
}
static double specular(const Vector3d &n, const Vector3d &l, const Vector3d &e, double s)
{
double nrm = (s + 8.0) / (PI * 8.0);
return pow(max(reflect(e, n).dot(l), 0.0), s) * nrm;
}
// sky
static Vector3d getSkyColor(Vector3d e)
{
e[1] = max(e[1], 0.0);
return Vector3d(pow(1.0 - e[1]*0.4, 2.0), 1.0 - e[1]*0.4, 0.8 + (1.0 - e[1])*0.2);
}
// Some approximations of reflections, refractions and the Fresnel reflectivity term.
static Vector3d getSeaColour(const Vector3d &p, const Vector3d &n, const Vector3d &l, const Vector3d &eye, const Vector3d &dist)
{
double fresnel = max(0.0, min(1.0 - n.dot(-eye), 1.0));
fresnel = pow(fresnel, 2.0) * 1.0;
Vector3d reflected = getSkyColor(reflect(eye, n));
Vector3d refracted = seaBase + diffuse(n, l, 80.0) * seaWaterColour * 0.12;
Vector3d color = mix(refracted, reflected, fresnel);
double atten = max(1.0 - dist.dot(dist) * 0.001, 0.0);
color += seaWaterColour * max(0.0, (p[1] - seaHeight)) * 0.18 * atten;
double s = specular(n, l, eye, 60.0);
color += Vector3d(s,s,s);
return color;
}
int chapter7Figure4()
{
vector<BYTE> out(width*height * 3); // .bmp pixel buffer
memset(&out[0], 255, out.size() * sizeof(BYTE));
Vector3d camPos(0.2, -2.0, 1.0);
Vector3d dir = Vector3d(-0.05, 0, -0.2) - camPos;
dir.normalize();
Vector3d side = Vector3d(0, 0, -1).cross(dir).normalized();
Vector3d up = side.cross(dir);
double time = 7.3;
double scaler = 0.5;
for (double y = 1.0; y >= -1.0; y -= 0.0008)
{
for (double x = -1.0; x <= 1.0; x += 0.001)
{
double amp = 0.3;
double wavelength = 1.0;
double yaw = 0.25;
double h = 0;
Vector2d grad(0, 0);
for (int i = 0; i < 10; i++)
{
double ang = -0.25*pi + 0.5*pi*yaw; // this keeps the wave direction within a 90 degree window, to mimic wind-driven waves
Vector2d waveDir(sin(ang), cos(ang));
double phase = (x*waveDir[0] + y*waveDir[1] + time) / wavelength;
h += amp*sin(phase);
grad += waveDir * amp * cos(phase) / wavelength;
amp *= scaler;
wavelength *= scaler;
yaw = fmod(yaw + 1.618, 1.0); // rather than actual random wave directions, I add an irrational number each time, to avoid clustering
}
// convert the point to screen space
Vector3d pos(x, y, h);
pos -= camPos;
Vector3d viewPos;
viewPos[0] = pos.dot(side);
viewPos[1] = pos.dot(dir);
viewPos[2] = pos.dot(up);
Vector2d screenPos = Vector2d(viewPos[0] / viewPos[1], viewPos[2] / viewPos[1]) * (double)width / 1.5;
screenPos += Vector2d(width / 2, height / 2);
// lighting
Vector3d normal = Vector3d(-grad[0], -grad[1], 1.0).normalized();
Vector3d ray = pos.normalized();
Vector3d sun = Vector3d(0.0, 2.0, 1.6).normalized();
Vector3d colour = getSeaColour(Vector3d(x,y,h), normal, sun, ray, pos);
putpixel(out, Vector2i(screenPos[0], screenPos[1]), colour);
}
}
stbi_write_png("ocean_water.png", width, height, 3, &out[0], 3 * width);
return 0;
}
| 31.562044 | 141 | 0.616096 | [
"vector"
] |
fd2ba22309ff66d5ffd2b6d1348d114c5dd8a0cf | 4,616 | cpp | C++ | Plugins/RPRPlugin/Source/RPRTools/Private/Helpers/RPRLightHelpers.cpp | hi-ro-no/RadeonProRenderUE | dcbf2b6df80b104c6cd2994e047f5d2fef98f493 | [
"Apache-2.0"
] | 15 | 2020-05-13T17:23:40.000Z | 2022-01-08T04:19:42.000Z | Plugins/RPRPlugin/Source/RPRTools/Private/Helpers/RPRLightHelpers.cpp | hi-ro-no/RadeonProRenderUE | dcbf2b6df80b104c6cd2994e047f5d2fef98f493 | [
"Apache-2.0"
] | 12 | 2020-05-17T08:06:45.000Z | 2021-12-20T18:07:59.000Z | Plugins/RPRPlugin/Source/RPRTools/Private/Helpers/RPRLightHelpers.cpp | hi-ro-no/RadeonProRenderUE | dcbf2b6df80b104c6cd2994e047f5d2fef98f493 | [
"Apache-2.0"
] | 7 | 2020-05-15T16:07:44.000Z | 2021-07-14T08:38:54.000Z | /*************************************************************************
* Copyright 2020 Advanced Micro Devices
*
* 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 "Helpers/RPRLightHelpers.h"
#include "RadeonProRender.h"
#include "Helpers/GenericGetInfo.h"
namespace RPR
{
namespace Light
{
template<typename T>
RPR::FResult GetInfoNoAlloc(RPR::FLight Light, RPR::ELightInfo Info, T& OutValue)
{
return RPR::Generic::GetInfoNoAlloc(rprLightGetInfo, Light, Info, &OutValue);
}
template<typename T>
RPR::FResult GetInfoToArray(RPR::FLight Light, RPR::ELightInfo Info, TArray<T>& OutValue)
{
return RPR::Generic::GetInfoToArray(rprLightGetInfo, Light, Info, OutValue);
}
//////////////////////////////////////////////////////////////////////////
RPR::FResult GetName(RPR::FLight Light, FString& OutObjectName)
{
return RPR::Generic::GetObjectName(rprLightGetInfo, Light, OutObjectName);
}
FString GetName(RPR::FLight Light)
{
FString name;
RPR::FResult status = GetName(Light, name);
if (RPR::IsResultFailed(status))
{
name = TEXT("[Unknown]");
}
if (name.IsEmpty())
{
name = TEXT("[Undefined]");
}
return (name);
}
RPR::FResult GetWorldTransform(RPR::FLight Light, FTransform& OutTransform)
{
return RPR::Generic::GetObjectTransform(rprLightGetInfo, Light, ELightInfo::Transform, OutTransform);
}
RPR::FResult SetWorldTransform(RPR::FLight Light, FTransform Transform)
{
RadeonProRender::matrix matrix = BuildMatrixWithScale(Transform);
RPR::FResult status = rprLightSetTransform(Light, RPR_TRUE, &matrix.m00);
UE_LOG(LogRPRTools_Step, Verbose,
TEXT("rprLightSetTransform(light=%s, tranpose=true, matrix=%s) -> %d"),
*RPR::Light::GetName(Light),
*Transform.ToString(),
status
);
return status;
}
RPR::FResult GetLightType(RPR::FLight Light, RPR::ELightType& OutLightType)
{
return GetInfoNoAlloc(Light, ELightInfo::Type, OutLightType);
}
bool IsLightPowerSupportedByLightType(RPR::ELightType LightType)
{
switch (LightType)
{
case ELightType::Point:
case ELightType::Directional:
case ELightType::Spot:
case ELightType::IES:
return true;
default:
return false;
}
}
RPR::FResult GetLightPower(RPR::FLight Light, RPR::ELightType LightType, FLinearColor& OutColor)
{
ELightInfo lightInfoType;
bool isLightInfoSupported = true;
switch (LightType)
{
case ELightType::Point:
lightInfoType = ELightInfo::PointLight_RadiantPower;
break;
case ELightType::Directional:
lightInfoType = ELightInfo::DirectionalLight_RadiantPower;
break;
case ELightType::Spot:
lightInfoType = ELightInfo::SpotLight_RadiantPower;
break;
case ELightType::IES:
lightInfoType = ELightInfo::IES_RadiantPower;
break;
default:
isLightInfoSupported = false;
lightInfoType = (ELightInfo) 0x0;
break;
}
if (isLightInfoSupported)
{
return GetInfoNoAlloc(Light, lightInfoType, OutColor);
}
return (RPR_ERROR_UNSUPPORTED);
}
RPR::FResult GetLightConeShape(RPR::FLight Light, float& OutInnerAngle, float& OutOuterAngle)
{
FVector2D values;
RPR::FResult status = GetInfoNoAlloc(Light, ELightInfo::SpotLight_ConeShape, values);
if (RPR::IsResultSuccess(status))
{
OutInnerAngle = values[0];
OutOuterAngle = values[1];
}
return status;
}
RPR::FResult GetEnvironmentLightIntensityScale(RPR::FLight Light, float& OutLightIntensityScale)
{
return GetInfoNoAlloc(Light, ELightInfo::Environment_LightIntensityScale, OutLightIntensityScale);
}
RPR::FResult GetEnvironmentLightImage(RPR::FLight Light, RPR::FImage& OutImage)
{
return GetInfoNoAlloc(Light, ELightInfo::Environment_Image, OutImage);
}
RPR::FResult GetDirectionalShadowSoftness(RPR::FLight Light, float& OutShadowSoftness)
{
return GetInfoNoAlloc(Light, ELightInfo::DirectionalLight_ShadowSoftness, OutShadowSoftness);
}
} // namespace Light
} // namespace RPR
| 27.47619 | 104 | 0.685659 | [
"transform"
] |
fd365828b71382eb31c59822121b4ccd7941e523 | 1,793 | hpp | C++ | etl/_type_traits/aligned_union.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | 4 | 2021-11-28T08:48:11.000Z | 2021-12-14T09:53:51.000Z | etl/_type_traits/aligned_union.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | null | null | null | etl/_type_traits/aligned_union.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | null | null | null | /// \copyright Tobias Hienzsch 2019-2021
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
#ifndef TETL_TYPE_TRAITS_ALIGNED_UNION_HPP
#define TETL_TYPE_TRAITS_ALIGNED_UNION_HPP
#include "etl/_cstddef/size_t.hpp"
namespace etl {
namespace detail {
template <typename T>
[[nodiscard]] constexpr auto vmax(T val) -> T
{
return val;
}
template <typename T0, typename T1, typename... Ts>
[[nodiscard]] constexpr auto vmax(T0 val1, T1 val2, Ts... vs) -> T0
{
return (val1 > val2) ? vmax(val1, vs...) : vmax(val2, vs...);
}
} // namespace detail
/// \brief Provides the nested type type, which is a trivial standard-layout
/// type of a size and alignment suitable for use as uninitialized storage for
/// an object of any of the types listed in Types. The size of the storage is at
/// least Len. aligned_union also determines the strictest (largest) alignment
/// requirement among all Types and makes it available as the constant
/// alignment_value. If sizeof...(Types) == 0 or if any of the types in Types is
/// not a complete object type, the behavior is undefined. It is
/// implementation-defined whether any extended alignment is supported. The
/// behavior of a program that adds specializations for aligned_union is
/// undefined.
template <etl::size_t Len, typename... Types>
struct aligned_union {
static constexpr etl::size_t alignment_value = detail::vmax(alignof(Types)...);
struct type {
alignas(alignment_value) char storage[detail::vmax(Len, sizeof(Types)...)];
};
};
template <etl::size_t Len, typename... Types>
using aligned_union_t = typename etl::aligned_union<Len, Types...>::type;
} // namespace etl
#endif // TETL_TYPE_TRAITS_ALIGNED_UNION_HPP | 35.86 | 83 | 0.732292 | [
"object"
] |
fd378e214f14d724454167bcf11cb5ceeb01ef41 | 1,355 | cpp | C++ | 469_identical-binary-tree/identical-binary-tree.cpp | piguin/lintcode | 382e0880f82480eb8153041e78c297dbaeb4b9ea | [
"CC0-1.0"
] | null | null | null | 469_identical-binary-tree/identical-binary-tree.cpp | piguin/lintcode | 382e0880f82480eb8153041e78c297dbaeb4b9ea | [
"CC0-1.0"
] | null | null | null | 469_identical-binary-tree/identical-binary-tree.cpp | piguin/lintcode | 382e0880f82480eb8153041e78c297dbaeb4b9ea | [
"CC0-1.0"
] | null | null | null | /*
@Copyright:LintCode
@Author: qili
@Problem: http://www.lintcode.com/problem/identical-binary-tree
@Language: C++
@Datetime: 16-07-30 03:58
*/
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @aaram a, b, the root of binary trees.
* @return true if they are identical, or false.
*/
bool isIdentical(TreeNode* a, TreeNode* b) {
vector<TreeNode *> path1;
vector<TreeNode *> path2;
TreeNode *p = a;
TreeNode *q = b;
while (p != NULL || path1.size() != 0) {
if (p == NULL) {
if (q != NULL) return false;
p = path1.back()->right;
path1.pop_back();
q = path2.back()->right;
path2.pop_back();
continue;
}
if (q == NULL || p->val != q->val) return false;
path1.push_back(p);
path2.push_back(q);
p = p->left;
q = q->left;
}
return q == NULL && path2.size() == 0;
}
}; | 24.636364 | 64 | 0.42952 | [
"vector"
] |
fd3d21312576830e98929d501c411935f637df0b | 1,378 | cpp | C++ | Pyre/src/Pyre/Core/Log.cpp | wexaris/pyre | 9f4c1e64a2eeffd11f09ba9396d44c8b7e70f2b4 | [
"Apache-2.0"
] | null | null | null | Pyre/src/Pyre/Core/Log.cpp | wexaris/pyre | 9f4c1e64a2eeffd11f09ba9396d44c8b7e70f2b4 | [
"Apache-2.0"
] | null | null | null | Pyre/src/Pyre/Core/Log.cpp | wexaris/pyre | 9f4c1e64a2eeffd11f09ba9396d44c8b7e70f2b4 | [
"Apache-2.0"
] | null | null | null | #include "pyrepch.hpp"
#include "Pyre/Core/Log.hpp"
#include "Pyre/ImGui/ImGuiConsole.hpp"
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
namespace Pyre {
Ref<spdlog::logger> Log::s_CoreLogger;
Ref<spdlog::logger> Log::s_ClientLogger;
void Log::Init(const std::string& path) {
// Create sinks
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<ImGuiConsole_mt>()); // ImGui console
sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); // VS debug console
sinks.push_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>(path, true)); // log file
sinks[0]->set_pattern("%^[%T] %n: %v%$");
sinks[1]->set_pattern("%^[%T] %n: %v%$");
sinks[2]->set_pattern("[%T] [%1] %n: %v");
// Create loggers
s_CoreLogger = std::make_shared<spdlog::logger>("PYRE", sinks.begin(), sinks.end());
spdlog::register_logger(s_CoreLogger);
s_CoreLogger->set_level(spdlog::level::trace);
s_CoreLogger->flush_on(spdlog::level::trace);
s_ClientLogger = std::make_shared<spdlog::logger>("APP", sinks.begin(), sinks.end());
spdlog::register_logger(s_ClientLogger);
s_ClientLogger->set_level(spdlog::level::trace);
s_ClientLogger->flush_on(spdlog::level::trace);
}
} | 38.277778 | 101 | 0.650218 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.